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
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
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
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/Core/Portable/ReferenceManager/AssemblyDataForAssemblyBeingBuilt.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 Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class CommonReferenceManager<TCompilation, TAssemblySymbol> { protected sealed class AssemblyDataForAssemblyBeingBuilt : AssemblyData { private readonly AssemblyIdentity _assemblyIdentity; // assemblies referenced directly by the assembly: private readonly ImmutableArray<AssemblyData> _referencedAssemblyData; // all referenced assembly names including assemblies referenced by modules: private readonly ImmutableArray<AssemblyIdentity> _referencedAssemblies; public AssemblyDataForAssemblyBeingBuilt( AssemblyIdentity identity, ImmutableArray<AssemblyData> referencedAssemblyData, ImmutableArray<PEModule> modules) { Debug.Assert(identity != null); Debug.Assert(!referencedAssemblyData.IsDefault); _assemblyIdentity = identity; _referencedAssemblyData = referencedAssemblyData; var refs = ArrayBuilder<AssemblyIdentity>.GetInstance(referencedAssemblyData.Length + modules.Length); //approximate size foreach (AssemblyData data in referencedAssemblyData) { refs.Add(data.Identity); } // add assembly names from modules: for (int i = 1; i <= modules.Length; i++) { refs.AddRange(modules[i - 1].ReferencedAssemblies); } _referencedAssemblies = refs.ToImmutableAndFree(); } public override AssemblyIdentity Identity { get { return _assemblyIdentity; } } public override ImmutableArray<AssemblyIdentity> AssemblyReferences { get { return _referencedAssemblies; } } public override IEnumerable<TAssemblySymbol> AvailableSymbols { get { throw ExceptionUtilities.Unreachable; } } public override AssemblyReferenceBinding[] BindAssemblyReferences( ImmutableArray<AssemblyData> assemblies, AssemblyIdentityComparer assemblyIdentityComparer) { var boundReferences = new AssemblyReferenceBinding[_referencedAssemblies.Length]; for (int i = 0; i < _referencedAssemblyData.Length; i++) { Debug.Assert(ReferenceEquals(_referencedAssemblyData[i], assemblies[i + 1])); boundReferences[i] = new AssemblyReferenceBinding(assemblies[i + 1].Identity, i + 1); } // references from added modules shouldn't resolve against the assembly being built (definition #0) const int definitionStartIndex = 1; // resolve references coming from linked modules: for (int i = _referencedAssemblyData.Length; i < _referencedAssemblies.Length; i++) { boundReferences[i] = ResolveReferencedAssembly( _referencedAssemblies[i], assemblies, definitionStartIndex, assemblyIdentityComparer); } return boundReferences; } public override bool IsMatchingAssembly(TAssemblySymbol? assembly) { throw ExceptionUtilities.Unreachable; } public override bool ContainsNoPiaLocalTypes { get { throw ExceptionUtilities.Unreachable; } } public override bool IsLinked { get { return false; } } public override bool DeclaresTheObjectClass { get { return false; } } public override Compilation? SourceCompilation => null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class CommonReferenceManager<TCompilation, TAssemblySymbol> { protected sealed class AssemblyDataForAssemblyBeingBuilt : AssemblyData { private readonly AssemblyIdentity _assemblyIdentity; // assemblies referenced directly by the assembly: private readonly ImmutableArray<AssemblyData> _referencedAssemblyData; // all referenced assembly names including assemblies referenced by modules: private readonly ImmutableArray<AssemblyIdentity> _referencedAssemblies; public AssemblyDataForAssemblyBeingBuilt( AssemblyIdentity identity, ImmutableArray<AssemblyData> referencedAssemblyData, ImmutableArray<PEModule> modules) { Debug.Assert(identity != null); Debug.Assert(!referencedAssemblyData.IsDefault); _assemblyIdentity = identity; _referencedAssemblyData = referencedAssemblyData; var refs = ArrayBuilder<AssemblyIdentity>.GetInstance(referencedAssemblyData.Length + modules.Length); //approximate size foreach (AssemblyData data in referencedAssemblyData) { refs.Add(data.Identity); } // add assembly names from modules: for (int i = 1; i <= modules.Length; i++) { refs.AddRange(modules[i - 1].ReferencedAssemblies); } _referencedAssemblies = refs.ToImmutableAndFree(); } public override AssemblyIdentity Identity { get { return _assemblyIdentity; } } public override ImmutableArray<AssemblyIdentity> AssemblyReferences { get { return _referencedAssemblies; } } public override IEnumerable<TAssemblySymbol> AvailableSymbols { get { throw ExceptionUtilities.Unreachable; } } public override AssemblyReferenceBinding[] BindAssemblyReferences( ImmutableArray<AssemblyData> assemblies, AssemblyIdentityComparer assemblyIdentityComparer) { var boundReferences = new AssemblyReferenceBinding[_referencedAssemblies.Length]; for (int i = 0; i < _referencedAssemblyData.Length; i++) { Debug.Assert(ReferenceEquals(_referencedAssemblyData[i], assemblies[i + 1])); boundReferences[i] = new AssemblyReferenceBinding(assemblies[i + 1].Identity, i + 1); } // references from added modules shouldn't resolve against the assembly being built (definition #0) const int definitionStartIndex = 1; // resolve references coming from linked modules: for (int i = _referencedAssemblyData.Length; i < _referencedAssemblies.Length; i++) { boundReferences[i] = ResolveReferencedAssembly( _referencedAssemblies[i], assemblies, definitionStartIndex, assemblyIdentityComparer); } return boundReferences; } public override bool IsMatchingAssembly(TAssemblySymbol? assembly) { throw ExceptionUtilities.Unreachable; } public override bool ContainsNoPiaLocalTypes { get { throw ExceptionUtilities.Unreachable; } } public override bool IsLinked { get { return false; } } public override bool DeclaresTheObjectClass { get { return false; } } public override Compilation? SourceCompilation => null; } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalyzerConfigOptionsProvider.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.Diagnostics { /// <summary> /// Provide options from an analyzer config file keyed on a source file. /// </summary> public abstract class AnalyzerConfigOptionsProvider { /// <summary> /// Gets global options that do not apply to any specific file /// </summary> public abstract AnalyzerConfigOptions GlobalOptions { get; } /// <summary> /// Get options for a given <paramref name="tree"/>. /// </summary> public abstract AnalyzerConfigOptions GetOptions(SyntaxTree tree); /// <summary> /// Get options for a given <see cref="AdditionalText"/> /// </summary> public abstract AnalyzerConfigOptions GetOptions(AdditionalText textFile); } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics { /// <summary> /// Provide options from an analyzer config file keyed on a source file. /// </summary> public abstract class AnalyzerConfigOptionsProvider { /// <summary> /// Gets global options that do not apply to any specific file /// </summary> public abstract AnalyzerConfigOptions GlobalOptions { get; } /// <summary> /// Get options for a given <paramref name="tree"/>. /// </summary> public abstract AnalyzerConfigOptions GetOptions(SyntaxTree tree); /// <summary> /// Get options for a given <see cref="AdditionalText"/> /// </summary> public abstract AnalyzerConfigOptions GetOptions(AdditionalText textFile); } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/Core/Portable/Operations/UnaryOperatorKind.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.Operations { /// <summary> /// Kind of unary operator /// </summary> public enum UnaryOperatorKind { /// <summary> /// Represents unknown or error operator kind. /// </summary> None = 0x0, /// <summary> /// Represents the C# '~' operator. /// </summary> BitwiseNegation = 0x1, /// <summary> /// Represents the C# '!' operator and VB 'Not' operator. /// </summary> Not = 0x2, /// <summary> /// Represents the unary '+' operator. /// </summary> Plus = 0x3, /// <summary> /// Represents the unary '-' operator. /// </summary> Minus = 0x4, /// <summary> /// Represents the C# 'true' operator and VB 'IsTrue' operator. /// </summary> True = 0x5, /// <summary> /// Represents the C# 'false' operator and VB 'IsFalse' operator. /// </summary> False = 0x6, /// <summary> /// Represents the C# '^' operator. /// </summary> Hat = 0x7, } }
// Licensed to the .NET Foundation under one or more 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.Operations { /// <summary> /// Kind of unary operator /// </summary> public enum UnaryOperatorKind { /// <summary> /// Represents unknown or error operator kind. /// </summary> None = 0x0, /// <summary> /// Represents the C# '~' operator. /// </summary> BitwiseNegation = 0x1, /// <summary> /// Represents the C# '!' operator and VB 'Not' operator. /// </summary> Not = 0x2, /// <summary> /// Represents the unary '+' operator. /// </summary> Plus = 0x3, /// <summary> /// Represents the unary '-' operator. /// </summary> Minus = 0x4, /// <summary> /// Represents the C# 'true' operator and VB 'IsTrue' operator. /// </summary> True = 0x5, /// <summary> /// Represents the C# 'false' operator and VB 'IsFalse' operator. /// </summary> False = 0x6, /// <summary> /// Represents the C# '^' operator. /// </summary> Hat = 0x7, } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/VisualStudio/Core/Def/Implementation/CallHierarchy/ICallHierarchyPresenter.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.Editor.Implementation.CallHierarchy; namespace Microsoft.CodeAnalysis.Editor.Host { internal interface ICallHierarchyPresenter { void PresentRoot(CallHierarchyItem root); } }
// Licensed to the .NET Foundation under one or more 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.Editor.Implementation.CallHierarchy; namespace Microsoft.CodeAnalysis.Editor.Host { internal interface ICallHierarchyPresenter { void PresentRoot(CallHierarchyItem root); } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Portable/Binder/SwitchBinder.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class SwitchBinder : LocalScopeBinder { protected readonly SwitchStatementSyntax SwitchSyntax; private readonly GeneratedLabelSymbol _breakLabel; private BoundExpression _switchGoverningExpression; private BindingDiagnosticBag _switchGoverningDiagnostics; private SwitchBinder(Binder next, SwitchStatementSyntax switchSyntax) : base(next) { SwitchSyntax = switchSyntax; _breakLabel = new GeneratedLabelSymbol("break"); } protected bool PatternsEnabled => ((CSharpParseOptions)SwitchSyntax.SyntaxTree.Options)?.IsFeatureEnabled(MessageID.IDS_FeaturePatternMatching) != false; protected BoundExpression SwitchGoverningExpression { get { EnsureSwitchGoverningExpressionAndDiagnosticsBound(); Debug.Assert(_switchGoverningExpression != null); return _switchGoverningExpression; } } protected TypeSymbol SwitchGoverningType => SwitchGoverningExpression.Type; protected uint SwitchGoverningValEscape => GetValEscape(SwitchGoverningExpression, LocalScopeDepth); protected BindingDiagnosticBag SwitchGoverningDiagnostics { get { EnsureSwitchGoverningExpressionAndDiagnosticsBound(); return _switchGoverningDiagnostics; } } private void EnsureSwitchGoverningExpressionAndDiagnosticsBound() { if (_switchGoverningExpression == null) { var switchGoverningDiagnostics = new BindingDiagnosticBag(); var boundSwitchExpression = BindSwitchGoverningExpression(switchGoverningDiagnostics); _switchGoverningDiagnostics = switchGoverningDiagnostics; Interlocked.CompareExchange(ref _switchGoverningExpression, boundSwitchExpression, null); } } // Dictionary for the switch case/default labels. // Case labels with a non-null constant value are indexed on their ConstantValue. // Default label(s) are indexed on a special DefaultKey object. // Invalid case labels with null constant value are indexed on the labelName. private Dictionary<object, SourceLabelSymbol> _lazySwitchLabelsMap; private static readonly object s_defaultKey = new object(); private Dictionary<object, SourceLabelSymbol> LabelsByValue { get { if (_lazySwitchLabelsMap == null && this.Labels.Length > 0) { _lazySwitchLabelsMap = BuildLabelsByValue(this.Labels); } return _lazySwitchLabelsMap; } } private static Dictionary<object, SourceLabelSymbol> BuildLabelsByValue(ImmutableArray<LabelSymbol> labels) { Debug.Assert(labels.Length > 0); var map = new Dictionary<object, SourceLabelSymbol>(labels.Length, new SwitchConstantValueHelper.SwitchLabelsComparer()); foreach (SourceLabelSymbol label in labels) { SyntaxKind labelKind = label.IdentifierNodeOrToken.Kind(); if (labelKind == SyntaxKind.IdentifierToken) { continue; } object key; var constantValue = label.SwitchCaseLabelConstant; if ((object)constantValue != null && !constantValue.IsBad) { // Case labels with a non-null constant value are indexed on their ConstantValue. key = KeyForConstant(constantValue); } else if (labelKind == SyntaxKind.DefaultSwitchLabel) { // Default label(s) are indexed on a special DefaultKey object. key = s_defaultKey; } else { // Invalid case labels with null constant value are indexed on the labelName. key = label.IdentifierNodeOrToken.AsNode(); } // If there is a duplicate label, ignore it. It will be reported when binding the switch label. if (!map.ContainsKey(key)) { map.Add(key, label); } } return map; } protected override ImmutableArray<LocalSymbol> BuildLocals() { var builder = ArrayBuilder<LocalSymbol>.GetInstance(); foreach (var section in SwitchSyntax.Sections) { builder.AddRange(BuildLocals(section.Statements, GetBinder(section))); } return builder.ToImmutableAndFree(); } protected override ImmutableArray<LocalFunctionSymbol> BuildLocalFunctions() { var builder = ArrayBuilder<LocalFunctionSymbol>.GetInstance(); foreach (var section in SwitchSyntax.Sections) { builder.AddRange(BuildLocalFunctions(section.Statements)); } return builder.ToImmutableAndFree(); } internal override bool IsLocalFunctionsScopeBinder { get { return true; } } internal override GeneratedLabelSymbol BreakLabel { get { return _breakLabel; } } protected override ImmutableArray<LabelSymbol> BuildLabels() { // We bind the switch expression and the switch case label expressions so that the constant values can be // part of the label, but we do not report any diagnostics here. Diagnostics will be reported during binding. ArrayBuilder<LabelSymbol> labels = ArrayBuilder<LabelSymbol>.GetInstance(); foreach (var section in SwitchSyntax.Sections) { // add switch case/default labels BuildSwitchLabels(section.Labels, GetBinder(section), labels, BindingDiagnosticBag.Discarded); // add regular labels from the statements in the switch section BuildLabels(section.Statements, ref labels); } return labels.ToImmutableAndFree(); } internal override bool IsLabelsScopeBinder { get { return true; } } private void BuildSwitchLabels(SyntaxList<SwitchLabelSyntax> labelsSyntax, Binder sectionBinder, ArrayBuilder<LabelSymbol> labels, BindingDiagnosticBag tempDiagnosticBag) { // add switch case/default labels foreach (var labelSyntax in labelsSyntax) { ConstantValue boundLabelConstantOpt = null; switch (labelSyntax.Kind()) { case SyntaxKind.CaseSwitchLabel: // compute the constant value to place in the label symbol var caseLabel = (CaseSwitchLabelSyntax)labelSyntax; Debug.Assert(caseLabel.Value != null); var boundLabelExpression = sectionBinder.BindTypeOrRValue(caseLabel.Value, tempDiagnosticBag); if (boundLabelExpression is BoundTypeExpression type) { // Nothing to do at this point. The label will be bound later. } else { _ = ConvertCaseExpression(labelSyntax, boundLabelExpression, sectionBinder, out boundLabelConstantOpt, tempDiagnosticBag); } break; case SyntaxKind.CasePatternSwitchLabel: // bind the pattern, to cause its pattern variables to be inferred if necessary var matchLabel = (CasePatternSwitchLabelSyntax)labelSyntax; _ = sectionBinder.BindPattern( matchLabel.Pattern, SwitchGoverningType, SwitchGoverningValEscape, permitDesignations: true, labelSyntax.HasErrors, tempDiagnosticBag); break; default: // No constant value break; } // Create the label symbol labels.Add(new SourceLabelSymbol((MethodSymbol)this.ContainingMemberOrLambda, labelSyntax, boundLabelConstantOpt)); } } protected BoundExpression ConvertCaseExpression(CSharpSyntaxNode node, BoundExpression caseExpression, Binder sectionBinder, out ConstantValue constantValueOpt, BindingDiagnosticBag diagnostics, bool isGotoCaseExpr = false) { bool hasErrors = false; if (isGotoCaseExpr) { // SPEC VIOLATION for Dev10 COMPATIBILITY: // Dev10 compiler violates the SPEC comment below: // "if the constant-expression is not implicitly convertible (§6.1) to // the governing type of the nearest enclosing switch statement, // a compile-time error occurs" // If there is no implicit conversion from gotoCaseExpression to switchGoverningType, // but there exists an explicit conversion, Dev10 compiler generates a warning "WRN_GotoCaseShouldConvert" // instead of an error. See test "CS0469_NoImplicitConversionWarning". CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = Conversions.ClassifyConversionFromExpression(caseExpression, SwitchGoverningType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!conversion.IsValid) { GenerateImplicitConversionError(diagnostics, node, conversion, caseExpression, SwitchGoverningType); hasErrors = true; } else if (!conversion.IsImplicit) { diagnostics.Add(ErrorCode.WRN_GotoCaseShouldConvert, node.Location, SwitchGoverningType); hasErrors = true; } caseExpression = CreateConversion(caseExpression, conversion, SwitchGoverningType, diagnostics); } return ConvertPatternExpression(SwitchGoverningType, node, caseExpression, out constantValueOpt, hasErrors, diagnostics); } private static readonly object s_nullKey = new object(); protected static object KeyForConstant(ConstantValue constantValue) { Debug.Assert((object)constantValue != null); return constantValue.IsNull ? s_nullKey : constantValue.Value; } protected SourceLabelSymbol FindMatchingSwitchCaseLabel(ConstantValue constantValue, CSharpSyntaxNode labelSyntax) { // SwitchLabelsMap: Dictionary for the switch case/default labels. // Case labels with a non-null constant value are indexed on their ConstantValue. // Invalid case labels (with null constant value) are indexed on the label syntax. object key; if ((object)constantValue != null && !constantValue.IsBad) { key = KeyForConstant(constantValue); } else { key = labelSyntax; } return FindMatchingSwitchLabel(key); } private SourceLabelSymbol GetDefaultLabel() { // SwitchLabelsMap: Dictionary for the switch case/default labels. // Default label(s) are indexed on a special DefaultKey object. return FindMatchingSwitchLabel(s_defaultKey); } private SourceLabelSymbol FindMatchingSwitchLabel(object key) { Debug.Assert(key != null); var labelsMap = LabelsByValue; if (labelsMap != null) { SourceLabelSymbol label; if (labelsMap.TryGetValue(key, out label)) { Debug.Assert((object)label != null); return label; } } return null; } internal override ImmutableArray<LocalSymbol> GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) { if (SwitchSyntax == scopeDesignator) { return this.Locals; } throw ExceptionUtilities.Unreachable; } internal override ImmutableArray<LocalFunctionSymbol> GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) { if (SwitchSyntax == scopeDesignator) { return this.LocalFunctions; } throw ExceptionUtilities.Unreachable; } internal override SyntaxNode ScopeDesignator { get { return SwitchSyntax; } } # region "Switch statement binding methods" // Bind the switch expression private BoundExpression BindSwitchGoverningExpression(BindingDiagnosticBag diagnostics) { // We are at present inside the switch binder, but the switch expression is not // bound in the context of the switch binder; it's bound in the context of the // enclosing binder. For example: // // class C { // int x; // void M() { // switch(x) { // case 1: // int x; // // The "x" in "switch(x)" refers to this.x, not the local x that is in scope inside the switch block. Debug.Assert(ScopeDesignator == SwitchSyntax); ExpressionSyntax node = SwitchSyntax.Expression; var binder = this.GetBinder(node); Debug.Assert(binder != null); var switchGoverningExpression = binder.BindRValueWithoutTargetType(node, diagnostics); var switchGoverningType = switchGoverningExpression.Type; if ((object)switchGoverningType != null && !switchGoverningType.IsErrorType()) { // SPEC: The governing type of a switch statement is established by the switch expression. // SPEC: 1) If the type of the switch expression is sbyte, byte, short, ushort, int, uint, // SPEC: long, ulong, bool, char, string, or an enum-type, or if it is the nullable type // SPEC: corresponding to one of these types, then that is the governing type of the switch statement. // SPEC: 2) Otherwise if exactly one user-defined implicit conversion (§6.4) exists from the // SPEC: type of the switch expression to one of the following possible governing types: // SPEC: sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or, a nullable type // SPEC: corresponding to one of those types, then the result is the switch governing type // SPEC: 3) Otherwise (in C# 7 and later) the switch governing type is the type of the // SPEC: switch expression. if (switchGoverningType.IsValidV6SwitchGoverningType()) { // Condition (1) satisfied // Note: dev11 actually checks the stripped type, but nullable was introduced at the same // time, so it doesn't really matter. if (switchGoverningType.SpecialType == SpecialType.System_Boolean) { CheckFeatureAvailability(node, MessageID.IDS_FeatureSwitchOnBool, diagnostics); } return switchGoverningExpression; } else { TypeSymbol resultantGoverningType; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = binder.Conversions.ClassifyImplicitUserDefinedConversionForV6SwitchGoverningType(switchGoverningType, out resultantGoverningType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (conversion.IsValid) { // Condition (2) satisfied Debug.Assert(conversion.Kind == ConversionKind.ImplicitUserDefined); Debug.Assert(conversion.Method.IsUserDefinedConversion()); Debug.Assert(conversion.UserDefinedToConversion.IsIdentity); Debug.Assert(resultantGoverningType.IsValidV6SwitchGoverningType(isTargetTypeOfUserDefinedOp: true)); return binder.CreateConversion(node, switchGoverningExpression, conversion, isCast: false, conversionGroupOpt: null, resultantGoverningType, diagnostics); } else if (!switchGoverningType.IsVoidType()) { // Otherwise (3) satisfied if (!PatternsEnabled) { diagnostics.Add(ErrorCode.ERR_V6SwitchGoverningTypeValueExpected, node.Location); } return switchGoverningExpression; } else { switchGoverningType = CreateErrorType(switchGoverningType.Name); } } } if (!switchGoverningExpression.HasAnyErrors) { Debug.Assert((object)switchGoverningExpression.Type == null || switchGoverningExpression.Type.IsVoidType()); diagnostics.Add(ErrorCode.ERR_SwitchExpressionValueExpected, node.Location, switchGoverningExpression.Display); } return new BoundBadExpression(node, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, ImmutableArray.Create(switchGoverningExpression), switchGoverningType ?? CreateErrorType()); } private Dictionary<SyntaxNode, LabelSymbol> _labelsByNode; protected Dictionary<SyntaxNode, LabelSymbol> LabelsByNode { get { if (_labelsByNode == null) { var result = new Dictionary<SyntaxNode, LabelSymbol>(); foreach (var label in Labels) { var node = ((SourceLabelSymbol)label).IdentifierNodeOrToken.AsNode(); if (node != null) { result.Add(node, label); } } _labelsByNode = result; } return _labelsByNode; } } internal BoundStatement BindGotoCaseOrDefault(GotoStatementSyntax node, Binder gotoBinder, BindingDiagnosticBag diagnostics) { Debug.Assert(node.Kind() == SyntaxKind.GotoCaseStatement || node.Kind() == SyntaxKind.GotoDefaultStatement); BoundExpression gotoCaseExpressionOpt = null; // Prevent cascading diagnostics if (!node.HasErrors) { ConstantValue gotoCaseExpressionConstant = null; bool hasErrors = false; SourceLabelSymbol matchedLabelSymbol; // SPEC: If the goto case statement is not enclosed by a switch statement, if the constant-expression // SPEC: is not implicitly convertible (§6.1) to the governing type of the nearest enclosing switch statement, // SPEC: or if the nearest enclosing switch statement does not contain a case label with the given constant value, // SPEC: a compile-time error occurs. // SPEC: If the goto default statement is not enclosed by a switch statement, or if the nearest enclosing // SPEC: switch statement does not contain a default label, a compile-time error occurs. if (node.Expression != null) { Debug.Assert(node.Kind() == SyntaxKind.GotoCaseStatement); // Bind the goto case expression gotoCaseExpressionOpt = gotoBinder.BindValue(node.Expression, diagnostics, BindValueKind.RValue); gotoCaseExpressionOpt = ConvertCaseExpression(node, gotoCaseExpressionOpt, gotoBinder, out gotoCaseExpressionConstant, diagnostics, isGotoCaseExpr: true); // Check for bind errors hasErrors = hasErrors || gotoCaseExpressionOpt.HasAnyErrors; if (!hasErrors && gotoCaseExpressionConstant == null) { diagnostics.Add(ErrorCode.ERR_ConstantExpected, node.Location); hasErrors = true; } ConstantValueUtils.CheckLangVersionForConstantValue(gotoCaseExpressionOpt, diagnostics); // LabelSymbols for all the switch case labels are created by BuildLabels(). // Fetch the matching switch case label symbols matchedLabelSymbol = FindMatchingSwitchCaseLabel(gotoCaseExpressionConstant, node); } else { Debug.Assert(node.Kind() == SyntaxKind.GotoDefaultStatement); matchedLabelSymbol = GetDefaultLabel(); } if ((object)matchedLabelSymbol == null) { if (!hasErrors) { // No matching case label/default label found var labelName = SyntaxFacts.GetText(node.CaseOrDefaultKeyword.Kind()); if (node.Kind() == SyntaxKind.GotoCaseStatement) { labelName += " " + gotoCaseExpressionConstant.Value?.ToString(); } labelName += ":"; diagnostics.Add(ErrorCode.ERR_LabelNotFound, node.Location, labelName); hasErrors = true; } } else { return new BoundGotoStatement(node, matchedLabelSymbol, gotoCaseExpressionOpt, null, hasErrors); } } return new BoundBadStatement( syntax: node, childBoundNodes: gotoCaseExpressionOpt != null ? ImmutableArray.Create<BoundNode>(gotoCaseExpressionOpt) : ImmutableArray<BoundNode>.Empty, hasErrors: true); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class SwitchBinder : LocalScopeBinder { protected readonly SwitchStatementSyntax SwitchSyntax; private readonly GeneratedLabelSymbol _breakLabel; private BoundExpression _switchGoverningExpression; private BindingDiagnosticBag _switchGoverningDiagnostics; private SwitchBinder(Binder next, SwitchStatementSyntax switchSyntax) : base(next) { SwitchSyntax = switchSyntax; _breakLabel = new GeneratedLabelSymbol("break"); } protected bool PatternsEnabled => ((CSharpParseOptions)SwitchSyntax.SyntaxTree.Options)?.IsFeatureEnabled(MessageID.IDS_FeaturePatternMatching) != false; protected BoundExpression SwitchGoverningExpression { get { EnsureSwitchGoverningExpressionAndDiagnosticsBound(); Debug.Assert(_switchGoverningExpression != null); return _switchGoverningExpression; } } protected TypeSymbol SwitchGoverningType => SwitchGoverningExpression.Type; protected uint SwitchGoverningValEscape => GetValEscape(SwitchGoverningExpression, LocalScopeDepth); protected BindingDiagnosticBag SwitchGoverningDiagnostics { get { EnsureSwitchGoverningExpressionAndDiagnosticsBound(); return _switchGoverningDiagnostics; } } private void EnsureSwitchGoverningExpressionAndDiagnosticsBound() { if (_switchGoverningExpression == null) { var switchGoverningDiagnostics = new BindingDiagnosticBag(); var boundSwitchExpression = BindSwitchGoverningExpression(switchGoverningDiagnostics); _switchGoverningDiagnostics = switchGoverningDiagnostics; Interlocked.CompareExchange(ref _switchGoverningExpression, boundSwitchExpression, null); } } // Dictionary for the switch case/default labels. // Case labels with a non-null constant value are indexed on their ConstantValue. // Default label(s) are indexed on a special DefaultKey object. // Invalid case labels with null constant value are indexed on the labelName. private Dictionary<object, SourceLabelSymbol> _lazySwitchLabelsMap; private static readonly object s_defaultKey = new object(); private Dictionary<object, SourceLabelSymbol> LabelsByValue { get { if (_lazySwitchLabelsMap == null && this.Labels.Length > 0) { _lazySwitchLabelsMap = BuildLabelsByValue(this.Labels); } return _lazySwitchLabelsMap; } } private static Dictionary<object, SourceLabelSymbol> BuildLabelsByValue(ImmutableArray<LabelSymbol> labels) { Debug.Assert(labels.Length > 0); var map = new Dictionary<object, SourceLabelSymbol>(labels.Length, new SwitchConstantValueHelper.SwitchLabelsComparer()); foreach (SourceLabelSymbol label in labels) { SyntaxKind labelKind = label.IdentifierNodeOrToken.Kind(); if (labelKind == SyntaxKind.IdentifierToken) { continue; } object key; var constantValue = label.SwitchCaseLabelConstant; if ((object)constantValue != null && !constantValue.IsBad) { // Case labels with a non-null constant value are indexed on their ConstantValue. key = KeyForConstant(constantValue); } else if (labelKind == SyntaxKind.DefaultSwitchLabel) { // Default label(s) are indexed on a special DefaultKey object. key = s_defaultKey; } else { // Invalid case labels with null constant value are indexed on the labelName. key = label.IdentifierNodeOrToken.AsNode(); } // If there is a duplicate label, ignore it. It will be reported when binding the switch label. if (!map.ContainsKey(key)) { map.Add(key, label); } } return map; } protected override ImmutableArray<LocalSymbol> BuildLocals() { var builder = ArrayBuilder<LocalSymbol>.GetInstance(); foreach (var section in SwitchSyntax.Sections) { builder.AddRange(BuildLocals(section.Statements, GetBinder(section))); } return builder.ToImmutableAndFree(); } protected override ImmutableArray<LocalFunctionSymbol> BuildLocalFunctions() { var builder = ArrayBuilder<LocalFunctionSymbol>.GetInstance(); foreach (var section in SwitchSyntax.Sections) { builder.AddRange(BuildLocalFunctions(section.Statements)); } return builder.ToImmutableAndFree(); } internal override bool IsLocalFunctionsScopeBinder { get { return true; } } internal override GeneratedLabelSymbol BreakLabel { get { return _breakLabel; } } protected override ImmutableArray<LabelSymbol> BuildLabels() { // We bind the switch expression and the switch case label expressions so that the constant values can be // part of the label, but we do not report any diagnostics here. Diagnostics will be reported during binding. ArrayBuilder<LabelSymbol> labels = ArrayBuilder<LabelSymbol>.GetInstance(); foreach (var section in SwitchSyntax.Sections) { // add switch case/default labels BuildSwitchLabels(section.Labels, GetBinder(section), labels, BindingDiagnosticBag.Discarded); // add regular labels from the statements in the switch section BuildLabels(section.Statements, ref labels); } return labels.ToImmutableAndFree(); } internal override bool IsLabelsScopeBinder { get { return true; } } private void BuildSwitchLabels(SyntaxList<SwitchLabelSyntax> labelsSyntax, Binder sectionBinder, ArrayBuilder<LabelSymbol> labels, BindingDiagnosticBag tempDiagnosticBag) { // add switch case/default labels foreach (var labelSyntax in labelsSyntax) { ConstantValue boundLabelConstantOpt = null; switch (labelSyntax.Kind()) { case SyntaxKind.CaseSwitchLabel: // compute the constant value to place in the label symbol var caseLabel = (CaseSwitchLabelSyntax)labelSyntax; Debug.Assert(caseLabel.Value != null); var boundLabelExpression = sectionBinder.BindTypeOrRValue(caseLabel.Value, tempDiagnosticBag); if (boundLabelExpression is BoundTypeExpression type) { // Nothing to do at this point. The label will be bound later. } else { _ = ConvertCaseExpression(labelSyntax, boundLabelExpression, sectionBinder, out boundLabelConstantOpt, tempDiagnosticBag); } break; case SyntaxKind.CasePatternSwitchLabel: // bind the pattern, to cause its pattern variables to be inferred if necessary var matchLabel = (CasePatternSwitchLabelSyntax)labelSyntax; _ = sectionBinder.BindPattern( matchLabel.Pattern, SwitchGoverningType, SwitchGoverningValEscape, permitDesignations: true, labelSyntax.HasErrors, tempDiagnosticBag); break; default: // No constant value break; } // Create the label symbol labels.Add(new SourceLabelSymbol((MethodSymbol)this.ContainingMemberOrLambda, labelSyntax, boundLabelConstantOpt)); } } protected BoundExpression ConvertCaseExpression(CSharpSyntaxNode node, BoundExpression caseExpression, Binder sectionBinder, out ConstantValue constantValueOpt, BindingDiagnosticBag diagnostics, bool isGotoCaseExpr = false) { bool hasErrors = false; if (isGotoCaseExpr) { // SPEC VIOLATION for Dev10 COMPATIBILITY: // Dev10 compiler violates the SPEC comment below: // "if the constant-expression is not implicitly convertible (§6.1) to // the governing type of the nearest enclosing switch statement, // a compile-time error occurs" // If there is no implicit conversion from gotoCaseExpression to switchGoverningType, // but there exists an explicit conversion, Dev10 compiler generates a warning "WRN_GotoCaseShouldConvert" // instead of an error. See test "CS0469_NoImplicitConversionWarning". CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = Conversions.ClassifyConversionFromExpression(caseExpression, SwitchGoverningType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!conversion.IsValid) { GenerateImplicitConversionError(diagnostics, node, conversion, caseExpression, SwitchGoverningType); hasErrors = true; } else if (!conversion.IsImplicit) { diagnostics.Add(ErrorCode.WRN_GotoCaseShouldConvert, node.Location, SwitchGoverningType); hasErrors = true; } caseExpression = CreateConversion(caseExpression, conversion, SwitchGoverningType, diagnostics); } return ConvertPatternExpression(SwitchGoverningType, node, caseExpression, out constantValueOpt, hasErrors, diagnostics); } private static readonly object s_nullKey = new object(); protected static object KeyForConstant(ConstantValue constantValue) { Debug.Assert((object)constantValue != null); return constantValue.IsNull ? s_nullKey : constantValue.Value; } protected SourceLabelSymbol FindMatchingSwitchCaseLabel(ConstantValue constantValue, CSharpSyntaxNode labelSyntax) { // SwitchLabelsMap: Dictionary for the switch case/default labels. // Case labels with a non-null constant value are indexed on their ConstantValue. // Invalid case labels (with null constant value) are indexed on the label syntax. object key; if ((object)constantValue != null && !constantValue.IsBad) { key = KeyForConstant(constantValue); } else { key = labelSyntax; } return FindMatchingSwitchLabel(key); } private SourceLabelSymbol GetDefaultLabel() { // SwitchLabelsMap: Dictionary for the switch case/default labels. // Default label(s) are indexed on a special DefaultKey object. return FindMatchingSwitchLabel(s_defaultKey); } private SourceLabelSymbol FindMatchingSwitchLabel(object key) { Debug.Assert(key != null); var labelsMap = LabelsByValue; if (labelsMap != null) { SourceLabelSymbol label; if (labelsMap.TryGetValue(key, out label)) { Debug.Assert((object)label != null); return label; } } return null; } internal override ImmutableArray<LocalSymbol> GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) { if (SwitchSyntax == scopeDesignator) { return this.Locals; } throw ExceptionUtilities.Unreachable; } internal override ImmutableArray<LocalFunctionSymbol> GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) { if (SwitchSyntax == scopeDesignator) { return this.LocalFunctions; } throw ExceptionUtilities.Unreachable; } internal override SyntaxNode ScopeDesignator { get { return SwitchSyntax; } } # region "Switch statement binding methods" // Bind the switch expression private BoundExpression BindSwitchGoverningExpression(BindingDiagnosticBag diagnostics) { // We are at present inside the switch binder, but the switch expression is not // bound in the context of the switch binder; it's bound in the context of the // enclosing binder. For example: // // class C { // int x; // void M() { // switch(x) { // case 1: // int x; // // The "x" in "switch(x)" refers to this.x, not the local x that is in scope inside the switch block. Debug.Assert(ScopeDesignator == SwitchSyntax); ExpressionSyntax node = SwitchSyntax.Expression; var binder = this.GetBinder(node); Debug.Assert(binder != null); var switchGoverningExpression = binder.BindRValueWithoutTargetType(node, diagnostics); var switchGoverningType = switchGoverningExpression.Type; if ((object)switchGoverningType != null && !switchGoverningType.IsErrorType()) { // SPEC: The governing type of a switch statement is established by the switch expression. // SPEC: 1) If the type of the switch expression is sbyte, byte, short, ushort, int, uint, // SPEC: long, ulong, bool, char, string, or an enum-type, or if it is the nullable type // SPEC: corresponding to one of these types, then that is the governing type of the switch statement. // SPEC: 2) Otherwise if exactly one user-defined implicit conversion (§6.4) exists from the // SPEC: type of the switch expression to one of the following possible governing types: // SPEC: sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or, a nullable type // SPEC: corresponding to one of those types, then the result is the switch governing type // SPEC: 3) Otherwise (in C# 7 and later) the switch governing type is the type of the // SPEC: switch expression. if (switchGoverningType.IsValidV6SwitchGoverningType()) { // Condition (1) satisfied // Note: dev11 actually checks the stripped type, but nullable was introduced at the same // time, so it doesn't really matter. if (switchGoverningType.SpecialType == SpecialType.System_Boolean) { CheckFeatureAvailability(node, MessageID.IDS_FeatureSwitchOnBool, diagnostics); } return switchGoverningExpression; } else { TypeSymbol resultantGoverningType; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = binder.Conversions.ClassifyImplicitUserDefinedConversionForV6SwitchGoverningType(switchGoverningType, out resultantGoverningType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (conversion.IsValid) { // Condition (2) satisfied Debug.Assert(conversion.Kind == ConversionKind.ImplicitUserDefined); Debug.Assert(conversion.Method.IsUserDefinedConversion()); Debug.Assert(conversion.UserDefinedToConversion.IsIdentity); Debug.Assert(resultantGoverningType.IsValidV6SwitchGoverningType(isTargetTypeOfUserDefinedOp: true)); return binder.CreateConversion(node, switchGoverningExpression, conversion, isCast: false, conversionGroupOpt: null, resultantGoverningType, diagnostics); } else if (!switchGoverningType.IsVoidType()) { // Otherwise (3) satisfied if (!PatternsEnabled) { diagnostics.Add(ErrorCode.ERR_V6SwitchGoverningTypeValueExpected, node.Location); } return switchGoverningExpression; } else { switchGoverningType = CreateErrorType(switchGoverningType.Name); } } } if (!switchGoverningExpression.HasAnyErrors) { Debug.Assert((object)switchGoverningExpression.Type == null || switchGoverningExpression.Type.IsVoidType()); diagnostics.Add(ErrorCode.ERR_SwitchExpressionValueExpected, node.Location, switchGoverningExpression.Display); } return new BoundBadExpression(node, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, ImmutableArray.Create(switchGoverningExpression), switchGoverningType ?? CreateErrorType()); } private Dictionary<SyntaxNode, LabelSymbol> _labelsByNode; protected Dictionary<SyntaxNode, LabelSymbol> LabelsByNode { get { if (_labelsByNode == null) { var result = new Dictionary<SyntaxNode, LabelSymbol>(); foreach (var label in Labels) { var node = ((SourceLabelSymbol)label).IdentifierNodeOrToken.AsNode(); if (node != null) { result.Add(node, label); } } _labelsByNode = result; } return _labelsByNode; } } internal BoundStatement BindGotoCaseOrDefault(GotoStatementSyntax node, Binder gotoBinder, BindingDiagnosticBag diagnostics) { Debug.Assert(node.Kind() == SyntaxKind.GotoCaseStatement || node.Kind() == SyntaxKind.GotoDefaultStatement); BoundExpression gotoCaseExpressionOpt = null; // Prevent cascading diagnostics if (!node.HasErrors) { ConstantValue gotoCaseExpressionConstant = null; bool hasErrors = false; SourceLabelSymbol matchedLabelSymbol; // SPEC: If the goto case statement is not enclosed by a switch statement, if the constant-expression // SPEC: is not implicitly convertible (§6.1) to the governing type of the nearest enclosing switch statement, // SPEC: or if the nearest enclosing switch statement does not contain a case label with the given constant value, // SPEC: a compile-time error occurs. // SPEC: If the goto default statement is not enclosed by a switch statement, or if the nearest enclosing // SPEC: switch statement does not contain a default label, a compile-time error occurs. if (node.Expression != null) { Debug.Assert(node.Kind() == SyntaxKind.GotoCaseStatement); // Bind the goto case expression gotoCaseExpressionOpt = gotoBinder.BindValue(node.Expression, diagnostics, BindValueKind.RValue); gotoCaseExpressionOpt = ConvertCaseExpression(node, gotoCaseExpressionOpt, gotoBinder, out gotoCaseExpressionConstant, diagnostics, isGotoCaseExpr: true); // Check for bind errors hasErrors = hasErrors || gotoCaseExpressionOpt.HasAnyErrors; if (!hasErrors && gotoCaseExpressionConstant == null) { diagnostics.Add(ErrorCode.ERR_ConstantExpected, node.Location); hasErrors = true; } ConstantValueUtils.CheckLangVersionForConstantValue(gotoCaseExpressionOpt, diagnostics); // LabelSymbols for all the switch case labels are created by BuildLabels(). // Fetch the matching switch case label symbols matchedLabelSymbol = FindMatchingSwitchCaseLabel(gotoCaseExpressionConstant, node); } else { Debug.Assert(node.Kind() == SyntaxKind.GotoDefaultStatement); matchedLabelSymbol = GetDefaultLabel(); } if ((object)matchedLabelSymbol == null) { if (!hasErrors) { // No matching case label/default label found var labelName = SyntaxFacts.GetText(node.CaseOrDefaultKeyword.Kind()); if (node.Kind() == SyntaxKind.GotoCaseStatement) { labelName += " " + gotoCaseExpressionConstant.Value?.ToString(); } labelName += ":"; diagnostics.Add(ErrorCode.ERR_LabelNotFound, node.Location, labelName); hasErrors = true; } } else { return new BoundGotoStatement(node, matchedLabelSymbol, gotoCaseExpressionOpt, null, hasErrors); } } return new BoundBadStatement( syntax: node, childBoundNodes: gotoCaseExpressionOpt != null ? ImmutableArray.Create<BoundNode>(gotoCaseExpressionOpt) : ImmutableArray<BoundNode>.Empty, hasErrors: true); } #endregion } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/Core/MSBuild/MSBuild/Constants/MetadataNames.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.MSBuild { internal static class MetadataNames { public const string Aliases = nameof(Aliases); public const string HintPath = nameof(HintPath); public const string Link = nameof(Link); public const string Name = nameof(Name); public const string ReferenceOutputAssembly = nameof(ReferenceOutputAssembly); } }
// Licensed to the .NET Foundation under one or more 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.MSBuild { internal static class MetadataNames { public const string Aliases = nameof(Aliases); public const string HintPath = nameof(HintPath); public const string Link = nameof(Link); public const string Name = nameof(Name); public const string ReferenceOutputAssembly = nameof(ReferenceOutputAssembly); } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/FixAllContext.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes { /// <summary> /// Context for "Fix all occurrences" code fixes provided by a <see cref="FixAllProvider"/>. /// </summary> public partial class FixAllContext { internal FixAllState State { get; } internal FixAllProvider? FixAllProvider => State.FixAllProvider; /// <summary> /// Solution to fix all occurrences. /// </summary> public Solution Solution => State.Solution; /// <summary> /// Project within which fix all occurrences was triggered. /// </summary> public Project Project => State.Project; /// <summary> /// Document within which fix all occurrences was triggered. /// Can be null if the context was created using <see cref="FixAllContext.FixAllContext(Project, CodeFixProvider, FixAllScope, string, IEnumerable{string}, DiagnosticProvider, CancellationToken)"/>. /// </summary> public Document? Document => State.Document; /// <summary> /// Underlying <see cref="CodeFixes.CodeFixProvider"/> which triggered this fix all. /// </summary> public CodeFixProvider CodeFixProvider => State.CodeFixProvider; /// <summary> /// <see cref="FixAllScope"/> to fix all occurrences. /// </summary> public FixAllScope Scope => State.Scope; /// <summary> /// Diagnostic Ids to fix. /// Note that <see cref="GetDocumentDiagnosticsAsync(Document)"/>, <see cref="GetProjectDiagnosticsAsync(Project)"/> and <see cref="GetAllDiagnosticsAsync(Project)"/> methods /// return only diagnostics whose IDs are contained in this set of Ids. /// </summary> public ImmutableHashSet<string> DiagnosticIds => State.DiagnosticIds; /// <summary> /// The <see cref="CodeAction.EquivalenceKey"/> value expected of a <see cref="CodeAction"/> participating in this fix all. /// </summary> public string? CodeActionEquivalenceKey => State.CodeActionEquivalenceKey; /// <summary> /// CancellationToken for fix all session. /// </summary> public CancellationToken CancellationToken { get; } internal IProgressTracker ProgressTracker { get; } /// <summary> /// Creates a new <see cref="FixAllContext"/>. /// Use this overload when applying fix all to a diagnostic with a source location. /// </summary> /// <param name="document">Document within which fix all occurrences was triggered.</param> /// <param name="codeFixProvider">Underlying <see cref="CodeFixes.CodeFixProvider"/> which triggered this fix all.</param> /// <param name="scope"><see cref="FixAllScope"/> to fix all occurrences.</param> /// <param name="codeActionEquivalenceKey">The <see cref="CodeAction.EquivalenceKey"/> value expected of a <see cref="CodeAction"/> participating in this fix all.</param> /// <param name="diagnosticIds">Diagnostic Ids to fix.</param> /// <param name="fixAllDiagnosticProvider"> /// <see cref="DiagnosticProvider"/> to fetch document/project diagnostics to fix in a <see cref="FixAllContext"/>. /// </param> /// <param name="cancellationToken">Cancellation token for fix all computation.</param> public FixAllContext( Document document, CodeFixProvider codeFixProvider, FixAllScope scope, string codeActionEquivalenceKey, IEnumerable<string> diagnosticIds, DiagnosticProvider fixAllDiagnosticProvider, CancellationToken cancellationToken) : this(new FixAllState(null, document, codeFixProvider, scope, codeActionEquivalenceKey, diagnosticIds, fixAllDiagnosticProvider), new ProgressTracker(), cancellationToken) { if (document == null) { throw new ArgumentNullException(nameof(document)); } } /// <summary> /// Creates a new <see cref="FixAllContext"/>. /// Use this overload when applying fix all to a diagnostic with no source location, i.e. <see cref="Location.None"/>. /// </summary> /// <param name="project">Project within which fix all occurrences was triggered.</param> /// <param name="codeFixProvider">Underlying <see cref="CodeFixes.CodeFixProvider"/> which triggered this fix all.</param> /// <param name="scope"><see cref="FixAllScope"/> to fix all occurrences.</param> /// <param name="codeActionEquivalenceKey">The <see cref="CodeAction.EquivalenceKey"/> value expected of a <see cref="CodeAction"/> participating in this fix all.</param> /// <param name="diagnosticIds">Diagnostic Ids to fix.</param> /// <param name="fixAllDiagnosticProvider"> /// <see cref="DiagnosticProvider"/> to fetch document/project diagnostics to fix in a <see cref="FixAllContext"/>. /// </param> /// <param name="cancellationToken">Cancellation token for fix all computation.</param> public FixAllContext( Project project, CodeFixProvider codeFixProvider, FixAllScope scope, string codeActionEquivalenceKey, IEnumerable<string> diagnosticIds, DiagnosticProvider fixAllDiagnosticProvider, CancellationToken cancellationToken) : this(new FixAllState(null, project, codeFixProvider, scope, codeActionEquivalenceKey, diagnosticIds, fixAllDiagnosticProvider), new ProgressTracker(), cancellationToken) { if (project == null) { throw new ArgumentNullException(nameof(project)); } } internal FixAllContext( FixAllState state, IProgressTracker progressTracker, CancellationToken cancellationToken) { State = state; this.ProgressTracker = progressTracker; this.CancellationToken = cancellationToken; } /// <summary> /// Gets all the diagnostics in the given document filtered by <see cref="DiagnosticIds"/>. /// </summary> public async Task<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document) { if (document == null) { throw new ArgumentNullException(nameof(document)); } if (this.Project.Language != document.Project.Language) { return ImmutableArray<Diagnostic>.Empty; } var getDiagnosticsTask = State.DiagnosticProvider.GetDocumentDiagnosticsAsync(document, this.CancellationToken); return await GetFilteredDiagnosticsAsync(getDiagnosticsTask, this.DiagnosticIds).ConfigureAwait(false); } private static async Task<ImmutableArray<Diagnostic>> GetFilteredDiagnosticsAsync(Task<IEnumerable<Diagnostic>> getDiagnosticsTask, ImmutableHashSet<string> diagnosticIds) { if (getDiagnosticsTask != null) { var diagnostics = await getDiagnosticsTask.ConfigureAwait(false); if (diagnostics != null) { return diagnostics.Where(d => d != null && diagnosticIds.Contains(d.Id)).ToImmutableArray(); } } return ImmutableArray<Diagnostic>.Empty; } /// <summary> /// Gets all the project-level diagnostics, i.e. diagnostics with no source location, in the given project filtered by <see cref="DiagnosticIds"/>. /// </summary> public Task<ImmutableArray<Diagnostic>> GetProjectDiagnosticsAsync(Project project) { if (project == null) { throw new ArgumentNullException(nameof(project)); } return GetProjectDiagnosticsAsync(project, includeAllDocumentDiagnostics: false); } /// <summary> /// Gets all the diagnostics in the given project filtered by <see cref="DiagnosticIds"/>. /// This includes both document-level diagnostics for all documents in the given project and project-level diagnostics, i.e. diagnostics with no source location, in the given project. /// </summary> public Task<ImmutableArray<Diagnostic>> GetAllDiagnosticsAsync(Project project) { if (project == null) { throw new ArgumentNullException(nameof(project)); } return GetProjectDiagnosticsAsync(project, includeAllDocumentDiagnostics: true); } /// <summary> /// Gets all the project diagnostics in the given project filtered by <see cref="DiagnosticIds"/>. /// If <paramref name="includeAllDocumentDiagnostics"/> is false, then returns only project-level diagnostics which have no source location. /// Otherwise, returns all diagnostics in the project, including the document diagnostics for all documents in the given project. /// </summary> private async Task<ImmutableArray<Diagnostic>> GetProjectDiagnosticsAsync(Project project, bool includeAllDocumentDiagnostics) { Contract.ThrowIfNull(project); if (this.Project.Language != project.Language) { return ImmutableArray<Diagnostic>.Empty; } var getDiagnosticsTask = includeAllDocumentDiagnostics ? State.DiagnosticProvider.GetAllDiagnosticsAsync(project, CancellationToken) : State.DiagnosticProvider.GetProjectDiagnosticsAsync(project, CancellationToken); return await GetFilteredDiagnosticsAsync(getDiagnosticsTask, this.DiagnosticIds).ConfigureAwait(false); } /// <summary> /// Gets a new <see cref="FixAllContext"/> with the given cancellationToken. /// </summary> public FixAllContext WithCancellationToken(CancellationToken cancellationToken) { // TODO: We should change this API to be a virtual method, as the class is not sealed. if (this.CancellationToken == cancellationToken) { return this; } return new FixAllContext(State, this.ProgressTracker, cancellationToken); } internal FixAllContext WithScope(FixAllScope scope) => this.WithState(State.WithScope(scope)); internal FixAllContext WithProject(Project project) => this.WithState(State.WithProject(project)); internal FixAllContext WithDocument(Document? document) => this.WithState(State.WithDocument(document)); private FixAllContext WithState(FixAllState state) => this.State == state ? this : new FixAllContext(state, ProgressTracker, CancellationToken); internal Task<ImmutableDictionary<Document, ImmutableArray<Diagnostic>>> GetDocumentDiagnosticsToFixAsync() => DiagnosticProvider.GetDocumentDiagnosticsToFixAsync(this); internal Task<ImmutableDictionary<Project, ImmutableArray<Diagnostic>>> GetProjectDiagnosticsToFixAsync() => DiagnosticProvider.GetProjectDiagnosticsToFixAsync(this); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes { /// <summary> /// Context for "Fix all occurrences" code fixes provided by a <see cref="FixAllProvider"/>. /// </summary> public partial class FixAllContext { internal FixAllState State { get; } internal FixAllProvider? FixAllProvider => State.FixAllProvider; /// <summary> /// Solution to fix all occurrences. /// </summary> public Solution Solution => State.Solution; /// <summary> /// Project within which fix all occurrences was triggered. /// </summary> public Project Project => State.Project; /// <summary> /// Document within which fix all occurrences was triggered. /// Can be null if the context was created using <see cref="FixAllContext.FixAllContext(Project, CodeFixProvider, FixAllScope, string, IEnumerable{string}, DiagnosticProvider, CancellationToken)"/>. /// </summary> public Document? Document => State.Document; /// <summary> /// Underlying <see cref="CodeFixes.CodeFixProvider"/> which triggered this fix all. /// </summary> public CodeFixProvider CodeFixProvider => State.CodeFixProvider; /// <summary> /// <see cref="FixAllScope"/> to fix all occurrences. /// </summary> public FixAllScope Scope => State.Scope; /// <summary> /// Diagnostic Ids to fix. /// Note that <see cref="GetDocumentDiagnosticsAsync(Document)"/>, <see cref="GetProjectDiagnosticsAsync(Project)"/> and <see cref="GetAllDiagnosticsAsync(Project)"/> methods /// return only diagnostics whose IDs are contained in this set of Ids. /// </summary> public ImmutableHashSet<string> DiagnosticIds => State.DiagnosticIds; /// <summary> /// The <see cref="CodeAction.EquivalenceKey"/> value expected of a <see cref="CodeAction"/> participating in this fix all. /// </summary> public string? CodeActionEquivalenceKey => State.CodeActionEquivalenceKey; /// <summary> /// CancellationToken for fix all session. /// </summary> public CancellationToken CancellationToken { get; } internal IProgressTracker ProgressTracker { get; } /// <summary> /// Creates a new <see cref="FixAllContext"/>. /// Use this overload when applying fix all to a diagnostic with a source location. /// </summary> /// <param name="document">Document within which fix all occurrences was triggered.</param> /// <param name="codeFixProvider">Underlying <see cref="CodeFixes.CodeFixProvider"/> which triggered this fix all.</param> /// <param name="scope"><see cref="FixAllScope"/> to fix all occurrences.</param> /// <param name="codeActionEquivalenceKey">The <see cref="CodeAction.EquivalenceKey"/> value expected of a <see cref="CodeAction"/> participating in this fix all.</param> /// <param name="diagnosticIds">Diagnostic Ids to fix.</param> /// <param name="fixAllDiagnosticProvider"> /// <see cref="DiagnosticProvider"/> to fetch document/project diagnostics to fix in a <see cref="FixAllContext"/>. /// </param> /// <param name="cancellationToken">Cancellation token for fix all computation.</param> public FixAllContext( Document document, CodeFixProvider codeFixProvider, FixAllScope scope, string codeActionEquivalenceKey, IEnumerable<string> diagnosticIds, DiagnosticProvider fixAllDiagnosticProvider, CancellationToken cancellationToken) : this(new FixAllState(null, document, codeFixProvider, scope, codeActionEquivalenceKey, diagnosticIds, fixAllDiagnosticProvider), new ProgressTracker(), cancellationToken) { if (document == null) { throw new ArgumentNullException(nameof(document)); } } /// <summary> /// Creates a new <see cref="FixAllContext"/>. /// Use this overload when applying fix all to a diagnostic with no source location, i.e. <see cref="Location.None"/>. /// </summary> /// <param name="project">Project within which fix all occurrences was triggered.</param> /// <param name="codeFixProvider">Underlying <see cref="CodeFixes.CodeFixProvider"/> which triggered this fix all.</param> /// <param name="scope"><see cref="FixAllScope"/> to fix all occurrences.</param> /// <param name="codeActionEquivalenceKey">The <see cref="CodeAction.EquivalenceKey"/> value expected of a <see cref="CodeAction"/> participating in this fix all.</param> /// <param name="diagnosticIds">Diagnostic Ids to fix.</param> /// <param name="fixAllDiagnosticProvider"> /// <see cref="DiagnosticProvider"/> to fetch document/project diagnostics to fix in a <see cref="FixAllContext"/>. /// </param> /// <param name="cancellationToken">Cancellation token for fix all computation.</param> public FixAllContext( Project project, CodeFixProvider codeFixProvider, FixAllScope scope, string codeActionEquivalenceKey, IEnumerable<string> diagnosticIds, DiagnosticProvider fixAllDiagnosticProvider, CancellationToken cancellationToken) : this(new FixAllState(null, project, codeFixProvider, scope, codeActionEquivalenceKey, diagnosticIds, fixAllDiagnosticProvider), new ProgressTracker(), cancellationToken) { if (project == null) { throw new ArgumentNullException(nameof(project)); } } internal FixAllContext( FixAllState state, IProgressTracker progressTracker, CancellationToken cancellationToken) { State = state; this.ProgressTracker = progressTracker; this.CancellationToken = cancellationToken; } /// <summary> /// Gets all the diagnostics in the given document filtered by <see cref="DiagnosticIds"/>. /// </summary> public async Task<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document) { if (document == null) { throw new ArgumentNullException(nameof(document)); } if (this.Project.Language != document.Project.Language) { return ImmutableArray<Diagnostic>.Empty; } var getDiagnosticsTask = State.DiagnosticProvider.GetDocumentDiagnosticsAsync(document, this.CancellationToken); return await GetFilteredDiagnosticsAsync(getDiagnosticsTask, this.DiagnosticIds).ConfigureAwait(false); } private static async Task<ImmutableArray<Diagnostic>> GetFilteredDiagnosticsAsync(Task<IEnumerable<Diagnostic>> getDiagnosticsTask, ImmutableHashSet<string> diagnosticIds) { if (getDiagnosticsTask != null) { var diagnostics = await getDiagnosticsTask.ConfigureAwait(false); if (diagnostics != null) { return diagnostics.Where(d => d != null && diagnosticIds.Contains(d.Id)).ToImmutableArray(); } } return ImmutableArray<Diagnostic>.Empty; } /// <summary> /// Gets all the project-level diagnostics, i.e. diagnostics with no source location, in the given project filtered by <see cref="DiagnosticIds"/>. /// </summary> public Task<ImmutableArray<Diagnostic>> GetProjectDiagnosticsAsync(Project project) { if (project == null) { throw new ArgumentNullException(nameof(project)); } return GetProjectDiagnosticsAsync(project, includeAllDocumentDiagnostics: false); } /// <summary> /// Gets all the diagnostics in the given project filtered by <see cref="DiagnosticIds"/>. /// This includes both document-level diagnostics for all documents in the given project and project-level diagnostics, i.e. diagnostics with no source location, in the given project. /// </summary> public Task<ImmutableArray<Diagnostic>> GetAllDiagnosticsAsync(Project project) { if (project == null) { throw new ArgumentNullException(nameof(project)); } return GetProjectDiagnosticsAsync(project, includeAllDocumentDiagnostics: true); } /// <summary> /// Gets all the project diagnostics in the given project filtered by <see cref="DiagnosticIds"/>. /// If <paramref name="includeAllDocumentDiagnostics"/> is false, then returns only project-level diagnostics which have no source location. /// Otherwise, returns all diagnostics in the project, including the document diagnostics for all documents in the given project. /// </summary> private async Task<ImmutableArray<Diagnostic>> GetProjectDiagnosticsAsync(Project project, bool includeAllDocumentDiagnostics) { Contract.ThrowIfNull(project); if (this.Project.Language != project.Language) { return ImmutableArray<Diagnostic>.Empty; } var getDiagnosticsTask = includeAllDocumentDiagnostics ? State.DiagnosticProvider.GetAllDiagnosticsAsync(project, CancellationToken) : State.DiagnosticProvider.GetProjectDiagnosticsAsync(project, CancellationToken); return await GetFilteredDiagnosticsAsync(getDiagnosticsTask, this.DiagnosticIds).ConfigureAwait(false); } /// <summary> /// Gets a new <see cref="FixAllContext"/> with the given cancellationToken. /// </summary> public FixAllContext WithCancellationToken(CancellationToken cancellationToken) { // TODO: We should change this API to be a virtual method, as the class is not sealed. if (this.CancellationToken == cancellationToken) { return this; } return new FixAllContext(State, this.ProgressTracker, cancellationToken); } internal FixAllContext WithScope(FixAllScope scope) => this.WithState(State.WithScope(scope)); internal FixAllContext WithProject(Project project) => this.WithState(State.WithProject(project)); internal FixAllContext WithDocument(Document? document) => this.WithState(State.WithDocument(document)); private FixAllContext WithState(FixAllState state) => this.State == state ? this : new FixAllContext(state, ProgressTracker, CancellationToken); internal Task<ImmutableDictionary<Document, ImmutableArray<Diagnostic>>> GetDocumentDiagnosticsToFixAsync() => DiagnosticProvider.GetDocumentDiagnosticsToFixAsync(this); internal Task<ImmutableDictionary<Project, ImmutableArray<Diagnostic>>> GetProjectDiagnosticsToFixAsync() => DiagnosticProvider.GetProjectDiagnosticsToFixAsync(this); } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Test/Emit/Attributes/InternalsVisibleToAndStrongNameTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Roslyn.Test.Utilities.SigningTestHelpers; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class InternalsVisibleToAndStrongNameTests : CSharpTestBase { public static IEnumerable<object[]> AllProviderParseOptions { get { if (ExecutionConditionUtil.IsWindows) { return new[] { new object[] { TestOptions.Regular }, new object[] { TestOptions.RegularWithLegacyStrongName } }; } return SpecializedCollections.SingletonEnumerable(new object[] { TestOptions.Regular }); } } #region Helpers public InternalsVisibleToAndStrongNameTests() { SigningTestHelpers.InstallKey(); } private static readonly string s_keyPairFile = SigningTestHelpers.KeyPairFile; private static readonly string s_publicKeyFile = SigningTestHelpers.PublicKeyFile; private static readonly ImmutableArray<byte> s_publicKey = SigningTestHelpers.PublicKey; private static StrongNameProvider GetProviderWithPath(string keyFilePath) => new DesktopStrongNameProvider(ImmutableArray.Create(keyFilePath), strongNameFileSystem: new VirtualizedStrongNameFileSystem()); #endregion #region Naming Tests [WorkItem(529419, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529419")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void AssemblyKeyFileAttributeNotExistFile(CSharpParseOptions parseOptions) { string source = @" using System; using System.Reflection; [assembly: AssemblyKeyFile(""MyKey.snk"")] [assembly: AssemblyKeyName(""Key Name"")] public class Test { public static void Main() { Console.Write(""Hello World!""); } } "; // Dev11 RC gives error now (CS1548) + two warnings // Diagnostic(ErrorCode.WRN_UseSwitchInsteadOfAttribute).WithArguments(@"/keyfile", "AssemblyKeyFile"), // Diagnostic(ErrorCode.WRN_UseSwitchInsteadOfAttribute).WithArguments(@"/keycontainer", "AssemblyKeyName") var c = CreateCompilation(source, options: TestOptions.ReleaseDll.WithStrongNameProvider(new DesktopStrongNameProvider()), parseOptions: parseOptions); c.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments("MyKey.snk", CodeAnalysisResources.FileNotFound)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFromKeyFileAttribute(CSharpParseOptions parseOptions) { var x = s_keyPairFile; string s = String.Format("{0}{1}{2}", @"[assembly: System.Reflection.AssemblyKeyFile(@""", x, @""")] public class C {}"); var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); other.VerifyDiagnostics(); Assert.True(ByteSequenceComparer.Equals(s_publicKey, other.Assembly.Identity.PublicKey)); CompileAndVerify(other, symbolValidator: (ModuleSymbol m) => { bool haveAttribute = false; foreach (var attrData in m.ContainingAssembly.GetAttributes()) { if (attrData.IsTargetAttribute(m.ContainingAssembly, AttributeDescription.AssemblyKeyFileAttribute)) { haveAttribute = true; break; } } Assert.True(haveAttribute); }); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFromKeyFileAttribute_AssemblyKeyFileResolver(CSharpParseOptions parseOptions) { string keyFileDir = Path.GetDirectoryName(s_keyPairFile); string keyFileName = Path.GetFileName(s_keyPairFile); string s = string.Format("{0}{1}{2}", @"[assembly: System.Reflection.AssemblyKeyFile(@""", keyFileName, @""")] public class C {}"); var syntaxTree = Parse(s, @"IVTAndStrongNameTests\AnotherTempDir\temp.cs", parseOptions); // verify failure with default assembly key file resolver var comp = CreateCompilation(syntaxTree, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments(keyFileName, "Assembly signing not supported.")); Assert.True(comp.Assembly.Identity.PublicKey.IsEmpty); // verify success with custom assembly key file resolver with keyFileDir added to search paths comp = CSharpCompilation.Create( GetUniqueName(), new[] { syntaxTree }, new[] { MscorlibRef }, TestOptions.ReleaseDll.WithStrongNameProvider(GetProviderWithPath(keyFileDir))); comp.VerifyDiagnostics(); Assert.True(ByteSequenceComparer.Equals(s_publicKey, comp.Assembly.Identity.PublicKey)); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestHasWindowsPaths)] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFromKeyFileAttribute_AssemblyKeyFileResolver_RelativeToCurrentParent(CSharpParseOptions parseOptions) { string keyFileDir = Path.GetDirectoryName(s_keyPairFile); string keyFileName = Path.GetFileName(s_keyPairFile); string s = String.Format("{0}{1}{2}", @"[assembly: System.Reflection.AssemblyKeyFile(@""..\", keyFileName, @""")] public class C {}"); var syntaxTree = Parse(s, @"IVTAndStrongNameTests\AnotherTempDir\temp.cs", parseOptions); // verify failure with default assembly key file resolver var comp = CreateCompilation(syntaxTree, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // error CS7027: Error extracting public key from file '..\KeyPairFile.snk' -- File not found. Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments(@"..\" + keyFileName, "Assembly signing not supported.")); Assert.True(comp.Assembly.Identity.PublicKey.IsEmpty); // verify success with custom assembly key file resolver with keyFileDir\TempSubDir added to search paths comp = CSharpCompilation.Create( GetUniqueName(), new[] { syntaxTree }, new[] { MscorlibRef }, TestOptions.ReleaseDll.WithStrongNameProvider(GetProviderWithPath(PathUtilities.CombineAbsoluteAndRelativePaths(keyFileDir, @"TempSubDir\")))); Assert.Empty(comp.GetDiagnostics()); Assert.True(ByteSequenceComparer.Equals(s_publicKey, comp.Assembly.Identity.PublicKey)); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestHasWindowsPaths)] public void SigningNotAvailable001() { string keyFileDir = Path.GetDirectoryName(s_keyPairFile); string keyFileName = Path.GetFileName(s_keyPairFile); string s = String.Format("{0}{1}{2}", @"[assembly: System.Reflection.AssemblyKeyFile(@""..\", keyFileName, @""")] public class C {}"); var syntaxTree = Parse(s, @"IVTAndStrongNameTests\AnotherTempDir\temp.cs", TestOptions.RegularWithLegacyStrongName); var provider = new TestDesktopStrongNameProvider( ImmutableArray.Create(PathUtilities.CombineAbsoluteAndRelativePaths(keyFileDir, @"TempSubDir\")), new VirtualizedStrongNameFileSystem()) { GetStrongNameInterfaceFunc = () => throw new DllNotFoundException("aaa.dll not found.") }; var options = TestOptions.ReleaseDll.WithStrongNameProvider(provider); // verify failure var comp = CreateCompilation( assemblyName: GetUniqueName(), source: new[] { syntaxTree }, options: options); comp.VerifyEmitDiagnostics( // error CS7027: Error signing output with public key from file '..\KeyPair_6187d0d6-f691-47fd-985b-03570bc0668d.snk' -- aaa.dll not found. Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments("..\\" + keyFileName, "aaa.dll not found.").WithLocation(1, 1) ); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFromKeyContainerAttribute(CSharpParseOptions parseOptions) { var x = s_keyPairFile; string s = @"[assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); other.VerifyDiagnostics(); Assert.True(ByteSequenceComparer.Equals(s_publicKey, other.Assembly.Identity.PublicKey)); CompileAndVerify(other, symbolValidator: (ModuleSymbol m) => { bool haveAttribute = false; foreach (var attrData in m.ContainingAssembly.GetAttributes()) { if (attrData.IsTargetAttribute(m.ContainingAssembly, AttributeDescription.AssemblyKeyNameAttribute)) { haveAttribute = true; break; } } Assert.True(haveAttribute); }); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFromKeyFileOptions(CSharpParseOptions parseOptions) { string s = "public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); other.VerifyDiagnostics(); Assert.True(ByteSequenceComparer.Equals(s_publicKey, other.Assembly.Identity.PublicKey)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFromKeyFileOptions_ReferenceResolver(CSharpParseOptions parseOptions) { string keyFileDir = Path.GetDirectoryName(s_keyPairFile); string keyFileName = Path.GetFileName(s_keyPairFile); string s = "public class C {}"; var syntaxTree = Parse(s, @"IVTAndStrongNameTests\AnotherTempDir\temp.cs"); // verify failure with default resolver var comp = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(keyFileName), parseOptions: parseOptions); comp.VerifyDiagnostics( // error CS7027: Error extracting public key from file 'KeyPairFile.snk' -- File not found. Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments(keyFileName, CodeAnalysisResources.FileNotFound)); Assert.True(comp.Assembly.Identity.PublicKey.IsEmpty); // verify success with custom assembly key file resolver with keyFileDir added to search paths comp = CSharpCompilation.Create( GetUniqueName(), new[] { syntaxTree }, new[] { MscorlibRef }, TestOptions.ReleaseDll.WithCryptoKeyFile(keyFileName).WithStrongNameProvider(GetProviderWithPath(keyFileDir))); Assert.Empty(comp.GetDiagnostics()); Assert.True(ByteSequenceComparer.Equals(s_publicKey, comp.Assembly.Identity.PublicKey)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFromKeyFileOptionsJustPublicKey(CSharpParseOptions parseOptions) { string s = "public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithDelaySign(true), parseOptions: parseOptions); other.VerifyDiagnostics(); Assert.True(ByteSequenceComparer.Equals(TestResources.General.snPublicKey.AsImmutableOrNull(), other.Assembly.Identity.PublicKey)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFromKeyFileOptionsJustPublicKey_ReferenceResolver(CSharpParseOptions parseOptions) { string publicKeyFileDir = Path.GetDirectoryName(s_publicKeyFile); string publicKeyFileName = Path.GetFileName(s_publicKeyFile); string s = "public class C {}"; var syntaxTree = Parse(s, @"IVTAndStrongNameTests\AnotherTempDir\temp.cs"); // verify failure with default resolver var comp = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(publicKeyFileName).WithDelaySign(true), parseOptions: parseOptions); comp.VerifyDiagnostics( // error CS7027: Error extracting public key from file 'PublicKeyFile.snk' -- File not found. Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments(publicKeyFileName, CodeAnalysisResources.FileNotFound), // warning CS7033: Delay signing was specified and requires a public key, but no public key was specified Diagnostic(ErrorCode.WRN_DelaySignButNoKey) ); Assert.True(comp.Assembly.Identity.PublicKey.IsEmpty); // verify success with custom assembly key file resolver with publicKeyFileDir added to search paths comp = CSharpCompilation.Create( GetUniqueName(), new[] { syntaxTree }, new[] { MscorlibRef }, TestOptions.ReleaseDll.WithCryptoKeyFile(publicKeyFileName).WithDelaySign(true).WithStrongNameProvider(GetProviderWithPath(publicKeyFileDir))); Assert.Empty(comp.GetDiagnostics()); Assert.True(ByteSequenceComparer.Equals(s_publicKey, comp.Assembly.Identity.PublicKey)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFileNotFoundOptions(CSharpParseOptions parseOptions) { string s = "public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile("goo"), parseOptions: parseOptions); other.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments("goo", CodeAnalysisResources.FileNotFound)); Assert.True(other.Assembly.Identity.PublicKey.IsEmpty); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFileBogusOptions(CSharpParseOptions parseOptions) { var tempFile = Temp.CreateFile().WriteAllBytes(new byte[] { 1, 2, 3, 4 }); string s = "public class C {}"; CSharpCompilation other = CreateCompilation(s, options: TestOptions.ReleaseDll.WithCryptoKeyFile(tempFile.Path), parseOptions: parseOptions); //TODO check for specific error Assert.NotEmpty(other.GetDiagnostics()); Assert.True(other.Assembly.Identity.PublicKey.IsEmpty); } [WorkItem(5662, "https://github.com/dotnet/roslyn/issues/5662")] [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyContainerBogusOptions(CSharpParseOptions parseOptions) { string s = "public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyContainer("goo"), parseOptions: parseOptions); // error CS7028: Error signing output with public key from container 'goo' -- Keyset does not exist (Exception from HRESULT: 0x80090016) var err = other.GetDiagnostics().Single(); Assert.Equal((int)ErrorCode.ERR_PublicKeyContainerFailure, err.Code); Assert.Equal(2, err.Arguments.Count); Assert.Equal("goo", err.Arguments[0]); Assert.True(((string)err.Arguments[1]).EndsWith("0x80090016)", StringComparison.Ordinal), (string)err.Arguments[1]); Assert.True(other.Assembly.Identity.PublicKey.IsEmpty); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void KeyFileAttributeOptionConflict(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Reflection.AssemblyKeyFile(""bogus"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); other.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_CmdOptionConflictsSource).WithArguments("CryptoKeyFile", "System.Reflection.AssemblyKeyFileAttribute")); Assert.True(ByteSequenceComparer.Equals(s_publicKey, other.Assembly.Identity.PublicKey)); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void KeyContainerAttributeOptionConflict(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Reflection.AssemblyKeyName(""bogus"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyContainer("RoslynTestContainer"), parseOptions: parseOptions); other.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_CmdOptionConflictsSource).WithArguments("CryptoKeyContainer", "System.Reflection.AssemblyKeyNameAttribute")); Assert.True(ByteSequenceComparer.Equals(s_publicKey, other.Assembly.Identity.PublicKey)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void KeyFileAttributeEmpty(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Reflection.AssemblyKeyFile("""")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); Assert.True(other.Assembly.Identity.PublicKey.IsEmpty); other.VerifyDiagnostics(); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void KeyContainerEmpty(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Reflection.AssemblyKeyName("""")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); Assert.True(other.Assembly.Identity.PublicKey.IsEmpty); other.VerifyDiagnostics(); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PublicKeyFromOptions_DelaySigned(CSharpParseOptions parseOptions) { string source = @" [assembly: System.Reflection.AssemblyDelaySign(true)] public class C {}"; var c = CreateCompilation(source, options: TestOptions.ReleaseDll.WithCryptoPublicKey(s_publicKey), parseOptions: parseOptions); c.VerifyDiagnostics(); Assert.True(ByteSequenceComparer.Equals(s_publicKey, c.Assembly.Identity.PublicKey)); var metadata = ModuleMetadata.CreateFromImage(c.EmitToArray()); var identity = metadata.Module.ReadAssemblyIdentityOrThrow(); Assert.True(identity.HasPublicKey); AssertEx.Equal(identity.PublicKey, s_publicKey); Assert.Equal(CorFlags.ILOnly, metadata.Module.PEReaderOpt.PEHeaders.CorHeader.Flags); } [WorkItem(9150, "https://github.com/dotnet/roslyn/issues/9150")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PublicKeyFromOptions_PublicSign(CSharpParseOptions parseOptions) { // attributes are ignored string source = @" [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] [assembly: System.Reflection.AssemblyKeyFile(""some file"")] public class C {} "; var c = CreateCompilation(source, options: TestOptions.ReleaseDll.WithCryptoPublicKey(s_publicKey).WithPublicSign(true), parseOptions: parseOptions); c.VerifyDiagnostics( // warning CS7103: Attribute 'System.Reflection.AssemblyKeyNameAttribute' is ignored when public signing is specified. Diagnostic(ErrorCode.WRN_AttributeIgnoredWhenPublicSigning).WithArguments("System.Reflection.AssemblyKeyNameAttribute").WithLocation(1, 1), // warning CS7103: Attribute 'System.Reflection.AssemblyKeyFileAttribute' is ignored when public signing is specified. Diagnostic(ErrorCode.WRN_AttributeIgnoredWhenPublicSigning).WithArguments("System.Reflection.AssemblyKeyFileAttribute").WithLocation(1, 1) ); Assert.True(ByteSequenceComparer.Equals(s_publicKey, c.Assembly.Identity.PublicKey)); var metadata = ModuleMetadata.CreateFromImage(c.EmitToArray()); var identity = metadata.Module.ReadAssemblyIdentityOrThrow(); Assert.True(identity.HasPublicKey); AssertEx.Equal(identity.PublicKey, s_publicKey); Assert.Equal(CorFlags.ILOnly | CorFlags.StrongNameSigned, metadata.Module.PEReaderOpt.PEHeaders.CorHeader.Flags); c = CreateCompilation(source, options: TestOptions.SigningReleaseModule.WithCryptoPublicKey(s_publicKey).WithPublicSign(true), parseOptions: parseOptions); c.VerifyDiagnostics( // error CS8201: Public signing is not supported for netmodules. Diagnostic(ErrorCode.ERR_PublicSignNetModule).WithLocation(1, 1) ); c = CreateCompilation(source, options: TestOptions.SigningReleaseModule.WithCryptoKeyFile(s_publicKeyFile).WithPublicSign(true), parseOptions: parseOptions); c.VerifyDiagnostics( // error CS7091: Attribute 'System.Reflection.AssemblyKeyFileAttribute' given in a source file conflicts with option 'CryptoKeyFile'. Diagnostic(ErrorCode.ERR_CmdOptionConflictsSource).WithArguments("System.Reflection.AssemblyKeyFileAttribute", "CryptoKeyFile").WithLocation(1, 1), // error CS8201: Public signing is not supported for netmodules. Diagnostic(ErrorCode.ERR_PublicSignNetModule).WithLocation(1, 1) ); var snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey); string source1 = @" [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] [assembly: System.Reflection.AssemblyKeyFile(@""" + snk.Path + @""")] public class C {} "; c = CreateCompilation(source1, options: TestOptions.SigningReleaseModule.WithCryptoKeyFile(snk.Path).WithPublicSign(true)); c.VerifyDiagnostics( // error CS8201: Public signing is not supported for netmodules. Diagnostic(ErrorCode.ERR_PublicSignNetModule).WithLocation(1, 1) ); } [WorkItem(9150, "https://github.com/dotnet/roslyn/issues/9150")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void KeyFileFromAttributes_PublicSign(CSharpParseOptions parseOptions) { string source = @" [assembly: System.Reflection.AssemblyKeyFile(""test.snk"")] public class C {} "; var c = CreateCompilation(source, options: TestOptions.ReleaseDll.WithPublicSign(true), parseOptions: parseOptions); c.VerifyDiagnostics( // warning CS7103: Attribute 'System.Reflection.AssemblyKeyFileAttribute' is ignored when public signing is specified. Diagnostic(ErrorCode.WRN_AttributeIgnoredWhenPublicSigning).WithArguments("System.Reflection.AssemblyKeyFileAttribute").WithLocation(1, 1), // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1) ); Assert.True(c.Options.PublicSign); } [WorkItem(9150, "https://github.com/dotnet/roslyn/issues/9150")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void KeyContainerFromAttributes_PublicSign(CSharpParseOptions parseOptions) { string source = @" [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class C {} "; var c = CreateCompilation(source, options: TestOptions.ReleaseDll.WithPublicSign(true), parseOptions: parseOptions); c.VerifyDiagnostics( // warning CS7103: Attribute 'System.Reflection.AssemblyKeyNameAttribute' is ignored when public signing is specified. Diagnostic(ErrorCode.WRN_AttributeIgnoredWhenPublicSigning).WithArguments("System.Reflection.AssemblyKeyNameAttribute").WithLocation(1, 1), // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1) ); Assert.True(c.Options.PublicSign); } private void VerifySignedBitSetAfterEmit(Compilation comp, bool expectedToBeSigned = true) { using (var outStream = comp.EmitToStream()) { outStream.Position = 0; using (var reader = new PEReader(outStream)) { var flags = reader.PEHeaders.CorHeader.Flags; Assert.Equal(expectedToBeSigned, flags.HasFlag(CorFlags.StrongNameSigned)); } } } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SnkFile_PublicSign(CSharpParseOptions parseOptions) { var snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey); var comp = CreateCompilation("public class C{}", options: TestOptions.ReleaseDll .WithCryptoKeyFile(snk.Path) .WithPublicSign(true), parseOptions: parseOptions); comp.VerifyDiagnostics(); Assert.True(comp.Options.PublicSign); Assert.Null(comp.Options.DelaySign); Assert.False(comp.IsRealSigned); Assert.NotNull(comp.Options.CryptoKeyFile); VerifySignedBitSetAfterEmit(comp); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PublicKeyFile_PublicSign(CSharpParseOptions parseOptions) { var pubKeyFile = Temp.CreateFile().WriteAllBytes(TestResources.General.snPublicKey); var comp = CreateCompilation("public class C {}", options: TestOptions.ReleaseDll .WithCryptoKeyFile(pubKeyFile.Path) .WithPublicSign(true), parseOptions: parseOptions); comp.VerifyDiagnostics(); Assert.True(comp.Options.PublicSign); Assert.Null(comp.Options.DelaySign); Assert.False(comp.IsRealSigned); Assert.NotNull(comp.Options.CryptoKeyFile); VerifySignedBitSetAfterEmit(comp); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PublicSign_DelaySignAttribute(CSharpParseOptions parseOptions) { var pubKeyFile = Temp.CreateFile().WriteAllBytes(TestResources.General.snPublicKey); var comp = CreateCompilation(@" [assembly: System.Reflection.AssemblyDelaySign(true)] public class C {}", options: TestOptions.ReleaseDll .WithCryptoKeyFile(pubKeyFile.Path) .WithPublicSign(true), parseOptions: parseOptions); comp.VerifyDiagnostics( // warning CS1616: Option 'PublicSign' overrides attribute 'System.Reflection.AssemblyDelaySignAttribute' given in a source file or added module Diagnostic(ErrorCode.WRN_CmdOptionConflictsSource).WithArguments("PublicSign", "System.Reflection.AssemblyDelaySignAttribute").WithLocation(1, 1)); Assert.True(comp.Options.PublicSign); Assert.Null(comp.Options.DelaySign); Assert.False(comp.IsRealSigned); Assert.NotNull(comp.Options.CryptoKeyFile); VerifySignedBitSetAfterEmit(comp); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void KeyContainerNoSNProvider_PublicSign(CSharpParseOptions parseOptions) { var comp = CreateCompilation("public class C {}", options: TestOptions.ReleaseDll .WithCryptoKeyContainer("roslynTestContainer") .WithPublicSign(true), parseOptions: parseOptions); comp.VerifyDiagnostics( // error CS7102: Compilation options 'PublicSign' and 'CryptoKeyContainer' can't both be specified at the same time. Diagnostic(ErrorCode.ERR_MutuallyExclusiveOptions).WithArguments("PublicSign", "CryptoKeyContainer").WithLocation(1, 1), // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void KeyContainerDesktopProvider_PublicSign(CSharpParseOptions parseOptions) { var comp = CreateCompilation("public class C {}", options: TestOptions.SigningReleaseDll .WithCryptoKeyContainer("roslynTestContainer") .WithPublicSign(true), parseOptions: parseOptions); comp.VerifyDiagnostics( // error CS7102: Compilation options 'PublicSign' and 'CryptoKeyContainer' can't both be specified at the same time. Diagnostic(ErrorCode.ERR_MutuallyExclusiveOptions).WithArguments("PublicSign", "CryptoKeyContainer").WithLocation(1, 1), // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1)); Assert.True(comp.Options.PublicSign); Assert.Null(comp.Options.DelaySign); Assert.False(comp.IsRealSigned); Assert.NotNull(comp.Options.CryptoKeyContainer); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PublicSignAndDelaySign(CSharpParseOptions parseOptions) { var snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey); var comp = CreateCompilation("public class C {}", options: TestOptions.ReleaseDll .WithPublicSign(true) .WithDelaySign(true) .WithCryptoKeyFile(snk.Path), parseOptions: parseOptions); comp.VerifyDiagnostics( // error CS7102: Compilation options 'PublicSign' and 'DelaySign' can't both be specified at the same time. Diagnostic(ErrorCode.ERR_MutuallyExclusiveOptions).WithArguments("PublicSign", "DelaySign").WithLocation(1, 1)); Assert.True(comp.Options.PublicSign); Assert.True(comp.Options.DelaySign); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PublicSignAndDelaySignFalse(CSharpParseOptions parseOptions) { var snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey); var comp = CreateCompilation("public class C {}", options: TestOptions.ReleaseDll .WithPublicSign(true) .WithDelaySign(false) .WithCryptoKeyFile(snk.Path), parseOptions: parseOptions); comp.VerifyDiagnostics(); Assert.True(comp.Options.PublicSign); Assert.False(comp.Options.DelaySign); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PublicSignNoKey(CSharpParseOptions parseOptions) { var comp = CreateCompilation("public class C {}", options: TestOptions.ReleaseDll.WithPublicSign(true), parseOptions: parseOptions); comp.VerifyDiagnostics( // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1)); Assert.True(comp.Options.PublicSign); Assert.True(comp.Assembly.PublicKey.IsDefaultOrEmpty); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PublicKeyFromOptions_InvalidCompilationOptions(CSharpParseOptions parseOptions) { string source = @"public class C {}"; var c = CreateCompilation(source, options: TestOptions.SigningReleaseDll. WithCryptoPublicKey(ImmutableArray.Create<byte>(1, 2, 3)). WithCryptoKeyContainer("roslynTestContainer"). WithCryptoKeyFile("file.snk"), parseOptions: parseOptions); c.VerifyDiagnostics( // error CS7102: Compilation options 'CryptoPublicKey' and 'CryptoKeyFile' can't both be specified at the same time. Diagnostic(ErrorCode.ERR_MutuallyExclusiveOptions).WithArguments("CryptoPublicKey", "CryptoKeyFile").WithLocation(1, 1), // error CS7102: Compilation options 'CryptoPublicKey' and 'CryptoKeyContainer' can't both be specified at the same time. Diagnostic(ErrorCode.ERR_MutuallyExclusiveOptions).WithArguments("CryptoPublicKey", "CryptoKeyContainer").WithLocation(1, 1), // error CS7088: Invalid 'CryptoPublicKey' value: '01-02-03'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("CryptoPublicKey", "01-02-03").WithLocation(1, 1)); } #endregion #region IVT Access Checking [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IVTBasicCompilation(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""WantsIVTAccess"")] public class C { internal void Goo() {} }"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll, assemblyName: "Paul", parseOptions: parseOptions); var c = CreateCompilation( @"public class A { internal class B { protected B(C o) { o.Goo(); } } }", new[] { new CSharpCompilationReference(other) }, assemblyName: "WantsIVTAccessButCantHave", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); //compilation should not succeed, and internals should not be imported. c.VerifyDiagnostics( // (7,15): error CS0122: 'C.Goo()' is inaccessible due to its protection level // o.Goo(); Diagnostic(ErrorCode.ERR_BadAccess, "Goo").WithArguments("C.Goo()").WithLocation(7, 15) ); var c2 = CreateCompilation( @"public class A { internal class B { protected B(C o) { o.Goo(); } } }", new[] { new CSharpCompilationReference(other) }, assemblyName: "WantsIVTAccess", options: TestOptions.SigningReleaseDll); Assert.Empty(c2.GetDiagnostics()); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IVTBasicMetadata(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""WantsIVTAccess"")] public class C { internal void Goo() {} }"; var otherStream = CreateCompilation(s, options: TestOptions.SigningReleaseDll, parseOptions: parseOptions).EmitToStream(); var c = CreateCompilation( @"public class A { internal class B { protected B(C o) { o.Goo(); } } }", references: new[] { AssemblyMetadata.CreateFromStream(otherStream, leaveOpen: true).GetReference() }, assemblyName: "WantsIVTAccessButCantHave", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); //compilation should not succeed, and internals should not be imported. c.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Goo").WithArguments("C", "Goo")); otherStream.Position = 0; var c2 = CreateCompilation( @"public class A { internal class B { protected B(C o) { o.Goo(); } } }", new[] { MetadataReference.CreateFromStream(otherStream) }, assemblyName: "WantsIVTAccess", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); Assert.Empty(c2.GetDiagnostics()); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void IVTSigned(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] public class C { internal void Goo() {} }"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), assemblyName: "Paul", parseOptions: parseOptions); other.VerifyDiagnostics(); var requestor = CreateCompilation( @"public class A { internal class B { protected B(C o) { o.Goo(); } } }", new MetadataReference[] { new CSharpCompilationReference(other) }, TestOptions.SigningReleaseDll.WithCryptoKeyContainer("roslynTestContainer"), assemblyName: "John", parseOptions: parseOptions); Assert.Empty(requestor.GetDiagnostics()); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IVTNotBothSigned_CStoCS(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] public class C { internal void Goo() {} }"; var other = CreateCompilation(s, assemblyName: "Paul", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); other.VerifyDiagnostics(); var requestor = CreateCompilation( @"public class A { internal class B { protected B(C o) { o.Goo(); } } }", references: new[] { new CSharpCompilationReference(other) }, assemblyName: "John", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); // We allow John to access Paul's internal Goo even though strong-named John should not be referencing weak-named Paul. // Paul has, after all, specifically granted access to John. // During emit time we should produce an error that says that a strong-named assembly cannot reference // a weak-named assembly. But the C# compiler doesn't currently do that. See https://github.com/dotnet/roslyn/issues/26722 requestor.VerifyDiagnostics(); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void CS0281Method(CSharpParseOptions parseOptions) { var friendClass = CreateCompilation(@" using System.Runtime.CompilerServices; [ assembly: InternalsVisibleTo(""cs0281, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"") ] public class PublicClass { internal static void InternalMethod() { } protected static void ProtectedMethod() { } private static void PrivateMethod() { } internal protected static void InternalProtectedMethod() { } private protected static void PrivateProtectedMethod() { } }", assemblyName: "Paul", parseOptions: parseOptions); string cs0281 = @" public class Test { static void Main () { PublicClass.InternalMethod(); PublicClass.ProtectedMethod(); PublicClass.PrivateMethod(); PublicClass.InternalProtectedMethod(); PublicClass.PrivateProtectedMethod(); } }"; var other = CreateCompilation(cs0281, references: new[] { friendClass.EmitToImageReference() }, assemblyName: "cs0281", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); other.VerifyDiagnostics( // (7,15): error CS0281: Friend access was granted by 'Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null', but the public key of the output assembly ('') does not match that specified by the InternalsVisibleTo attribute in the granting assembly. // PublicClass.InternalMethod(); Diagnostic(ErrorCode.ERR_FriendRefNotEqualToThis, "InternalMethod").WithArguments("Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "").WithLocation(7, 15), // (8,21): error CS0122: 'PublicClass.ProtectedMethod()' is inaccessible due to its protection level // PublicClass.ProtectedMethod(); Diagnostic(ErrorCode.ERR_BadAccess, "ProtectedMethod").WithArguments("PublicClass.ProtectedMethod()").WithLocation(8, 21), // (9,21): error CS0117: 'PublicClass' does not contain a definition for 'PrivateMethod' // PublicClass.PrivateMethod(); Diagnostic(ErrorCode.ERR_NoSuchMember, "PrivateMethod").WithArguments("PublicClass", "PrivateMethod").WithLocation(9, 21), // (10,21): error CS0281: Friend access was granted by 'Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null', but the public key of the output assembly ('') does not match that specified by the InternalsVisibleTo attribute in the granting assembly. // PublicClass.InternalProtectedMethod(); Diagnostic(ErrorCode.ERR_FriendRefNotEqualToThis, "InternalProtectedMethod").WithArguments("Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "").WithLocation(10, 21), // (11,21): error CS0281: Friend access was granted by 'Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null', but the public key of the output assembly ('') does not match that specified by the InternalsVisibleTo attribute in the granting assembly. // PublicClass.PrivateProtectedMethod(); Diagnostic(ErrorCode.ERR_FriendRefNotEqualToThis, "PrivateProtectedMethod").WithArguments("Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "").WithLocation(11, 21) ); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void CS0281Class(CSharpParseOptions parseOptions) { var friendClass = CreateCompilation(@" using System.Runtime.CompilerServices; [ assembly: InternalsVisibleTo(""cs0281, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"") ] internal class FriendClass { public static void MyMethod() { } }", assemblyName: "Paul", parseOptions: parseOptions); string cs0281 = @" public class Test { static void Main () { FriendClass.MyMethod (); } }"; var other = CreateCompilation(cs0281, references: new[] { friendClass.EmitToImageReference() }, assemblyName: "cs0281", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); // (7, 3): error CS0281: Friend access was granted by 'Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null', but the public key of the output assembly ('') // does not match that specified by the InternalsVisibleTo attribute in the granting assembly. // FriendClass.MyMethod (); other.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_FriendRefNotEqualToThis, "FriendClass").WithArguments("Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "").WithLocation(7, 3) ); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IVTNotBothSigned_VBtoCS(CSharpParseOptions parseOptions) { string s = @"<assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")> Public Class C Friend Sub Goo() End Sub End Class"; var other = VisualBasic.VisualBasicCompilation.Create( syntaxTrees: new[] { VisualBasic.VisualBasicSyntaxTree.ParseText(s) }, references: new[] { MscorlibRef_v4_0_30316_17626 }, assemblyName: "Paul", options: new VisualBasic.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary).WithStrongNameProvider(DefaultDesktopStrongNameProvider)); other.VerifyDiagnostics(); var requestor = CreateCompilation( @"public class A { internal class B { protected B(C o) { o.Goo(); } } }", references: new[] { MetadataReference.CreateFromImage(other.EmitToArray()) }, assemblyName: "John", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); // We allow John to access Paul's internal Goo even though strong-named John should not be referencing weak-named Paul. // Paul has, after all, specifically granted access to John. // During emit time we should produce an error that says that a strong-named assembly cannot reference // a weak-named assembly. But the C# compiler doesn't currently do that. See https://github.com/dotnet/roslyn/issues/26722 requestor.VerifyDiagnostics(); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void IVTDeferredSuccess(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class CAttribute : System.Attribute { public CAttribute() {} }"; var other = CreateCompilation(s, assemblyName: "Paul", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); other.VerifyDiagnostics(); var requestor = CreateCompilation( @" [assembly: C()] //causes optimistic granting [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new[] { new CSharpCompilationReference(other) }, assemblyName: "John", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); Assert.True(ByteSequenceComparer.Equals(s_publicKey, requestor.Assembly.Identity.PublicKey)); Assert.Empty(requestor.GetDiagnostics()); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void IVTDeferredFailSignMismatch(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class CAttribute : System.Attribute { public CAttribute() {} }"; var other = CreateCompilation(s, assemblyName: "Paul", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); //not signed. cryptoKeyFile: KeyPairFile, other.VerifyDiagnostics(); var requestor = CreateCompilation( @" [assembly: C()] [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new[] { new CSharpCompilationReference(other) }, assemblyName: "John", options: TestOptions.SigningReleaseDll); Assert.True(ByteSequenceComparer.Equals(s_publicKey, requestor.Assembly.Identity.PublicKey)); requestor.VerifyDiagnostics(); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void IVTDeferredFailSignMismatch_AssemblyKeyName(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class AssemblyKeyNameAttribute : System.Attribute { public AssemblyKeyNameAttribute() {} }"; var other = CreateCompilation(s, assemblyName: "Paul", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); //not signed. cryptoKeyFile: KeyPairFile, other.VerifyDiagnostics(); var requestor = CreateCompilation( @" [assembly: AssemblyKeyName()] //causes optimistic granting [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new[] { new CSharpCompilationReference(other) }, assemblyName: "John", options: TestOptions.SigningReleaseDll); Assert.True(ByteSequenceComparer.Equals(s_publicKey, requestor.Assembly.Identity.PublicKey)); requestor.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_FriendRefSigningMismatch, arguments: new object[] { "Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" })); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void IVTDeferredFailKeyMismatch(CSharpParseOptions parseOptions) { //key is wrong in the first digit. correct key starts with 0 string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=10240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class CAttribute : System.Attribute { public CAttribute() {} }"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), assemblyName: "Paul", parseOptions: parseOptions); other.VerifyDiagnostics(); var requestor = CreateCompilation( @" [assembly: C()] [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new MetadataReference[] { new CSharpCompilationReference(other) }, assemblyName: "John", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); Assert.True(ByteSequenceComparer.Equals(s_publicKey, requestor.Assembly.Identity.PublicKey)); requestor.VerifyDiagnostics( // (2,12): error CS0122: 'CAttribute' is inaccessible due to its protection level // [assembly: C()] Diagnostic(ErrorCode.ERR_BadAccess, "C").WithArguments("CAttribute").WithLocation(2, 12) ); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void IVTDeferredFailKeyMismatch_AssemblyKeyName(CSharpParseOptions parseOptions) { //key is wrong in the first digit. correct key starts with 0 string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=10240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class AssemblyKeyNameAttribute : System.Attribute { public AssemblyKeyNameAttribute() {} }"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), assemblyName: "Paul", parseOptions: parseOptions); other.VerifyDiagnostics(); var requestor = CreateCompilation( @" [assembly: AssemblyKeyName()] [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new MetadataReference[] { new CSharpCompilationReference(other) }, assemblyName: "John", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); Assert.True(ByteSequenceComparer.Equals(s_publicKey, requestor.Assembly.Identity.PublicKey)); requestor.VerifyDiagnostics( // error CS0281: Friend access was granted by 'Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2', // but the public key of the output assembly ('John, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2') // does not match that specified by the InternalsVisibleTo attribute in the granting assembly. Diagnostic(ErrorCode.ERR_FriendRefNotEqualToThis) .WithArguments("Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "John, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2") .WithLocation(1, 1), // (2,12): error CS0122: 'AssemblyKeyNameAttribute' is inaccessible due to its protection level // [assembly: AssemblyKeyName()] Diagnostic(ErrorCode.ERR_BadAccess, "AssemblyKeyName").WithArguments("AssemblyKeyNameAttribute").WithLocation(2, 12) ); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void IVTSuccessThroughIAssembly(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class CAttribute : System.Attribute { public CAttribute() {} }"; var other = CreateCompilation(s, assemblyName: "Paul", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); other.VerifyDiagnostics(); var requestor = CreateCompilation( @" [assembly: C()] //causes optimistic granting [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new MetadataReference[] { new CSharpCompilationReference(other) }, options: TestOptions.SigningReleaseDll, assemblyName: "John", parseOptions: parseOptions); Assert.True(other.Assembly.GivesAccessTo(requestor.Assembly)); Assert.Empty(requestor.GetDiagnostics()); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void IVTDeferredFailKeyMismatchIAssembly(CSharpParseOptions parseOptions) { //key is wrong in the first digit. correct key starts with 0 string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=10240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class CAttribute : System.Attribute { public CAttribute() {} }"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), assemblyName: "Paul", parseOptions: parseOptions); other.VerifyDiagnostics(); var requestor = CreateCompilation( @" [assembly: C()] [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new MetadataReference[] { new CSharpCompilationReference(other) }, TestOptions.SigningReleaseDll, assemblyName: "John", parseOptions: parseOptions); Assert.False(other.Assembly.GivesAccessTo(requestor.Assembly)); requestor.VerifyDiagnostics( // (3,12): error CS0122: 'CAttribute' is inaccessible due to its protection level // [assembly: C()] Diagnostic(ErrorCode.ERR_BadAccess, "C").WithArguments("CAttribute").WithLocation(3, 12) ); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void IVTDeferredFailKeyMismatchIAssembly_AssemblyKeyName(CSharpParseOptions parseOptions) { //key is wrong in the first digit. correct key starts with 0 string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=10240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class AssemblyKeyNameAttribute : System.Attribute { public AssemblyKeyNameAttribute() {} }"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), assemblyName: "Paul", parseOptions: parseOptions); other.VerifyDiagnostics(); var requestor = CreateCompilation( @" [assembly: AssemblyKeyName()] [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new MetadataReference[] { new CSharpCompilationReference(other) }, TestOptions.SigningReleaseDll, assemblyName: "John", parseOptions: parseOptions); Assert.False(other.Assembly.GivesAccessTo(requestor.Assembly)); requestor.VerifyDiagnostics( // error CS0281: Friend access was granted by 'Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2', // but the public key of the output assembly ('John, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2') // does not match that specified by the InternalsVisibleTo attribute in the granting assembly. Diagnostic(ErrorCode.ERR_FriendRefNotEqualToThis) .WithArguments("Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "John, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2") .WithLocation(1, 1), // (3,12): error CS0122: 'AssemblyKeyNameAttribute' is inaccessible due to its protection level // [assembly: AssemblyKeyName()] Diagnostic(ErrorCode.ERR_BadAccess, "AssemblyKeyName").WithArguments("AssemblyKeyNameAttribute").WithLocation(3, 12) ); } [WorkItem(820450, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/820450")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IVTGivesAccessToUsingDifferentKeys(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] namespace ClassLibrary1 { internal class Class1 { } } "; var giver = CreateCompilation(s, assemblyName: "Paul", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(SigningTestHelpers.KeyPairFile2), parseOptions: parseOptions); giver.VerifyDiagnostics(); var requestor = CreateCompilation( @" namespace ClassLibrary2 { internal class A { public void Goo(ClassLibrary1.Class1 a) { } } }", new MetadataReference[] { new CSharpCompilationReference(giver) }, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), assemblyName: "John", parseOptions: parseOptions); Assert.True(giver.Assembly.GivesAccessTo(requestor.Assembly)); Assert.Empty(requestor.GetDiagnostics()); } #endregion #region IVT instantiations [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IVTHasCulture(CSharpParseOptions parseOptions) { var other = CreateCompilation( @" using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""WantsIVTAccess, Culture=neutral"")] public class C { static void Goo() {} } ", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); other.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_FriendAssemblyBadArgs, @"InternalsVisibleTo(""WantsIVTAccess, Culture=neutral"")").WithArguments("WantsIVTAccess, Culture=neutral")); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IVTNoKey(CSharpParseOptions parseOptions) { var other = CreateCompilation( @" using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""WantsIVTAccess"")] public class C { static void Main() {} } ", options: TestOptions.SigningReleaseExe.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); other.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_FriendAssemblySNReq, @"InternalsVisibleTo(""WantsIVTAccess"")").WithArguments("WantsIVTAccess")); } #endregion #region Signing [ConditionalTheory(typeof(DesktopOnly), Reason = "https://github.com/dotnet/coreclr/issues/21723")] [MemberData(nameof(AllProviderParseOptions))] public void MaxSizeKey(CSharpParseOptions parseOptions) { var pubKey = TestResources.General.snMaxSizePublicKeyString; string pubKeyToken = "1540923db30520b2"; var pubKeyTokenBytes = new byte[] { 0x15, 0x40, 0x92, 0x3d, 0xb3, 0x05, 0x20, 0xb2 }; var comp = CreateCompilation($@" using System; using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""MaxSizeComp2, PublicKey={pubKey}, PublicKeyToken={pubKeyToken}"")] internal class C {{ public static void M() {{ Console.WriteLine(""Called M""); }} }}", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(SigningTestHelpers.MaxSizeKeyFile), parseOptions: parseOptions); comp.VerifyEmitDiagnostics(); Assert.True(comp.IsRealSigned); VerifySignedBitSetAfterEmit(comp); Assert.Equal(TestResources.General.snMaxSizePublicKey, comp.Assembly.Identity.PublicKey); Assert.Equal<byte>(pubKeyTokenBytes, comp.Assembly.Identity.PublicKeyToken); var src = @" class D { public static void Main() { C.M(); } }"; var comp2 = CreateCompilation(src, references: new[] { comp.ToMetadataReference() }, assemblyName: "MaxSizeComp2", options: TestOptions.SigningReleaseExe.WithCryptoKeyFile(SigningTestHelpers.MaxSizeKeyFile), parseOptions: parseOptions); CompileAndVerify(comp2, expectedOutput: "Called M"); Assert.Equal(TestResources.General.snMaxSizePublicKey, comp2.Assembly.Identity.PublicKey); Assert.Equal<byte>(pubKeyTokenBytes, comp2.Assembly.Identity.PublicKeyToken); var comp3 = CreateCompilation(src, references: new[] { comp.EmitToImageReference() }, assemblyName: "MaxSizeComp2", options: TestOptions.SigningReleaseExe.WithCryptoKeyFile(SigningTestHelpers.MaxSizeKeyFile), parseOptions: parseOptions); CompileAndVerify(comp3, expectedOutput: "Called M"); Assert.Equal(TestResources.General.snMaxSizePublicKey, comp3.Assembly.Identity.PublicKey); Assert.Equal<byte>(pubKeyTokenBytes, comp3.Assembly.Identity.PublicKeyToken); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignIt(CSharpParseOptions parseOptions) { var other = CreateCompilation( @" public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.True(success.Success); } Assert.True(IsFileFullSigned(tempFile)); } private static bool IsFileFullSigned(TempFile file) { using (var metadata = new FileStream(file.Path, FileMode.Open)) { return ILValidation.IsStreamFullSigned(metadata); } } private void ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(MemoryStream moduleContents, AttributeDescription expectedModuleAttr, CSharpParseOptions parseOptions) { //a module doesn't get signed for real. It should have either a keyfile or keycontainer attribute //parked on a typeRef named 'AssemblyAttributesGoHere.' When the module is added to an assembly, the //resulting assembly is signed with the key referred to by the aforementioned attribute. EmitResult success; var tempFile = Temp.CreateFile(); moduleContents.Position = 0; using (var metadata = ModuleMetadata.CreateFromStream(moduleContents)) { var flags = metadata.Module.PEReaderOpt.PEHeaders.CorHeader.Flags; //confirm file does not claim to be signed Assert.Equal(0, (int)(flags & CorFlags.StrongNameSigned)); var corlibName = RuntimeUtilities.IsCoreClrRuntime ? "netstandard" : "mscorlib"; EntityHandle token = metadata.Module.GetTypeRef(metadata.Module.GetAssemblyRef(corlibName), "System.Runtime.CompilerServices", "AssemblyAttributesGoHere"); Assert.False(token.IsNil); //could the type ref be located? If not then the attribute's not there. var attrInfos = metadata.Module.FindTargetAttributes(token, expectedModuleAttr); Assert.Equal(1, attrInfos.Count()); var source = @" public class Z { }"; //now that the module checks out, ensure that adding it to a compilation outputting a dll //results in a signed assembly. var assemblyComp = CreateCompilation(source, new[] { metadata.GetReference() }, TestOptions.SigningReleaseDll, parseOptions: parseOptions); using (var finalStrm = tempFile.Open()) { success = assemblyComp.Emit(finalStrm); } } success.Diagnostics.Verify(); Assert.True(success.Success); Assert.True(IsFileFullSigned(tempFile)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyFileAttr(CSharpParseOptions parseOptions) { var x = s_keyPairFile; string s = String.Format("{0}{1}{2}", @"[assembly: System.Reflection.AssemblyKeyFile(@""", x, @""")] public class C {}"); var other = CreateCompilation(s, options: TestOptions.SigningReleaseModule); var outStrm = other.EmitToStream(); ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyFileAttribute, parseOptions); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyContainerAttr(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseModule); var outStrm = other.EmitToStream(); ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyNameAttribute, parseOptions); } [WorkItem(5665, "https://github.com/dotnet/roslyn/issues/5665")] [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyContainerBogus(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Reflection.AssemblyKeyName(""bogus"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseModule, parseOptions: parseOptions); //shouldn't have an error. The attribute's contents are checked when the module is added. var reference = other.EmitToImageReference(); s = @"class D {}"; other = CreateCompilation(s, new[] { reference }, TestOptions.SigningReleaseDll); // error CS7028: Error signing output with public key from container 'bogus' -- Keyset does not exist (Exception from HRESULT: 0x80090016) var err = other.GetDiagnostics().Single(); Assert.Equal((int)ErrorCode.ERR_PublicKeyContainerFailure, err.Code); Assert.Equal(2, err.Arguments.Count); Assert.Equal("bogus", err.Arguments[0]); Assert.True(((string)err.Arguments[1]).EndsWith("0x80090016)", StringComparison.Ordinal), (string)err.Arguments[1]); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyFileBogus(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Reflection.AssemblyKeyFile(""bogus"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseModule); //shouldn't have an error. The attribute's contents are checked when the module is added. var reference = other.EmitToImageReference(); s = @"class D {}"; other = CreateCompilation(s, new[] { reference }, TestOptions.SigningReleaseDll, parseOptions: parseOptions); other.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments("bogus", CodeAnalysisResources.FileNotFound)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void AttemptToStrongNameWithOnlyPublicKey(CSharpParseOptions parseOptions) { string s = "public class C {}"; var options = TestOptions.SigningReleaseDll.WithCryptoKeyFile(PublicKeyFile); var other = CreateCompilation(s, options: options, parseOptions: parseOptions); var outStrm = new MemoryStream(); var refStrm = new MemoryStream(); var success = other.Emit(outStrm, metadataPEStream: refStrm); Assert.False(success.Success); // The diagnostic contains a random file path, so just check the code. Assert.True(success.Diagnostics[0].Code == (int)ErrorCode.ERR_SignButNoPrivateKey); } [WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")] [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyContainerCmdLine(CSharpParseOptions parseOptions) { string s = "public class C {}"; var options = TestOptions.SigningReleaseModule.WithCryptoKeyContainer("roslynTestContainer"); var other = CreateCompilation(s, options: options); var outStrm = new MemoryStream(); var success = other.Emit(outStrm); Assert.True(success.Success); ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyNameAttribute, parseOptions); } [WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")] [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyContainerCmdLine_1(CSharpParseOptions parseOptions) { string s = @" [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class C {}"; var options = TestOptions.SigningReleaseModule.WithCryptoKeyContainer("roslynTestContainer"); var other = CreateCompilation(s, options: options, parseOptions: parseOptions); var outStrm = new MemoryStream(); var success = other.Emit(outStrm); Assert.True(success.Success); ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyNameAttribute, parseOptions); } [WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyContainerCmdLine_2(CSharpParseOptions parseOptions) { string s = @" [assembly: System.Reflection.AssemblyKeyName(""bogus"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseModule.WithCryptoKeyContainer("roslynTestContainer"), parseOptions: parseOptions); var outStrm = new MemoryStream(); var success = other.Emit(outStrm); Assert.False(success.Success); success.Diagnostics.Verify( // error CS7091: Attribute 'System.Reflection.AssemblyKeyNameAttribute' given in a source file conflicts with option 'CryptoKeyContainer'. Diagnostic(ErrorCode.ERR_CmdOptionConflictsSource).WithArguments("System.Reflection.AssemblyKeyNameAttribute", "CryptoKeyContainer") ); } [WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyFileCmdLine(CSharpParseOptions parseOptions) { string s = "public class C {}"; var options = TestOptions.SigningReleaseModule.WithCryptoKeyFile(s_keyPairFile); var other = CreateCompilation(s, options: options, parseOptions: parseOptions); var outStrm = new MemoryStream(); var success = other.Emit(outStrm); Assert.True(success.Success); ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyFileAttribute, parseOptions); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void BothLegacyAndNonLegacyGiveTheSameOutput(CSharpParseOptions parseOptions) { string s = "public class C {}"; var options = TestOptions.SigningReleaseDll .WithDeterministic(true) .WithModuleName("a.dll") .WithCryptoKeyFile(s_keyPairFile); var emitOptions = EmitOptions.Default.WithOutputNameOverride("a.dll"); var compilation = CreateCompilation(s, options: options, parseOptions: parseOptions); var stream = compilation.EmitToStream(emitOptions); stream.Position = 0; using (var metadata = AssemblyMetadata.CreateFromStream(stream)) { var key = metadata.GetAssembly().Identity.PublicKey; Assert.True(s_publicKey.SequenceEqual(key)); } } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignRefAssemblyKeyFileCmdLine(CSharpParseOptions parseOptions) { string s = "public class C {}"; var options = TestOptions.SigningDebugDll.WithCryptoKeyFile(s_keyPairFile); var other = CreateCompilation(s, options: options, parseOptions: parseOptions); var outStrm = new MemoryStream(); var refStrm = new MemoryStream(); var success = other.Emit(outStrm, metadataPEStream: refStrm); Assert.True(success.Success); outStrm.Position = 0; refStrm.Position = 0; Assert.True(ILValidation.IsStreamFullSigned(outStrm)); Assert.True(ILValidation.IsStreamFullSigned(refStrm)); } [WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyFileCmdLine_1(CSharpParseOptions parseOptions) { var x = s_keyPairFile; string s = String.Format("{0}{1}{2}", @"[assembly: System.Reflection.AssemblyKeyFile(@""", x, @""")] public class C {}"); var options = TestOptions.SigningReleaseModule.WithCryptoKeyFile(s_keyPairFile); var other = CreateCompilation(s, options: options, parseOptions: parseOptions); var outStrm = new MemoryStream(); var success = other.Emit(outStrm); Assert.True(success.Success); ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyFileAttribute, parseOptions); } [WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyFileCmdLine_2(CSharpParseOptions parseOptions) { var x = s_keyPairFile; string s = @"[assembly: System.Reflection.AssemblyKeyFile(""bogus"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseModule.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); var outStrm = new MemoryStream(); var success = other.Emit(outStrm); Assert.False(success.Success); success.Diagnostics.Verify( // error CS7091: Attribute 'System.Reflection.AssemblyKeyFileAttribute' given in a source file conflicts with option 'CryptoKeyFile'. Diagnostic(ErrorCode.ERR_CmdOptionConflictsSource).WithArguments("System.Reflection.AssemblyKeyFileAttribute", "CryptoKeyFile")); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignItWithOnlyPublicKey(CSharpParseOptions parseOptions) { var other = CreateCompilation( @" public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_publicKeyFile), parseOptions: parseOptions); var outStrm = new MemoryStream(); var emitResult = other.Emit(outStrm); other.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_SignButNoPrivateKey).WithArguments(s_publicKeyFile)); other = other.WithOptions(TestOptions.SigningReleaseModule.WithCryptoKeyFile(s_publicKeyFile)); var assembly = CreateCompilation("", references: new[] { other.EmitToImageReference() }, options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); assembly.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_SignButNoPrivateKey).WithArguments(s_publicKeyFile)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void AssemblySignatureKeyOnNetModule(CSharpParseOptions parseOptions) { var other = CreateCompilation(@" [assembly: System.Reflection.AssemblySignatureKeyAttribute( ""00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"", ""bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseModule, parseOptions: parseOptions); var comp = CreateCompilation("", references: new[] { other.EmitToImageReference() }, options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); comp.VerifyDiagnostics(); Assert.StartsWith("0024000004", ((SourceAssemblySymbol)comp.Assembly.Modules[1].ContainingAssembly).SignatureKey); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void DelaySignItWithOnlyPublicKey(CSharpParseOptions parseOptions) { var other = CreateCompilation( @" [assembly: System.Reflection.AssemblyDelaySign(true)] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_publicKeyFile), parseOptions: parseOptions); using (var outStrm = new MemoryStream()) { var emitResult = other.Emit(outStrm); Assert.True(emitResult.Success); } } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void DelaySignButNoKey(CSharpParseOptions parseOptions) { var other = CreateCompilation( @" [assembly: System.Reflection.AssemblyDelaySign(true)] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); var outStrm = new MemoryStream(); var emitResult = other.Emit(outStrm); // Dev11: warning CS1699: Use command line option '/delaysign' or appropriate project settings instead of 'AssemblyDelaySignAttribute' // warning CS1607: Assembly generation -- Delay signing was requested, but no key was given // Roslyn: warning CS7033: Delay signing was specified and requires a public key, but no public key was specified other.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_DelaySignButNoKey)); Assert.True(emitResult.Success); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignInMemory(CSharpParseOptions parseOptions) { var other = CreateCompilation( @" public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); var outStrm = new MemoryStream(); var emitResult = other.Emit(outStrm); Assert.True(emitResult.Success); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void DelaySignConflict(CSharpParseOptions parseOptions) { var other = CreateCompilation( @" [assembly: System.Reflection.AssemblyDelaySign(true)] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithDelaySign(false), parseOptions: parseOptions); var outStrm = new MemoryStream(); //shouldn't get any key warning. other.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_CmdOptionConflictsSource).WithArguments("DelaySign", "System.Reflection.AssemblyDelaySignAttribute")); var emitResult = other.Emit(outStrm); Assert.True(emitResult.Success); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void DelaySignNoConflict(CSharpParseOptions parseOptions) { var other = CreateCompilation( @" [assembly: System.Reflection.AssemblyDelaySign(true)] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithDelaySign(true).WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); var outStrm = new MemoryStream(); //shouldn't get any key warning. other.VerifyDiagnostics(); var emitResult = other.Emit(outStrm); Assert.True(emitResult.Success); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void DelaySignWithAssemblySignatureKey(CSharpParseOptions parseOptions) { DelaySignWithAssemblySignatureKeyHelper(); void DelaySignWithAssemblySignatureKeyHelper() { //Note that this SignatureKey is some random one that I found in the devdiv build. //It is not related to the other keys we use in these tests. //In the native compiler, when the AssemblySignatureKey attribute is present, and //the binary is configured for delay signing, the contents of the assemblySignatureKey attribute //(rather than the contents of the keyfile or container) are used to compute the size needed to //reserve in the binary for its signature. Signing using this key is only supported via sn.exe var options = TestOptions.SigningReleaseDll .WithDelaySign(true) .WithCryptoKeyFile(s_keyPairFile); var other = CreateCompilation( @" [assembly: System.Reflection.AssemblyDelaySign(true)] [assembly: System.Reflection.AssemblySignatureKey(""002400000c800000140100000602000000240000525341310008000001000100613399aff18ef1a2c2514a273a42d9042b72321f1757102df9ebada69923e2738406c21e5b801552ab8d200a65a235e001ac9adc25f2d811eb09496a4c6a59d4619589c69f5baf0c4179a47311d92555cd006acc8b5959f2bd6e10e360c34537a1d266da8085856583c85d81da7f3ec01ed9564c58d93d713cd0172c8e23a10f0239b80c96b07736f5d8b022542a4e74251a5f432824318b3539a5a087f8e53d2f135f9ca47f3bb2e10aff0af0849504fb7cea3ff192dc8de0edad64c68efde34c56d302ad55fd6e80f302d5efcdeae953658d3452561b5f36c542efdbdd9f888538d374cef106acf7d93a4445c3c73cd911f0571aaf3d54da12b11ddec375b3"", ""a5a866e1ee186f807668209f3b11236ace5e21f117803a3143abb126dd035d7d2f876b6938aaf2ee3414d5420d753621400db44a49c486ce134300a2106adb6bdb433590fef8ad5c43cba82290dc49530effd86523d9483c00f458af46890036b0e2c61d077d7fbac467a506eba29e467a87198b053c749aa2a4d2840c784e6d"")] public class C { static void Goo() {} }", options: options, parseOptions: parseOptions); using (var metadata = ModuleMetadata.CreateFromImage(other.EmitToArray())) { var header = metadata.Module.PEReaderOpt.PEHeaders.CorHeader; //confirm header has expected SN signature size Assert.Equal(256, header.StrongNameSignatureDirectory.Size); // Delay sign should not have the strong name flag set Assert.Equal(CorFlags.ILOnly, header.Flags); } } } [WorkItem(545720, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545720")] [WorkItem(530050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530050")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void InvalidAssemblyName(CSharpParseOptions parseOptions) { var il = @" .assembly extern mscorlib { } .assembly asm1 { .custom instance void [mscorlib]System.Runtime.CompilerServices.InternalsVisibleToAttribute::.ctor(string) = ( 01 00 09 2F 5C 3A 2A 3F 27 3C 3E 7C 00 00 ) // .../\:*?'<>|.. } .class private auto ansi beforefieldinit Base extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; var csharp = @" class Derived : Base { } "; var ilRef = CompileIL(il, prependDefaultHeader: false); var comp = CreateCompilation(csharp, new[] { ilRef }, assemblyName: "asm2", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); comp.VerifyDiagnostics( // NOTE: dev10 reports WRN_InvalidAssemblyName, but Roslyn won't (DevDiv #15099). // (2,17): error CS0122: 'Base' is inaccessible due to its protection level // class Derived : Base Diagnostic(ErrorCode.ERR_BadAccess, "Base").WithArguments("Base").WithLocation(2, 17) ); } [WorkItem(546331, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546331")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IvtVirtualCall1(CSharpParseOptions parseOptions) { var source1 = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm2"")] public class A { internal virtual void M() { } internal virtual int P { get { return 0; } } internal virtual event System.Action E { add { } remove { } } } "; var source2 = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm3"")] public class B : A { internal override void M() { } internal override int P { get { return 0; } } internal override event System.Action E { add { } remove { } } } "; var source3 = @" using System; using System.Linq.Expressions; public class C : B { internal override void M() { } void Test() { C c = new C(); c.M(); int x = c.P; c.E += null; } void TestET() { C c = new C(); Expression<Action> expr = () => c.M(); } } "; var comp1 = CreateCompilationWithMscorlib45(source1, options: TestOptions.SigningReleaseDll, assemblyName: "asm1", parseOptions: parseOptions); comp1.VerifyDiagnostics(); var ref1 = new CSharpCompilationReference(comp1); var comp2 = CreateCompilationWithMscorlib45(source2, new[] { ref1 }, options: TestOptions.SigningReleaseDll, assemblyName: "asm2", parseOptions: parseOptions); comp2.VerifyDiagnostics(); var ref2 = new CSharpCompilationReference(comp2); var comp3 = CreateCompilationWithMscorlib45(source3, new[] { SystemCoreRef, ref1, ref2 }, options: TestOptions.SigningReleaseDll, assemblyName: "asm3", parseOptions: parseOptions); comp3.VerifyDiagnostics(); // Note: calls B.M, not A.M, since asm1 is not accessible. var verifier = CompileAndVerify(comp3); verifier.VerifyIL("C.Test", @" { // Code size 25 (0x19) .maxstack 2 IL_0000: newobj ""C..ctor()"" IL_0005: dup IL_0006: callvirt ""void B.M()"" IL_000b: dup IL_000c: callvirt ""int B.P.get"" IL_0011: pop IL_0012: ldnull IL_0013: callvirt ""void B.E.add"" IL_0018: ret }"); verifier.VerifyIL("C.TestET", @" { // Code size 85 (0x55) .maxstack 3 IL_0000: newobj ""C.<>c__DisplayClass2_0..ctor()"" IL_0005: dup IL_0006: newobj ""C..ctor()"" IL_000b: stfld ""C C.<>c__DisplayClass2_0.c"" IL_0010: ldtoken ""C.<>c__DisplayClass2_0"" IL_0015: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001a: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_001f: ldtoken ""C C.<>c__DisplayClass2_0.c"" IL_0024: call ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle)"" IL_0029: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)"" IL_002e: ldtoken ""void B.M()"" IL_0033: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0038: castclass ""System.Reflection.MethodInfo"" IL_003d: ldc.i4.0 IL_003e: newarr ""System.Linq.Expressions.Expression"" IL_0043: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_0048: ldc.i4.0 IL_0049: newarr ""System.Linq.Expressions.ParameterExpression"" IL_004e: call ""System.Linq.Expressions.Expression<System.Action> System.Linq.Expressions.Expression.Lambda<System.Action>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0053: pop IL_0054: ret } "); } [WorkItem(546331, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546331")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IvtVirtualCall2(CSharpParseOptions parseOptions) { var source1 = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm2"")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm4"")] public class A { internal virtual void M() { } internal virtual int P { get { return 0; } } internal virtual event System.Action E { add { } remove { } } } "; var source2 = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm3"")] public class B : A { internal override void M() { } internal override int P { get { return 0; } } internal override event System.Action E { add { } remove { } } } "; var source3 = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm4"")] public class C : B { internal override void M() { } internal override int P { get { return 0; } } internal override event System.Action E { add { } remove { } } } "; var source4 = @" using System; using System.Linq.Expressions; public class D : C { internal override void M() { } void Test() { D d = new D(); d.M(); int x = d.P; d.E += null; } void TestET() { D d = new D(); Expression<Action> expr = () => d.M(); } } "; var comp1 = CreateCompilationWithMscorlib45(source1, options: TestOptions.SigningReleaseDll, assemblyName: "asm1", parseOptions: parseOptions); comp1.VerifyDiagnostics(); var ref1 = new CSharpCompilationReference(comp1); var comp2 = CreateCompilationWithMscorlib45(source2, new[] { ref1 }, options: TestOptions.SigningReleaseDll, assemblyName: "asm2", parseOptions: parseOptions); comp2.VerifyDiagnostics(); var ref2 = new CSharpCompilationReference(comp2); var comp3 = CreateCompilationWithMscorlib45(source3, new[] { ref1, ref2 }, options: TestOptions.SigningReleaseDll, assemblyName: "asm3", parseOptions: parseOptions); comp3.VerifyDiagnostics(); var ref3 = new CSharpCompilationReference(comp3); var comp4 = CreateCompilationWithMscorlib45(source4, new[] { SystemCoreRef, ref1, ref2, ref3 }, options: TestOptions.SigningReleaseDll, assemblyName: "asm4", parseOptions: parseOptions); comp4.VerifyDiagnostics(); // Note: calls C.M, not A.M, since asm2 is not accessible (stops search). // Confirmed in Dev11. var verifier = CompileAndVerify(comp4); verifier.VerifyIL("D.Test", @" { // Code size 25 (0x19) .maxstack 2 IL_0000: newobj ""D..ctor()"" IL_0005: dup IL_0006: callvirt ""void C.M()"" IL_000b: dup IL_000c: callvirt ""int C.P.get"" IL_0011: pop IL_0012: ldnull IL_0013: callvirt ""void C.E.add"" IL_0018: ret }"); verifier.VerifyIL("D.TestET", @" { // Code size 85 (0x55) .maxstack 3 IL_0000: newobj ""D.<>c__DisplayClass2_0..ctor()"" IL_0005: dup IL_0006: newobj ""D..ctor()"" IL_000b: stfld ""D D.<>c__DisplayClass2_0.d"" IL_0010: ldtoken ""D.<>c__DisplayClass2_0"" IL_0015: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001a: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_001f: ldtoken ""D D.<>c__DisplayClass2_0.d"" IL_0024: call ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle)"" IL_0029: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)"" IL_002e: ldtoken ""void C.M()"" IL_0033: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0038: castclass ""System.Reflection.MethodInfo"" IL_003d: ldc.i4.0 IL_003e: newarr ""System.Linq.Expressions.Expression"" IL_0043: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_0048: ldc.i4.0 IL_0049: newarr ""System.Linq.Expressions.ParameterExpression"" IL_004e: call ""System.Linq.Expressions.Expression<System.Action> System.Linq.Expressions.Expression.Lambda<System.Action>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0053: pop IL_0054: ret }"); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IvtVirtual_ParamsAndDynamic(CSharpParseOptions parseOptions) { var source1 = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm2"")] public class A { internal virtual void F(params int[] a) { } internal virtual void G(System.Action<dynamic> a) { } [System.Obsolete(""obsolete"", true)] internal virtual void H() { } internal virtual int this[int x, params int[] a] { get { return 0; } } } "; // use IL to generate code that doesn't have synthesized ParamArrayAttribute on int[] parameters: // [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm3"")] // public class B : A // { // internal override void F(int[] a) { } // internal override void G(System.Action<object> a) { } // internal override void H() { } // internal override int this[int x, int[] a] { get { return 0; } } // } var source2 = @" .assembly extern asm1 { .ver 0:0:0:0 } .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly asm2 { .custom instance void [mscorlib]System.Runtime.CompilerServices.InternalsVisibleToAttribute::.ctor(string) = ( 01 00 04 61 73 6D 33 00 00 ) // ...asm3.. } .class public auto ansi beforefieldinit B extends [asm1]A { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item.. .method assembly hidebysig strict virtual instance void F(int32[] a) cil managed { nop ret } .method assembly hidebysig strict virtual instance void G(class [mscorlib]System.Action`1<object> a) cil managed { nop ret } .method assembly hidebysig strict virtual instance void H() cil managed { nop ret } .method assembly hidebysig specialname strict virtual instance int32 get_Item(int32 x, int32[] a) cil managed { ldloc.0 ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [asm1]A::.ctor() ret } .property instance int32 Item(int32, int32[]) { .get instance int32 B::get_Item(int32, int32[]) } }"; var source3 = @" public class C : B { void Test() { C c = new C(); c.F(); c.G(x => x.Bar()); c.H(); var z = c[1]; } } "; var comp1 = CreateCompilation(source1, options: TestOptions.SigningReleaseDll, assemblyName: "asm1", parseOptions: parseOptions); comp1.VerifyDiagnostics(); var ref1 = new CSharpCompilationReference(comp1); var ref2 = CompileIL(source2, prependDefaultHeader: false); var comp3 = CreateCompilation(source3, new[] { ref1, ref2 }, options: TestOptions.SigningReleaseDll, assemblyName: "asm3", parseOptions: parseOptions); comp3.VerifyDiagnostics( // (7,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'a' of 'B.F(int[])' Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "F").WithArguments("a", "B.F(int[])").WithLocation(7, 11), // (8,20): error CS1061: 'object' does not contain a definition for 'Bar' and no extension method 'Bar' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Bar").WithArguments("object", "Bar").WithLocation(8, 20), // (10,17): error CS7036: There is no argument given that corresponds to the required formal parameter 'a' of 'B.this[int, int[]]' Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "c[1]").WithArguments("a", "B.this[int, int[]]").WithLocation(10, 17)); } [WorkItem(529779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529779")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void Bug529779_1(CSharpParseOptions parseOptions) { CSharpCompilation unsigned = CreateCompilation( @" public class C1 {} ", options: TestOptions.SigningReleaseDll, assemblyName: "Unsigned", parseOptions: parseOptions); CSharpCompilation other = CreateCompilation( @" public class C { internal void Goo() { var x = new System.Guid(); System.Console.WriteLine(x); } } ", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); CompileAndVerify(other.WithReferences(new[] { other.References.ElementAt(0), new CSharpCompilationReference(unsigned) })).VerifyDiagnostics(); CompileAndVerify(other.WithReferences(new[] { other.References.ElementAt(0), MetadataReference.CreateFromStream(unsigned.EmitToStream()) })).VerifyDiagnostics(); } [WorkItem(529779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529779")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void Bug529779_2(CSharpParseOptions parseOptions) { CSharpCompilation unsigned = CreateCompilation( @" public class C1 {} ", options: TestOptions.SigningReleaseDll, assemblyName: "Unsigned", parseOptions: parseOptions); CSharpCompilation other = CreateCompilation( @" public class C { internal void Goo() { var x = new C1(); System.Console.WriteLine(x); } } ", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); var comps = new[] {other.WithReferences(new []{other.References.ElementAt(0), new CSharpCompilationReference(unsigned)}), other.WithReferences(new []{other.References.ElementAt(0), MetadataReference.CreateFromStream(unsigned.EmitToStream()) })}; foreach (var comp in comps) { var outStrm = new MemoryStream(); var emitResult = comp.Emit(outStrm); // Dev12 reports an error Assert.True(emitResult.Success); emitResult.Diagnostics.Verify( // warning CS8002: Referenced assembly 'Unsigned, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' does not have a strong name. Diagnostic(ErrorCode.WRN_ReferencedAssemblyDoesNotHaveStrongName).WithArguments("Unsigned, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } } #if !NETCOREAPP [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] [WorkItem(399, "https://github.com/dotnet/roslyn/issues/399")] public void Bug399() { // The referenced assembly Signed.dll from the repro steps var signed = Roslyn.Test.Utilities.Desktop.DesktopRuntimeUtil.CreateMetadataReferenceFromHexGZipImage(@" 1f8b0800000000000400f38d9ac0c0ccc0c0c002c4ffff3330ec6080000706c2a00188f9e477f1316ce13cabb883d1e7ac62 484666b14241517e7a5162ae4272625e5e7e894252aa4251699e42669e828b7fb0426e7e4aaa1e2f2f970ad48c005706061f 4626869e0db74260e63e606052e466e486388a0922f64f094828c01d26006633419430302068860488f8790f06a0bf1c5a41 4a410841c32930580334d71f9f2781f6f11011161800e83e0e242e0790ef81c4d72b49ad2801b99b19a216d9af484624e815 a5e6e42743dde00055c386e14427729c08020f9420b407d86856860b404bef30323070a2a90b5080c4372120f781b1f3ada8 5ec1078b0a8f606f87dacdfeae3b162edb7de055d1af12c942bde5a267ef37e6c6b787945936b0ece367e8f6f87566c6f7bd 46a67f5da4f50d2f8a7e95e159552d1bf747b3ccdae1679c666dd10626bb1bf9815ad1c1876d04a76d78163e4b32a8a77fb3 a77adbec4d15c75de79cd9a3a4a5155dd1fc50b86ce5bd7797cce73b057b3931323082dd020ab332133d033d630363434b90 082b430e90ac0162e53a06861740da00c40e2e29cacc4b2f06a9906084c49b72683083022324ad28bb877aba80d402f96b40 7ca79cfc24a87f81d1c1c8ca000daf5faac60c620c60db41d1c408c50c0c5c509a012e0272e3425078c1792c0d0c48aa407a d41890d2355895288263e39b9f529a936ac7109c999e979aa2979293c3905b9c9c5f949399c4e0091184ca81d5332b80a9a9 8764e24b67aff2dff0feb1f6c7b7e6d50c1cdbab62c2244d1e74362c6000664a902ba600d5b1813c00e407053b1a821c0172 e1dddd9665aa576abb26acf9f6e2eaeaab7527ed1f49174726fc8f395ad7c676f650da9c159bbcd6a73cd031d8a9762d8d6b 47f9eac4955b0566f61fbc9010e4bbf0c405d6e6cc8392f63e6f4bc5339f2d9bb9725d79c0d5cecbacacc9af4522debeb30a bebd207fe9963cbbe995f66bb227ac4c0cfd91c3dce095617a66ce0e9d0b9e8eae9b25965c514278ff1dac3cc0021e2821f3 e29df38b5c72727c1333f32001949a0a0e2c10f8af0a344300ab2123052840cb16e30176c72818100000c85fc49900080000", filePath: "Signed.dll"); var compilation = CreateCompilation( "interface IDerived : ISigned { }", references: new[] { signed }, options: TestOptions.SigningReleaseDll .WithGeneralDiagnosticOption(ReportDiagnostic.Error) .WithCryptoKeyFile(s_keyPairFile)); // ACTUAL: error CS8002: Referenced assembly 'Signed, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' does not have a strong name. // EXPECTED: no errors compilation.VerifyEmitDiagnostics(); } #endif [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void AssemblySignatureKeyAttribute_1(CSharpParseOptions parseOptions) { var other = CreateEmptyCompilation( @" [assembly: System.Reflection.AssemblySignatureKeyAttribute( ""00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"", ""bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), references: new[] { MscorlibRef_v4_0_30316_17626 }, parseOptions: parseOptions); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.True(success.Success); } Assert.True(IsFileFullSigned(tempFile)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void AssemblySignatureKeyAttribute_2(CSharpParseOptions parseOptions) { var other = CreateEmptyCompilation( @" [assembly: System.Reflection.AssemblySignatureKeyAttribute( ""xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"", ""bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), references: new[] { MscorlibRef_v4_0_30316_17626 }, parseOptions: parseOptions); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.False(success.Success); success.Diagnostics.Verify( // (3,1): error CS8003: Invalid signature public key specified in AssemblySignatureKeyAttribute. // "xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb", Diagnostic(ErrorCode.ERR_InvalidSignaturePublicKey, @"""xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb""")); } } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void AssemblySignatureKeyAttribute_3(CSharpParseOptions parseOptions) { var source = @" [assembly: System.Reflection.AssemblySignatureKeyAttribute( ""00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"", ""FFFFbc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")] public class C { static void Goo() {} }"; var options = TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile); var other = CreateEmptyCompilation(source, options: options, references: new[] { MscorlibRef_v4_0_30316_17626 }, parseOptions: parseOptions); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var result = other.Emit(outStrm); Assert.False(result.Success); result.Diagnostics.VerifyErrorCodes( // error CS7027: Error signing output with public key from file 'KeyPairFile.snk' -- Invalid countersignature specified in AssemblySignatureKeyAttribute. (Exception from HRESULT: 0x80131423) Diagnostic(ErrorCode.ERR_PublicKeyFileFailure)); } } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void AssemblySignatureKeyAttribute_4(CSharpParseOptions parseOptions) { var other = CreateEmptyCompilation( @" [assembly: System.Reflection.AssemblySignatureKeyAttribute( ""xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"", ""bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithDelaySign(true), references: new[] { MscorlibRef_v4_0_30316_17626 }, parseOptions: parseOptions); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.False(success.Success); success.Diagnostics.Verify( // (3,1): error CS8003: Invalid signature public key specified in AssemblySignatureKeyAttribute. // "xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb", Diagnostic(ErrorCode.ERR_InvalidSignaturePublicKey, @"""xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb""") ); } } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void AssemblySignatureKeyAttribute_5(CSharpParseOptions parseOptions) { var other = CreateEmptyCompilation( @" [assembly: System.Reflection.AssemblySignatureKeyAttribute( ""00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"", ""FFFFbc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithDelaySign(true), references: new[] { MscorlibRef_v4_0_30316_17626 }, parseOptions: parseOptions); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.True(success.Success); } } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void AssemblySignatureKeyAttribute_6(CSharpParseOptions parseOptions) { var other = CreateEmptyCompilation( @" [assembly: System.Reflection.AssemblySignatureKeyAttribute( null, ""bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithDelaySign(true), references: new[] { MscorlibRef_v4_0_30316_17626 }, parseOptions: parseOptions); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.False(success.Success); success.Diagnostics.Verify( // (3,1): error CS8003: Invalid signature public key specified in AssemblySignatureKeyAttribute. // null, Diagnostic(ErrorCode.ERR_InvalidSignaturePublicKey, "null") ); } } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void AssemblySignatureKeyAttribute_7(CSharpParseOptions parseOptions) { var other = CreateEmptyCompilation( @" [assembly: System.Reflection.AssemblySignatureKeyAttribute( ""00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"", null)] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithDelaySign(true), references: new[] { MscorlibRef_v4_0_30316_17626 }, parseOptions: parseOptions); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.True(success.Success); } } [WorkItem(781312, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/781312")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void Bug781312(CSharpParseOptions parseOptions) { var ca = CreateCompilation( @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Bug781312_B, PublicKey = 0024000004800000940000000602000000240000525341310004000001000100458a131798af87d9e33088a3ab1c6101cbd462760f023d4f41d97f691033649e60b42001e94f4d79386b5e087b0a044c54b7afce151b3ad19b33b332b83087e3b8b022f45b5e4ff9b9a1077b0572ff0679ce38f884c7bd3d9b4090e4a7ee086b7dd292dc20f81a3b1b8a0b67ee77023131e59831c709c81d11c6856669974cc4"")] internal class A { public int Value = 3; } ", options: TestOptions.SigningReleaseDll, assemblyName: "Bug769840_A", parseOptions: parseOptions); CompileAndVerify(ca); var cb = CreateCompilation( @" internal class B { public A GetA() { return new A(); } }", options: TestOptions.SigningReleaseModule, assemblyName: "Bug781312_B", references: new[] { new CSharpCompilationReference(ca) }, parseOptions: parseOptions); CompileAndVerify(cb, verify: Verification.Fails).Diagnostics.Verify(); } [WorkItem(1072350, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1072350")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void Bug1072350(CSharpParseOptions parseOptions) { const string sourceA = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""X "")] internal class A { internal static int I = 42; }"; const string sourceB = @" class B { static void Main() { System.Console.Write(A.I); } }"; var ca = CreateCompilation(sourceA, options: TestOptions.ReleaseDll, assemblyName: "ClassLibrary2", parseOptions: parseOptions); CompileAndVerify(ca); var cb = CreateCompilation(sourceB, options: TestOptions.ReleaseExe, assemblyName: "X", references: new[] { new CSharpCompilationReference(ca) }, parseOptions: parseOptions); CompileAndVerify(cb, expectedOutput: "42").Diagnostics.Verify(); } [WorkItem(1072339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1072339")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void Bug1072339(CSharpParseOptions parseOptions) { const string sourceA = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""x"")] internal class A { internal static int I = 42; }"; const string sourceB = @" class B { static void Main() { System.Console.Write(A.I); } }"; var ca = CreateCompilation(sourceA, options: TestOptions.ReleaseDll, assemblyName: "ClassLibrary2", parseOptions: parseOptions); CompileAndVerify(ca); var cb = CreateCompilation(sourceB, options: TestOptions.ReleaseExe, assemblyName: "X", references: new[] { new CSharpCompilationReference(ca) }, parseOptions: parseOptions); CompileAndVerify(cb, expectedOutput: "42").Diagnostics.Verify(); } [WorkItem(1095618, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1095618")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void Bug1095618(CSharpParseOptions parseOptions) { const string source = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""System.Runtime.Serialization, PublicKey = 10000000000000000400000000000000"")]"; var ca = CreateCompilation(source, parseOptions: parseOptions); ca.VerifyDiagnostics( // (1,12): warning CS1700: Assembly reference 'System.Runtime.Serialization, PublicKey = 10000000000000000400000000000000' is invalid and cannot be resolved // [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("System.Runtime.Serialization, PublicKey = 10000000000000000400000000000000")] Diagnostic(ErrorCode.WRN_InvalidAssemblyName, @"System.Runtime.CompilerServices.InternalsVisibleTo(""System.Runtime.Serialization, PublicKey = 10000000000000000400000000000000"")").WithArguments("System.Runtime.Serialization, PublicKey = 10000000000000000400000000000000").WithLocation(1, 12)); var verifier = CompileAndVerify(ca, symbolValidator: module => { var assembly = module.ContainingAssembly; Assert.NotNull(assembly); Assert.False(assembly.GetAttributes().Any(attr => attr.IsTargetAttribute(assembly, AttributeDescription.InternalsVisibleToAttribute))); }); } [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void ConsistentErrorMessageWhenProvidingNullKeyFile(CSharpParseOptions parseOptions) { var options = TestOptions.DebugDll; Assert.Null(options.CryptoKeyFile); var compilation = CreateCompilation(string.Empty, options: options, parseOptions: parseOptions).VerifyDiagnostics(); VerifySignedBitSetAfterEmit(compilation, expectedToBeSigned: false); } [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void ConsistentErrorMessageWhenProvidingEmptyKeyFile(CSharpParseOptions parseOptions) { var options = TestOptions.DebugDll.WithCryptoKeyFile(string.Empty); var compilation = CreateCompilation(string.Empty, options: options, parseOptions: parseOptions).VerifyDiagnostics(); VerifySignedBitSetAfterEmit(compilation, expectedToBeSigned: false); } [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void ConsistentErrorMessageWhenProvidingNullKeyFile_PublicSign(CSharpParseOptions parseOptions) { var options = TestOptions.DebugDll.WithPublicSign(true); Assert.Null(options.CryptoKeyFile); CreateCompilation(string.Empty, options: options, parseOptions: parseOptions).VerifyDiagnostics( // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1)); } [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void ConsistentErrorMessageWhenProvidingEmptyKeyFile_PublicSign(CSharpParseOptions parseOptions) { var options = TestOptions.DebugDll.WithCryptoKeyFile(string.Empty).WithPublicSign(true); CreateCompilation(string.Empty, options: options, parseOptions: parseOptions).VerifyDiagnostics( // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1)); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionHasCOMInterop)] public void LegacyDoesNotUseBuilder() { var provider = new TestDesktopStrongNameProvider(fileSystem: new VirtualizedStrongNameFileSystem()) { SignBuilderFunc = delegate { throw null; } }; var options = TestOptions.ReleaseDll .WithStrongNameProvider(provider) .WithCryptoKeyFile(s_keyPairFile); var other = CreateCompilation( @" public class C { static void Goo() {} }", options: options, parseOptions: TestOptions.RegularWithLegacyStrongName); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.True(success.Success); } Assert.True(IsFileFullSigned(tempFile)); } #endregion [Theory] [MemberData(nameof(AllProviderParseOptions))] [WorkItem(1341051, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1341051")] public void IVT_Circularity(CSharpParseOptions parseOptions) { string lib_cs = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""WantsIVTAccess"")] public abstract class TestBaseClass { protected internal virtual bool SupportSvgImages { get; } } "; var libRef = CreateCompilation(lib_cs, options: TestOptions.SigningReleaseDll, parseOptions: parseOptions).EmitToImageReference(); string source1 = @" [assembly: Class1] "; string source2 = @" public class Class1 : TestBaseClass { protected internal override bool SupportSvgImages { get { return true; } } } "; // To find what the property overrides, an IVT check is involved so we need to bind assembly-level attributes var c2 = CreateCompilation(new[] { source1, source2 }, new[] { libRef }, assemblyName: "WantsIVTAccess", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); c2.VerifyEmitDiagnostics( // (2,12): error CS0616: 'Class1' is not an attribute class // [assembly: Class1] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Class1").WithArguments("Class1").WithLocation(2, 12) ); } [Fact, WorkItem(1341051, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1341051")] public void IVT_Circularity_AttributeReferencesProperty() { string lib_cs = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""WantsIVTAccess"")] public abstract class TestBaseClass { protected internal virtual bool SupportSvgImages { get; } } public class MyAttribute : System.Attribute { public MyAttribute(string s) { } } "; var libRef = CreateCompilation(lib_cs, options: TestOptions.SigningReleaseDll).EmitToImageReference(); string source1 = @" [assembly: MyAttribute(Class1.Constant)] "; string source2 = @" public class Class1 : TestBaseClass { internal const string Constant = ""text""; protected internal override bool SupportSvgImages { get { return true; } } } "; // To find what the property overrides, an IVT check is involved so we need to bind assembly-level attributes var c2 = CreateCompilation(new[] { source1, source2 }, new[] { libRef }, assemblyName: "WantsIVTAccess", options: TestOptions.SigningReleaseDll); c2.VerifyEmitDiagnostics(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Roslyn.Test.Utilities.SigningTestHelpers; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class InternalsVisibleToAndStrongNameTests : CSharpTestBase { public static IEnumerable<object[]> AllProviderParseOptions { get { if (ExecutionConditionUtil.IsWindows) { return new[] { new object[] { TestOptions.Regular }, new object[] { TestOptions.RegularWithLegacyStrongName } }; } return SpecializedCollections.SingletonEnumerable(new object[] { TestOptions.Regular }); } } #region Helpers public InternalsVisibleToAndStrongNameTests() { SigningTestHelpers.InstallKey(); } private static readonly string s_keyPairFile = SigningTestHelpers.KeyPairFile; private static readonly string s_publicKeyFile = SigningTestHelpers.PublicKeyFile; private static readonly ImmutableArray<byte> s_publicKey = SigningTestHelpers.PublicKey; private static StrongNameProvider GetProviderWithPath(string keyFilePath) => new DesktopStrongNameProvider(ImmutableArray.Create(keyFilePath), strongNameFileSystem: new VirtualizedStrongNameFileSystem()); #endregion #region Naming Tests [WorkItem(529419, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529419")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void AssemblyKeyFileAttributeNotExistFile(CSharpParseOptions parseOptions) { string source = @" using System; using System.Reflection; [assembly: AssemblyKeyFile(""MyKey.snk"")] [assembly: AssemblyKeyName(""Key Name"")] public class Test { public static void Main() { Console.Write(""Hello World!""); } } "; // Dev11 RC gives error now (CS1548) + two warnings // Diagnostic(ErrorCode.WRN_UseSwitchInsteadOfAttribute).WithArguments(@"/keyfile", "AssemblyKeyFile"), // Diagnostic(ErrorCode.WRN_UseSwitchInsteadOfAttribute).WithArguments(@"/keycontainer", "AssemblyKeyName") var c = CreateCompilation(source, options: TestOptions.ReleaseDll.WithStrongNameProvider(new DesktopStrongNameProvider()), parseOptions: parseOptions); c.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments("MyKey.snk", CodeAnalysisResources.FileNotFound)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFromKeyFileAttribute(CSharpParseOptions parseOptions) { var x = s_keyPairFile; string s = String.Format("{0}{1}{2}", @"[assembly: System.Reflection.AssemblyKeyFile(@""", x, @""")] public class C {}"); var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); other.VerifyDiagnostics(); Assert.True(ByteSequenceComparer.Equals(s_publicKey, other.Assembly.Identity.PublicKey)); CompileAndVerify(other, symbolValidator: (ModuleSymbol m) => { bool haveAttribute = false; foreach (var attrData in m.ContainingAssembly.GetAttributes()) { if (attrData.IsTargetAttribute(m.ContainingAssembly, AttributeDescription.AssemblyKeyFileAttribute)) { haveAttribute = true; break; } } Assert.True(haveAttribute); }); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFromKeyFileAttribute_AssemblyKeyFileResolver(CSharpParseOptions parseOptions) { string keyFileDir = Path.GetDirectoryName(s_keyPairFile); string keyFileName = Path.GetFileName(s_keyPairFile); string s = string.Format("{0}{1}{2}", @"[assembly: System.Reflection.AssemblyKeyFile(@""", keyFileName, @""")] public class C {}"); var syntaxTree = Parse(s, @"IVTAndStrongNameTests\AnotherTempDir\temp.cs", parseOptions); // verify failure with default assembly key file resolver var comp = CreateCompilation(syntaxTree, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments(keyFileName, "Assembly signing not supported.")); Assert.True(comp.Assembly.Identity.PublicKey.IsEmpty); // verify success with custom assembly key file resolver with keyFileDir added to search paths comp = CSharpCompilation.Create( GetUniqueName(), new[] { syntaxTree }, new[] { MscorlibRef }, TestOptions.ReleaseDll.WithStrongNameProvider(GetProviderWithPath(keyFileDir))); comp.VerifyDiagnostics(); Assert.True(ByteSequenceComparer.Equals(s_publicKey, comp.Assembly.Identity.PublicKey)); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestHasWindowsPaths)] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFromKeyFileAttribute_AssemblyKeyFileResolver_RelativeToCurrentParent(CSharpParseOptions parseOptions) { string keyFileDir = Path.GetDirectoryName(s_keyPairFile); string keyFileName = Path.GetFileName(s_keyPairFile); string s = String.Format("{0}{1}{2}", @"[assembly: System.Reflection.AssemblyKeyFile(@""..\", keyFileName, @""")] public class C {}"); var syntaxTree = Parse(s, @"IVTAndStrongNameTests\AnotherTempDir\temp.cs", parseOptions); // verify failure with default assembly key file resolver var comp = CreateCompilation(syntaxTree, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // error CS7027: Error extracting public key from file '..\KeyPairFile.snk' -- File not found. Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments(@"..\" + keyFileName, "Assembly signing not supported.")); Assert.True(comp.Assembly.Identity.PublicKey.IsEmpty); // verify success with custom assembly key file resolver with keyFileDir\TempSubDir added to search paths comp = CSharpCompilation.Create( GetUniqueName(), new[] { syntaxTree }, new[] { MscorlibRef }, TestOptions.ReleaseDll.WithStrongNameProvider(GetProviderWithPath(PathUtilities.CombineAbsoluteAndRelativePaths(keyFileDir, @"TempSubDir\")))); Assert.Empty(comp.GetDiagnostics()); Assert.True(ByteSequenceComparer.Equals(s_publicKey, comp.Assembly.Identity.PublicKey)); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestHasWindowsPaths)] public void SigningNotAvailable001() { string keyFileDir = Path.GetDirectoryName(s_keyPairFile); string keyFileName = Path.GetFileName(s_keyPairFile); string s = String.Format("{0}{1}{2}", @"[assembly: System.Reflection.AssemblyKeyFile(@""..\", keyFileName, @""")] public class C {}"); var syntaxTree = Parse(s, @"IVTAndStrongNameTests\AnotherTempDir\temp.cs", TestOptions.RegularWithLegacyStrongName); var provider = new TestDesktopStrongNameProvider( ImmutableArray.Create(PathUtilities.CombineAbsoluteAndRelativePaths(keyFileDir, @"TempSubDir\")), new VirtualizedStrongNameFileSystem()) { GetStrongNameInterfaceFunc = () => throw new DllNotFoundException("aaa.dll not found.") }; var options = TestOptions.ReleaseDll.WithStrongNameProvider(provider); // verify failure var comp = CreateCompilation( assemblyName: GetUniqueName(), source: new[] { syntaxTree }, options: options); comp.VerifyEmitDiagnostics( // error CS7027: Error signing output with public key from file '..\KeyPair_6187d0d6-f691-47fd-985b-03570bc0668d.snk' -- aaa.dll not found. Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments("..\\" + keyFileName, "aaa.dll not found.").WithLocation(1, 1) ); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFromKeyContainerAttribute(CSharpParseOptions parseOptions) { var x = s_keyPairFile; string s = @"[assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); other.VerifyDiagnostics(); Assert.True(ByteSequenceComparer.Equals(s_publicKey, other.Assembly.Identity.PublicKey)); CompileAndVerify(other, symbolValidator: (ModuleSymbol m) => { bool haveAttribute = false; foreach (var attrData in m.ContainingAssembly.GetAttributes()) { if (attrData.IsTargetAttribute(m.ContainingAssembly, AttributeDescription.AssemblyKeyNameAttribute)) { haveAttribute = true; break; } } Assert.True(haveAttribute); }); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFromKeyFileOptions(CSharpParseOptions parseOptions) { string s = "public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); other.VerifyDiagnostics(); Assert.True(ByteSequenceComparer.Equals(s_publicKey, other.Assembly.Identity.PublicKey)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFromKeyFileOptions_ReferenceResolver(CSharpParseOptions parseOptions) { string keyFileDir = Path.GetDirectoryName(s_keyPairFile); string keyFileName = Path.GetFileName(s_keyPairFile); string s = "public class C {}"; var syntaxTree = Parse(s, @"IVTAndStrongNameTests\AnotherTempDir\temp.cs"); // verify failure with default resolver var comp = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(keyFileName), parseOptions: parseOptions); comp.VerifyDiagnostics( // error CS7027: Error extracting public key from file 'KeyPairFile.snk' -- File not found. Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments(keyFileName, CodeAnalysisResources.FileNotFound)); Assert.True(comp.Assembly.Identity.PublicKey.IsEmpty); // verify success with custom assembly key file resolver with keyFileDir added to search paths comp = CSharpCompilation.Create( GetUniqueName(), new[] { syntaxTree }, new[] { MscorlibRef }, TestOptions.ReleaseDll.WithCryptoKeyFile(keyFileName).WithStrongNameProvider(GetProviderWithPath(keyFileDir))); Assert.Empty(comp.GetDiagnostics()); Assert.True(ByteSequenceComparer.Equals(s_publicKey, comp.Assembly.Identity.PublicKey)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFromKeyFileOptionsJustPublicKey(CSharpParseOptions parseOptions) { string s = "public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithDelaySign(true), parseOptions: parseOptions); other.VerifyDiagnostics(); Assert.True(ByteSequenceComparer.Equals(TestResources.General.snPublicKey.AsImmutableOrNull(), other.Assembly.Identity.PublicKey)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFromKeyFileOptionsJustPublicKey_ReferenceResolver(CSharpParseOptions parseOptions) { string publicKeyFileDir = Path.GetDirectoryName(s_publicKeyFile); string publicKeyFileName = Path.GetFileName(s_publicKeyFile); string s = "public class C {}"; var syntaxTree = Parse(s, @"IVTAndStrongNameTests\AnotherTempDir\temp.cs"); // verify failure with default resolver var comp = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(publicKeyFileName).WithDelaySign(true), parseOptions: parseOptions); comp.VerifyDiagnostics( // error CS7027: Error extracting public key from file 'PublicKeyFile.snk' -- File not found. Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments(publicKeyFileName, CodeAnalysisResources.FileNotFound), // warning CS7033: Delay signing was specified and requires a public key, but no public key was specified Diagnostic(ErrorCode.WRN_DelaySignButNoKey) ); Assert.True(comp.Assembly.Identity.PublicKey.IsEmpty); // verify success with custom assembly key file resolver with publicKeyFileDir added to search paths comp = CSharpCompilation.Create( GetUniqueName(), new[] { syntaxTree }, new[] { MscorlibRef }, TestOptions.ReleaseDll.WithCryptoKeyFile(publicKeyFileName).WithDelaySign(true).WithStrongNameProvider(GetProviderWithPath(publicKeyFileDir))); Assert.Empty(comp.GetDiagnostics()); Assert.True(ByteSequenceComparer.Equals(s_publicKey, comp.Assembly.Identity.PublicKey)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFileNotFoundOptions(CSharpParseOptions parseOptions) { string s = "public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile("goo"), parseOptions: parseOptions); other.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments("goo", CodeAnalysisResources.FileNotFound)); Assert.True(other.Assembly.Identity.PublicKey.IsEmpty); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyFileBogusOptions(CSharpParseOptions parseOptions) { var tempFile = Temp.CreateFile().WriteAllBytes(new byte[] { 1, 2, 3, 4 }); string s = "public class C {}"; CSharpCompilation other = CreateCompilation(s, options: TestOptions.ReleaseDll.WithCryptoKeyFile(tempFile.Path), parseOptions: parseOptions); //TODO check for specific error Assert.NotEmpty(other.GetDiagnostics()); Assert.True(other.Assembly.Identity.PublicKey.IsEmpty); } [WorkItem(5662, "https://github.com/dotnet/roslyn/issues/5662")] [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void PubKeyContainerBogusOptions(CSharpParseOptions parseOptions) { string s = "public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyContainer("goo"), parseOptions: parseOptions); // error CS7028: Error signing output with public key from container 'goo' -- Keyset does not exist (Exception from HRESULT: 0x80090016) var err = other.GetDiagnostics().Single(); Assert.Equal((int)ErrorCode.ERR_PublicKeyContainerFailure, err.Code); Assert.Equal(2, err.Arguments.Count); Assert.Equal("goo", err.Arguments[0]); Assert.True(((string)err.Arguments[1]).EndsWith("0x80090016)", StringComparison.Ordinal), (string)err.Arguments[1]); Assert.True(other.Assembly.Identity.PublicKey.IsEmpty); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void KeyFileAttributeOptionConflict(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Reflection.AssemblyKeyFile(""bogus"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); other.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_CmdOptionConflictsSource).WithArguments("CryptoKeyFile", "System.Reflection.AssemblyKeyFileAttribute")); Assert.True(ByteSequenceComparer.Equals(s_publicKey, other.Assembly.Identity.PublicKey)); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void KeyContainerAttributeOptionConflict(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Reflection.AssemblyKeyName(""bogus"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyContainer("RoslynTestContainer"), parseOptions: parseOptions); other.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_CmdOptionConflictsSource).WithArguments("CryptoKeyContainer", "System.Reflection.AssemblyKeyNameAttribute")); Assert.True(ByteSequenceComparer.Equals(s_publicKey, other.Assembly.Identity.PublicKey)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void KeyFileAttributeEmpty(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Reflection.AssemblyKeyFile("""")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); Assert.True(other.Assembly.Identity.PublicKey.IsEmpty); other.VerifyDiagnostics(); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void KeyContainerEmpty(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Reflection.AssemblyKeyName("""")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); Assert.True(other.Assembly.Identity.PublicKey.IsEmpty); other.VerifyDiagnostics(); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PublicKeyFromOptions_DelaySigned(CSharpParseOptions parseOptions) { string source = @" [assembly: System.Reflection.AssemblyDelaySign(true)] public class C {}"; var c = CreateCompilation(source, options: TestOptions.ReleaseDll.WithCryptoPublicKey(s_publicKey), parseOptions: parseOptions); c.VerifyDiagnostics(); Assert.True(ByteSequenceComparer.Equals(s_publicKey, c.Assembly.Identity.PublicKey)); var metadata = ModuleMetadata.CreateFromImage(c.EmitToArray()); var identity = metadata.Module.ReadAssemblyIdentityOrThrow(); Assert.True(identity.HasPublicKey); AssertEx.Equal(identity.PublicKey, s_publicKey); Assert.Equal(CorFlags.ILOnly, metadata.Module.PEReaderOpt.PEHeaders.CorHeader.Flags); } [WorkItem(9150, "https://github.com/dotnet/roslyn/issues/9150")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PublicKeyFromOptions_PublicSign(CSharpParseOptions parseOptions) { // attributes are ignored string source = @" [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] [assembly: System.Reflection.AssemblyKeyFile(""some file"")] public class C {} "; var c = CreateCompilation(source, options: TestOptions.ReleaseDll.WithCryptoPublicKey(s_publicKey).WithPublicSign(true), parseOptions: parseOptions); c.VerifyDiagnostics( // warning CS7103: Attribute 'System.Reflection.AssemblyKeyNameAttribute' is ignored when public signing is specified. Diagnostic(ErrorCode.WRN_AttributeIgnoredWhenPublicSigning).WithArguments("System.Reflection.AssemblyKeyNameAttribute").WithLocation(1, 1), // warning CS7103: Attribute 'System.Reflection.AssemblyKeyFileAttribute' is ignored when public signing is specified. Diagnostic(ErrorCode.WRN_AttributeIgnoredWhenPublicSigning).WithArguments("System.Reflection.AssemblyKeyFileAttribute").WithLocation(1, 1) ); Assert.True(ByteSequenceComparer.Equals(s_publicKey, c.Assembly.Identity.PublicKey)); var metadata = ModuleMetadata.CreateFromImage(c.EmitToArray()); var identity = metadata.Module.ReadAssemblyIdentityOrThrow(); Assert.True(identity.HasPublicKey); AssertEx.Equal(identity.PublicKey, s_publicKey); Assert.Equal(CorFlags.ILOnly | CorFlags.StrongNameSigned, metadata.Module.PEReaderOpt.PEHeaders.CorHeader.Flags); c = CreateCompilation(source, options: TestOptions.SigningReleaseModule.WithCryptoPublicKey(s_publicKey).WithPublicSign(true), parseOptions: parseOptions); c.VerifyDiagnostics( // error CS8201: Public signing is not supported for netmodules. Diagnostic(ErrorCode.ERR_PublicSignNetModule).WithLocation(1, 1) ); c = CreateCompilation(source, options: TestOptions.SigningReleaseModule.WithCryptoKeyFile(s_publicKeyFile).WithPublicSign(true), parseOptions: parseOptions); c.VerifyDiagnostics( // error CS7091: Attribute 'System.Reflection.AssemblyKeyFileAttribute' given in a source file conflicts with option 'CryptoKeyFile'. Diagnostic(ErrorCode.ERR_CmdOptionConflictsSource).WithArguments("System.Reflection.AssemblyKeyFileAttribute", "CryptoKeyFile").WithLocation(1, 1), // error CS8201: Public signing is not supported for netmodules. Diagnostic(ErrorCode.ERR_PublicSignNetModule).WithLocation(1, 1) ); var snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey); string source1 = @" [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] [assembly: System.Reflection.AssemblyKeyFile(@""" + snk.Path + @""")] public class C {} "; c = CreateCompilation(source1, options: TestOptions.SigningReleaseModule.WithCryptoKeyFile(snk.Path).WithPublicSign(true)); c.VerifyDiagnostics( // error CS8201: Public signing is not supported for netmodules. Diagnostic(ErrorCode.ERR_PublicSignNetModule).WithLocation(1, 1) ); } [WorkItem(9150, "https://github.com/dotnet/roslyn/issues/9150")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void KeyFileFromAttributes_PublicSign(CSharpParseOptions parseOptions) { string source = @" [assembly: System.Reflection.AssemblyKeyFile(""test.snk"")] public class C {} "; var c = CreateCompilation(source, options: TestOptions.ReleaseDll.WithPublicSign(true), parseOptions: parseOptions); c.VerifyDiagnostics( // warning CS7103: Attribute 'System.Reflection.AssemblyKeyFileAttribute' is ignored when public signing is specified. Diagnostic(ErrorCode.WRN_AttributeIgnoredWhenPublicSigning).WithArguments("System.Reflection.AssemblyKeyFileAttribute").WithLocation(1, 1), // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1) ); Assert.True(c.Options.PublicSign); } [WorkItem(9150, "https://github.com/dotnet/roslyn/issues/9150")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void KeyContainerFromAttributes_PublicSign(CSharpParseOptions parseOptions) { string source = @" [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class C {} "; var c = CreateCompilation(source, options: TestOptions.ReleaseDll.WithPublicSign(true), parseOptions: parseOptions); c.VerifyDiagnostics( // warning CS7103: Attribute 'System.Reflection.AssemblyKeyNameAttribute' is ignored when public signing is specified. Diagnostic(ErrorCode.WRN_AttributeIgnoredWhenPublicSigning).WithArguments("System.Reflection.AssemblyKeyNameAttribute").WithLocation(1, 1), // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1) ); Assert.True(c.Options.PublicSign); } private void VerifySignedBitSetAfterEmit(Compilation comp, bool expectedToBeSigned = true) { using (var outStream = comp.EmitToStream()) { outStream.Position = 0; using (var reader = new PEReader(outStream)) { var flags = reader.PEHeaders.CorHeader.Flags; Assert.Equal(expectedToBeSigned, flags.HasFlag(CorFlags.StrongNameSigned)); } } } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SnkFile_PublicSign(CSharpParseOptions parseOptions) { var snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey); var comp = CreateCompilation("public class C{}", options: TestOptions.ReleaseDll .WithCryptoKeyFile(snk.Path) .WithPublicSign(true), parseOptions: parseOptions); comp.VerifyDiagnostics(); Assert.True(comp.Options.PublicSign); Assert.Null(comp.Options.DelaySign); Assert.False(comp.IsRealSigned); Assert.NotNull(comp.Options.CryptoKeyFile); VerifySignedBitSetAfterEmit(comp); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PublicKeyFile_PublicSign(CSharpParseOptions parseOptions) { var pubKeyFile = Temp.CreateFile().WriteAllBytes(TestResources.General.snPublicKey); var comp = CreateCompilation("public class C {}", options: TestOptions.ReleaseDll .WithCryptoKeyFile(pubKeyFile.Path) .WithPublicSign(true), parseOptions: parseOptions); comp.VerifyDiagnostics(); Assert.True(comp.Options.PublicSign); Assert.Null(comp.Options.DelaySign); Assert.False(comp.IsRealSigned); Assert.NotNull(comp.Options.CryptoKeyFile); VerifySignedBitSetAfterEmit(comp); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PublicSign_DelaySignAttribute(CSharpParseOptions parseOptions) { var pubKeyFile = Temp.CreateFile().WriteAllBytes(TestResources.General.snPublicKey); var comp = CreateCompilation(@" [assembly: System.Reflection.AssemblyDelaySign(true)] public class C {}", options: TestOptions.ReleaseDll .WithCryptoKeyFile(pubKeyFile.Path) .WithPublicSign(true), parseOptions: parseOptions); comp.VerifyDiagnostics( // warning CS1616: Option 'PublicSign' overrides attribute 'System.Reflection.AssemblyDelaySignAttribute' given in a source file or added module Diagnostic(ErrorCode.WRN_CmdOptionConflictsSource).WithArguments("PublicSign", "System.Reflection.AssemblyDelaySignAttribute").WithLocation(1, 1)); Assert.True(comp.Options.PublicSign); Assert.Null(comp.Options.DelaySign); Assert.False(comp.IsRealSigned); Assert.NotNull(comp.Options.CryptoKeyFile); VerifySignedBitSetAfterEmit(comp); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void KeyContainerNoSNProvider_PublicSign(CSharpParseOptions parseOptions) { var comp = CreateCompilation("public class C {}", options: TestOptions.ReleaseDll .WithCryptoKeyContainer("roslynTestContainer") .WithPublicSign(true), parseOptions: parseOptions); comp.VerifyDiagnostics( // error CS7102: Compilation options 'PublicSign' and 'CryptoKeyContainer' can't both be specified at the same time. Diagnostic(ErrorCode.ERR_MutuallyExclusiveOptions).WithArguments("PublicSign", "CryptoKeyContainer").WithLocation(1, 1), // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void KeyContainerDesktopProvider_PublicSign(CSharpParseOptions parseOptions) { var comp = CreateCompilation("public class C {}", options: TestOptions.SigningReleaseDll .WithCryptoKeyContainer("roslynTestContainer") .WithPublicSign(true), parseOptions: parseOptions); comp.VerifyDiagnostics( // error CS7102: Compilation options 'PublicSign' and 'CryptoKeyContainer' can't both be specified at the same time. Diagnostic(ErrorCode.ERR_MutuallyExclusiveOptions).WithArguments("PublicSign", "CryptoKeyContainer").WithLocation(1, 1), // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1)); Assert.True(comp.Options.PublicSign); Assert.Null(comp.Options.DelaySign); Assert.False(comp.IsRealSigned); Assert.NotNull(comp.Options.CryptoKeyContainer); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PublicSignAndDelaySign(CSharpParseOptions parseOptions) { var snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey); var comp = CreateCompilation("public class C {}", options: TestOptions.ReleaseDll .WithPublicSign(true) .WithDelaySign(true) .WithCryptoKeyFile(snk.Path), parseOptions: parseOptions); comp.VerifyDiagnostics( // error CS7102: Compilation options 'PublicSign' and 'DelaySign' can't both be specified at the same time. Diagnostic(ErrorCode.ERR_MutuallyExclusiveOptions).WithArguments("PublicSign", "DelaySign").WithLocation(1, 1)); Assert.True(comp.Options.PublicSign); Assert.True(comp.Options.DelaySign); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PublicSignAndDelaySignFalse(CSharpParseOptions parseOptions) { var snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey); var comp = CreateCompilation("public class C {}", options: TestOptions.ReleaseDll .WithPublicSign(true) .WithDelaySign(false) .WithCryptoKeyFile(snk.Path), parseOptions: parseOptions); comp.VerifyDiagnostics(); Assert.True(comp.Options.PublicSign); Assert.False(comp.Options.DelaySign); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PublicSignNoKey(CSharpParseOptions parseOptions) { var comp = CreateCompilation("public class C {}", options: TestOptions.ReleaseDll.WithPublicSign(true), parseOptions: parseOptions); comp.VerifyDiagnostics( // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1)); Assert.True(comp.Options.PublicSign); Assert.True(comp.Assembly.PublicKey.IsDefaultOrEmpty); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void PublicKeyFromOptions_InvalidCompilationOptions(CSharpParseOptions parseOptions) { string source = @"public class C {}"; var c = CreateCompilation(source, options: TestOptions.SigningReleaseDll. WithCryptoPublicKey(ImmutableArray.Create<byte>(1, 2, 3)). WithCryptoKeyContainer("roslynTestContainer"). WithCryptoKeyFile("file.snk"), parseOptions: parseOptions); c.VerifyDiagnostics( // error CS7102: Compilation options 'CryptoPublicKey' and 'CryptoKeyFile' can't both be specified at the same time. Diagnostic(ErrorCode.ERR_MutuallyExclusiveOptions).WithArguments("CryptoPublicKey", "CryptoKeyFile").WithLocation(1, 1), // error CS7102: Compilation options 'CryptoPublicKey' and 'CryptoKeyContainer' can't both be specified at the same time. Diagnostic(ErrorCode.ERR_MutuallyExclusiveOptions).WithArguments("CryptoPublicKey", "CryptoKeyContainer").WithLocation(1, 1), // error CS7088: Invalid 'CryptoPublicKey' value: '01-02-03'. Diagnostic(ErrorCode.ERR_BadCompilationOptionValue).WithArguments("CryptoPublicKey", "01-02-03").WithLocation(1, 1)); } #endregion #region IVT Access Checking [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IVTBasicCompilation(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""WantsIVTAccess"")] public class C { internal void Goo() {} }"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll, assemblyName: "Paul", parseOptions: parseOptions); var c = CreateCompilation( @"public class A { internal class B { protected B(C o) { o.Goo(); } } }", new[] { new CSharpCompilationReference(other) }, assemblyName: "WantsIVTAccessButCantHave", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); //compilation should not succeed, and internals should not be imported. c.VerifyDiagnostics( // (7,15): error CS0122: 'C.Goo()' is inaccessible due to its protection level // o.Goo(); Diagnostic(ErrorCode.ERR_BadAccess, "Goo").WithArguments("C.Goo()").WithLocation(7, 15) ); var c2 = CreateCompilation( @"public class A { internal class B { protected B(C o) { o.Goo(); } } }", new[] { new CSharpCompilationReference(other) }, assemblyName: "WantsIVTAccess", options: TestOptions.SigningReleaseDll); Assert.Empty(c2.GetDiagnostics()); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IVTBasicMetadata(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""WantsIVTAccess"")] public class C { internal void Goo() {} }"; var otherStream = CreateCompilation(s, options: TestOptions.SigningReleaseDll, parseOptions: parseOptions).EmitToStream(); var c = CreateCompilation( @"public class A { internal class B { protected B(C o) { o.Goo(); } } }", references: new[] { AssemblyMetadata.CreateFromStream(otherStream, leaveOpen: true).GetReference() }, assemblyName: "WantsIVTAccessButCantHave", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); //compilation should not succeed, and internals should not be imported. c.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Goo").WithArguments("C", "Goo")); otherStream.Position = 0; var c2 = CreateCompilation( @"public class A { internal class B { protected B(C o) { o.Goo(); } } }", new[] { MetadataReference.CreateFromStream(otherStream) }, assemblyName: "WantsIVTAccess", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); Assert.Empty(c2.GetDiagnostics()); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void IVTSigned(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] public class C { internal void Goo() {} }"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), assemblyName: "Paul", parseOptions: parseOptions); other.VerifyDiagnostics(); var requestor = CreateCompilation( @"public class A { internal class B { protected B(C o) { o.Goo(); } } }", new MetadataReference[] { new CSharpCompilationReference(other) }, TestOptions.SigningReleaseDll.WithCryptoKeyContainer("roslynTestContainer"), assemblyName: "John", parseOptions: parseOptions); Assert.Empty(requestor.GetDiagnostics()); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IVTNotBothSigned_CStoCS(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] public class C { internal void Goo() {} }"; var other = CreateCompilation(s, assemblyName: "Paul", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); other.VerifyDiagnostics(); var requestor = CreateCompilation( @"public class A { internal class B { protected B(C o) { o.Goo(); } } }", references: new[] { new CSharpCompilationReference(other) }, assemblyName: "John", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); // We allow John to access Paul's internal Goo even though strong-named John should not be referencing weak-named Paul. // Paul has, after all, specifically granted access to John. // During emit time we should produce an error that says that a strong-named assembly cannot reference // a weak-named assembly. But the C# compiler doesn't currently do that. See https://github.com/dotnet/roslyn/issues/26722 requestor.VerifyDiagnostics(); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void CS0281Method(CSharpParseOptions parseOptions) { var friendClass = CreateCompilation(@" using System.Runtime.CompilerServices; [ assembly: InternalsVisibleTo(""cs0281, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"") ] public class PublicClass { internal static void InternalMethod() { } protected static void ProtectedMethod() { } private static void PrivateMethod() { } internal protected static void InternalProtectedMethod() { } private protected static void PrivateProtectedMethod() { } }", assemblyName: "Paul", parseOptions: parseOptions); string cs0281 = @" public class Test { static void Main () { PublicClass.InternalMethod(); PublicClass.ProtectedMethod(); PublicClass.PrivateMethod(); PublicClass.InternalProtectedMethod(); PublicClass.PrivateProtectedMethod(); } }"; var other = CreateCompilation(cs0281, references: new[] { friendClass.EmitToImageReference() }, assemblyName: "cs0281", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); other.VerifyDiagnostics( // (7,15): error CS0281: Friend access was granted by 'Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null', but the public key of the output assembly ('') does not match that specified by the InternalsVisibleTo attribute in the granting assembly. // PublicClass.InternalMethod(); Diagnostic(ErrorCode.ERR_FriendRefNotEqualToThis, "InternalMethod").WithArguments("Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "").WithLocation(7, 15), // (8,21): error CS0122: 'PublicClass.ProtectedMethod()' is inaccessible due to its protection level // PublicClass.ProtectedMethod(); Diagnostic(ErrorCode.ERR_BadAccess, "ProtectedMethod").WithArguments("PublicClass.ProtectedMethod()").WithLocation(8, 21), // (9,21): error CS0117: 'PublicClass' does not contain a definition for 'PrivateMethod' // PublicClass.PrivateMethod(); Diagnostic(ErrorCode.ERR_NoSuchMember, "PrivateMethod").WithArguments("PublicClass", "PrivateMethod").WithLocation(9, 21), // (10,21): error CS0281: Friend access was granted by 'Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null', but the public key of the output assembly ('') does not match that specified by the InternalsVisibleTo attribute in the granting assembly. // PublicClass.InternalProtectedMethod(); Diagnostic(ErrorCode.ERR_FriendRefNotEqualToThis, "InternalProtectedMethod").WithArguments("Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "").WithLocation(10, 21), // (11,21): error CS0281: Friend access was granted by 'Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null', but the public key of the output assembly ('') does not match that specified by the InternalsVisibleTo attribute in the granting assembly. // PublicClass.PrivateProtectedMethod(); Diagnostic(ErrorCode.ERR_FriendRefNotEqualToThis, "PrivateProtectedMethod").WithArguments("Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "").WithLocation(11, 21) ); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void CS0281Class(CSharpParseOptions parseOptions) { var friendClass = CreateCompilation(@" using System.Runtime.CompilerServices; [ assembly: InternalsVisibleTo(""cs0281, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"") ] internal class FriendClass { public static void MyMethod() { } }", assemblyName: "Paul", parseOptions: parseOptions); string cs0281 = @" public class Test { static void Main () { FriendClass.MyMethod (); } }"; var other = CreateCompilation(cs0281, references: new[] { friendClass.EmitToImageReference() }, assemblyName: "cs0281", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); // (7, 3): error CS0281: Friend access was granted by 'Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null', but the public key of the output assembly ('') // does not match that specified by the InternalsVisibleTo attribute in the granting assembly. // FriendClass.MyMethod (); other.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_FriendRefNotEqualToThis, "FriendClass").WithArguments("Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "").WithLocation(7, 3) ); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IVTNotBothSigned_VBtoCS(CSharpParseOptions parseOptions) { string s = @"<assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")> Public Class C Friend Sub Goo() End Sub End Class"; var other = VisualBasic.VisualBasicCompilation.Create( syntaxTrees: new[] { VisualBasic.VisualBasicSyntaxTree.ParseText(s) }, references: new[] { MscorlibRef_v4_0_30316_17626 }, assemblyName: "Paul", options: new VisualBasic.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary).WithStrongNameProvider(DefaultDesktopStrongNameProvider)); other.VerifyDiagnostics(); var requestor = CreateCompilation( @"public class A { internal class B { protected B(C o) { o.Goo(); } } }", references: new[] { MetadataReference.CreateFromImage(other.EmitToArray()) }, assemblyName: "John", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); // We allow John to access Paul's internal Goo even though strong-named John should not be referencing weak-named Paul. // Paul has, after all, specifically granted access to John. // During emit time we should produce an error that says that a strong-named assembly cannot reference // a weak-named assembly. But the C# compiler doesn't currently do that. See https://github.com/dotnet/roslyn/issues/26722 requestor.VerifyDiagnostics(); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void IVTDeferredSuccess(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class CAttribute : System.Attribute { public CAttribute() {} }"; var other = CreateCompilation(s, assemblyName: "Paul", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); other.VerifyDiagnostics(); var requestor = CreateCompilation( @" [assembly: C()] //causes optimistic granting [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new[] { new CSharpCompilationReference(other) }, assemblyName: "John", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); Assert.True(ByteSequenceComparer.Equals(s_publicKey, requestor.Assembly.Identity.PublicKey)); Assert.Empty(requestor.GetDiagnostics()); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void IVTDeferredFailSignMismatch(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class CAttribute : System.Attribute { public CAttribute() {} }"; var other = CreateCompilation(s, assemblyName: "Paul", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); //not signed. cryptoKeyFile: KeyPairFile, other.VerifyDiagnostics(); var requestor = CreateCompilation( @" [assembly: C()] [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new[] { new CSharpCompilationReference(other) }, assemblyName: "John", options: TestOptions.SigningReleaseDll); Assert.True(ByteSequenceComparer.Equals(s_publicKey, requestor.Assembly.Identity.PublicKey)); requestor.VerifyDiagnostics(); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void IVTDeferredFailSignMismatch_AssemblyKeyName(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class AssemblyKeyNameAttribute : System.Attribute { public AssemblyKeyNameAttribute() {} }"; var other = CreateCompilation(s, assemblyName: "Paul", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); //not signed. cryptoKeyFile: KeyPairFile, other.VerifyDiagnostics(); var requestor = CreateCompilation( @" [assembly: AssemblyKeyName()] //causes optimistic granting [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new[] { new CSharpCompilationReference(other) }, assemblyName: "John", options: TestOptions.SigningReleaseDll); Assert.True(ByteSequenceComparer.Equals(s_publicKey, requestor.Assembly.Identity.PublicKey)); requestor.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_FriendRefSigningMismatch, arguments: new object[] { "Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null" })); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void IVTDeferredFailKeyMismatch(CSharpParseOptions parseOptions) { //key is wrong in the first digit. correct key starts with 0 string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=10240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class CAttribute : System.Attribute { public CAttribute() {} }"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), assemblyName: "Paul", parseOptions: parseOptions); other.VerifyDiagnostics(); var requestor = CreateCompilation( @" [assembly: C()] [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new MetadataReference[] { new CSharpCompilationReference(other) }, assemblyName: "John", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); Assert.True(ByteSequenceComparer.Equals(s_publicKey, requestor.Assembly.Identity.PublicKey)); requestor.VerifyDiagnostics( // (2,12): error CS0122: 'CAttribute' is inaccessible due to its protection level // [assembly: C()] Diagnostic(ErrorCode.ERR_BadAccess, "C").WithArguments("CAttribute").WithLocation(2, 12) ); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void IVTDeferredFailKeyMismatch_AssemblyKeyName(CSharpParseOptions parseOptions) { //key is wrong in the first digit. correct key starts with 0 string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=10240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class AssemblyKeyNameAttribute : System.Attribute { public AssemblyKeyNameAttribute() {} }"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), assemblyName: "Paul", parseOptions: parseOptions); other.VerifyDiagnostics(); var requestor = CreateCompilation( @" [assembly: AssemblyKeyName()] [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new MetadataReference[] { new CSharpCompilationReference(other) }, assemblyName: "John", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); Assert.True(ByteSequenceComparer.Equals(s_publicKey, requestor.Assembly.Identity.PublicKey)); requestor.VerifyDiagnostics( // error CS0281: Friend access was granted by 'Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2', // but the public key of the output assembly ('John, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2') // does not match that specified by the InternalsVisibleTo attribute in the granting assembly. Diagnostic(ErrorCode.ERR_FriendRefNotEqualToThis) .WithArguments("Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "John, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2") .WithLocation(1, 1), // (2,12): error CS0122: 'AssemblyKeyNameAttribute' is inaccessible due to its protection level // [assembly: AssemblyKeyName()] Diagnostic(ErrorCode.ERR_BadAccess, "AssemblyKeyName").WithArguments("AssemblyKeyNameAttribute").WithLocation(2, 12) ); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void IVTSuccessThroughIAssembly(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class CAttribute : System.Attribute { public CAttribute() {} }"; var other = CreateCompilation(s, assemblyName: "Paul", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); other.VerifyDiagnostics(); var requestor = CreateCompilation( @" [assembly: C()] //causes optimistic granting [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new MetadataReference[] { new CSharpCompilationReference(other) }, options: TestOptions.SigningReleaseDll, assemblyName: "John", parseOptions: parseOptions); Assert.True(other.Assembly.GivesAccessTo(requestor.Assembly)); Assert.Empty(requestor.GetDiagnostics()); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void IVTDeferredFailKeyMismatchIAssembly(CSharpParseOptions parseOptions) { //key is wrong in the first digit. correct key starts with 0 string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=10240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class CAttribute : System.Attribute { public CAttribute() {} }"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), assemblyName: "Paul", parseOptions: parseOptions); other.VerifyDiagnostics(); var requestor = CreateCompilation( @" [assembly: C()] [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new MetadataReference[] { new CSharpCompilationReference(other) }, TestOptions.SigningReleaseDll, assemblyName: "John", parseOptions: parseOptions); Assert.False(other.Assembly.GivesAccessTo(requestor.Assembly)); requestor.VerifyDiagnostics( // (3,12): error CS0122: 'CAttribute' is inaccessible due to its protection level // [assembly: C()] Diagnostic(ErrorCode.ERR_BadAccess, "C").WithArguments("CAttribute").WithLocation(3, 12) ); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void IVTDeferredFailKeyMismatchIAssembly_AssemblyKeyName(CSharpParseOptions parseOptions) { //key is wrong in the first digit. correct key starts with 0 string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=10240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] internal class AssemblyKeyNameAttribute : System.Attribute { public AssemblyKeyNameAttribute() {} }"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), assemblyName: "Paul", parseOptions: parseOptions); other.VerifyDiagnostics(); var requestor = CreateCompilation( @" [assembly: AssemblyKeyName()] [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class A { }", new MetadataReference[] { new CSharpCompilationReference(other) }, TestOptions.SigningReleaseDll, assemblyName: "John", parseOptions: parseOptions); Assert.False(other.Assembly.GivesAccessTo(requestor.Assembly)); requestor.VerifyDiagnostics( // error CS0281: Friend access was granted by 'Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2', // but the public key of the output assembly ('John, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2') // does not match that specified by the InternalsVisibleTo attribute in the granting assembly. Diagnostic(ErrorCode.ERR_FriendRefNotEqualToThis) .WithArguments("Paul, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2", "John, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2") .WithLocation(1, 1), // (3,12): error CS0122: 'AssemblyKeyNameAttribute' is inaccessible due to its protection level // [assembly: AssemblyKeyName()] Diagnostic(ErrorCode.ERR_BadAccess, "AssemblyKeyName").WithArguments("AssemblyKeyNameAttribute").WithLocation(3, 12) ); } [WorkItem(820450, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/820450")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IVTGivesAccessToUsingDifferentKeys(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""John, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")] namespace ClassLibrary1 { internal class Class1 { } } "; var giver = CreateCompilation(s, assemblyName: "Paul", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(SigningTestHelpers.KeyPairFile2), parseOptions: parseOptions); giver.VerifyDiagnostics(); var requestor = CreateCompilation( @" namespace ClassLibrary2 { internal class A { public void Goo(ClassLibrary1.Class1 a) { } } }", new MetadataReference[] { new CSharpCompilationReference(giver) }, options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), assemblyName: "John", parseOptions: parseOptions); Assert.True(giver.Assembly.GivesAccessTo(requestor.Assembly)); Assert.Empty(requestor.GetDiagnostics()); } #endregion #region IVT instantiations [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IVTHasCulture(CSharpParseOptions parseOptions) { var other = CreateCompilation( @" using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""WantsIVTAccess, Culture=neutral"")] public class C { static void Goo() {} } ", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); other.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_FriendAssemblyBadArgs, @"InternalsVisibleTo(""WantsIVTAccess, Culture=neutral"")").WithArguments("WantsIVTAccess, Culture=neutral")); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IVTNoKey(CSharpParseOptions parseOptions) { var other = CreateCompilation( @" using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""WantsIVTAccess"")] public class C { static void Main() {} } ", options: TestOptions.SigningReleaseExe.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); other.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_FriendAssemblySNReq, @"InternalsVisibleTo(""WantsIVTAccess"")").WithArguments("WantsIVTAccess")); } #endregion #region Signing [ConditionalTheory(typeof(DesktopOnly), Reason = "https://github.com/dotnet/coreclr/issues/21723")] [MemberData(nameof(AllProviderParseOptions))] public void MaxSizeKey(CSharpParseOptions parseOptions) { var pubKey = TestResources.General.snMaxSizePublicKeyString; string pubKeyToken = "1540923db30520b2"; var pubKeyTokenBytes = new byte[] { 0x15, 0x40, 0x92, 0x3d, 0xb3, 0x05, 0x20, 0xb2 }; var comp = CreateCompilation($@" using System; using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""MaxSizeComp2, PublicKey={pubKey}, PublicKeyToken={pubKeyToken}"")] internal class C {{ public static void M() {{ Console.WriteLine(""Called M""); }} }}", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(SigningTestHelpers.MaxSizeKeyFile), parseOptions: parseOptions); comp.VerifyEmitDiagnostics(); Assert.True(comp.IsRealSigned); VerifySignedBitSetAfterEmit(comp); Assert.Equal(TestResources.General.snMaxSizePublicKey, comp.Assembly.Identity.PublicKey); Assert.Equal<byte>(pubKeyTokenBytes, comp.Assembly.Identity.PublicKeyToken); var src = @" class D { public static void Main() { C.M(); } }"; var comp2 = CreateCompilation(src, references: new[] { comp.ToMetadataReference() }, assemblyName: "MaxSizeComp2", options: TestOptions.SigningReleaseExe.WithCryptoKeyFile(SigningTestHelpers.MaxSizeKeyFile), parseOptions: parseOptions); CompileAndVerify(comp2, expectedOutput: "Called M"); Assert.Equal(TestResources.General.snMaxSizePublicKey, comp2.Assembly.Identity.PublicKey); Assert.Equal<byte>(pubKeyTokenBytes, comp2.Assembly.Identity.PublicKeyToken); var comp3 = CreateCompilation(src, references: new[] { comp.EmitToImageReference() }, assemblyName: "MaxSizeComp2", options: TestOptions.SigningReleaseExe.WithCryptoKeyFile(SigningTestHelpers.MaxSizeKeyFile), parseOptions: parseOptions); CompileAndVerify(comp3, expectedOutput: "Called M"); Assert.Equal(TestResources.General.snMaxSizePublicKey, comp3.Assembly.Identity.PublicKey); Assert.Equal<byte>(pubKeyTokenBytes, comp3.Assembly.Identity.PublicKeyToken); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignIt(CSharpParseOptions parseOptions) { var other = CreateCompilation( @" public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.True(success.Success); } Assert.True(IsFileFullSigned(tempFile)); } private static bool IsFileFullSigned(TempFile file) { using (var metadata = new FileStream(file.Path, FileMode.Open)) { return ILValidation.IsStreamFullSigned(metadata); } } private void ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(MemoryStream moduleContents, AttributeDescription expectedModuleAttr, CSharpParseOptions parseOptions) { //a module doesn't get signed for real. It should have either a keyfile or keycontainer attribute //parked on a typeRef named 'AssemblyAttributesGoHere.' When the module is added to an assembly, the //resulting assembly is signed with the key referred to by the aforementioned attribute. EmitResult success; var tempFile = Temp.CreateFile(); moduleContents.Position = 0; using (var metadata = ModuleMetadata.CreateFromStream(moduleContents)) { var flags = metadata.Module.PEReaderOpt.PEHeaders.CorHeader.Flags; //confirm file does not claim to be signed Assert.Equal(0, (int)(flags & CorFlags.StrongNameSigned)); var corlibName = RuntimeUtilities.IsCoreClrRuntime ? "netstandard" : "mscorlib"; EntityHandle token = metadata.Module.GetTypeRef(metadata.Module.GetAssemblyRef(corlibName), "System.Runtime.CompilerServices", "AssemblyAttributesGoHere"); Assert.False(token.IsNil); //could the type ref be located? If not then the attribute's not there. var attrInfos = metadata.Module.FindTargetAttributes(token, expectedModuleAttr); Assert.Equal(1, attrInfos.Count()); var source = @" public class Z { }"; //now that the module checks out, ensure that adding it to a compilation outputting a dll //results in a signed assembly. var assemblyComp = CreateCompilation(source, new[] { metadata.GetReference() }, TestOptions.SigningReleaseDll, parseOptions: parseOptions); using (var finalStrm = tempFile.Open()) { success = assemblyComp.Emit(finalStrm); } } success.Diagnostics.Verify(); Assert.True(success.Success); Assert.True(IsFileFullSigned(tempFile)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyFileAttr(CSharpParseOptions parseOptions) { var x = s_keyPairFile; string s = String.Format("{0}{1}{2}", @"[assembly: System.Reflection.AssemblyKeyFile(@""", x, @""")] public class C {}"); var other = CreateCompilation(s, options: TestOptions.SigningReleaseModule); var outStrm = other.EmitToStream(); ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyFileAttribute, parseOptions); } [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyContainerAttr(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseModule); var outStrm = other.EmitToStream(); ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyNameAttribute, parseOptions); } [WorkItem(5665, "https://github.com/dotnet/roslyn/issues/5665")] [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyContainerBogus(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Reflection.AssemblyKeyName(""bogus"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseModule, parseOptions: parseOptions); //shouldn't have an error. The attribute's contents are checked when the module is added. var reference = other.EmitToImageReference(); s = @"class D {}"; other = CreateCompilation(s, new[] { reference }, TestOptions.SigningReleaseDll); // error CS7028: Error signing output with public key from container 'bogus' -- Keyset does not exist (Exception from HRESULT: 0x80090016) var err = other.GetDiagnostics().Single(); Assert.Equal((int)ErrorCode.ERR_PublicKeyContainerFailure, err.Code); Assert.Equal(2, err.Arguments.Count); Assert.Equal("bogus", err.Arguments[0]); Assert.True(((string)err.Arguments[1]).EndsWith("0x80090016)", StringComparison.Ordinal), (string)err.Arguments[1]); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyFileBogus(CSharpParseOptions parseOptions) { string s = @"[assembly: System.Reflection.AssemblyKeyFile(""bogus"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseModule); //shouldn't have an error. The attribute's contents are checked when the module is added. var reference = other.EmitToImageReference(); s = @"class D {}"; other = CreateCompilation(s, new[] { reference }, TestOptions.SigningReleaseDll, parseOptions: parseOptions); other.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_PublicKeyFileFailure).WithArguments("bogus", CodeAnalysisResources.FileNotFound)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void AttemptToStrongNameWithOnlyPublicKey(CSharpParseOptions parseOptions) { string s = "public class C {}"; var options = TestOptions.SigningReleaseDll.WithCryptoKeyFile(PublicKeyFile); var other = CreateCompilation(s, options: options, parseOptions: parseOptions); var outStrm = new MemoryStream(); var refStrm = new MemoryStream(); var success = other.Emit(outStrm, metadataPEStream: refStrm); Assert.False(success.Success); // The diagnostic contains a random file path, so just check the code. Assert.True(success.Diagnostics[0].Code == (int)ErrorCode.ERR_SignButNoPrivateKey); } [WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")] [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyContainerCmdLine(CSharpParseOptions parseOptions) { string s = "public class C {}"; var options = TestOptions.SigningReleaseModule.WithCryptoKeyContainer("roslynTestContainer"); var other = CreateCompilation(s, options: options); var outStrm = new MemoryStream(); var success = other.Emit(outStrm); Assert.True(success.Success); ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyNameAttribute, parseOptions); } [WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")] [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyContainerCmdLine_1(CSharpParseOptions parseOptions) { string s = @" [assembly: System.Reflection.AssemblyKeyName(""roslynTestContainer"")] public class C {}"; var options = TestOptions.SigningReleaseModule.WithCryptoKeyContainer("roslynTestContainer"); var other = CreateCompilation(s, options: options, parseOptions: parseOptions); var outStrm = new MemoryStream(); var success = other.Emit(outStrm); Assert.True(success.Success); ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyNameAttribute, parseOptions); } [WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyContainerCmdLine_2(CSharpParseOptions parseOptions) { string s = @" [assembly: System.Reflection.AssemblyKeyName(""bogus"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseModule.WithCryptoKeyContainer("roslynTestContainer"), parseOptions: parseOptions); var outStrm = new MemoryStream(); var success = other.Emit(outStrm); Assert.False(success.Success); success.Diagnostics.Verify( // error CS7091: Attribute 'System.Reflection.AssemblyKeyNameAttribute' given in a source file conflicts with option 'CryptoKeyContainer'. Diagnostic(ErrorCode.ERR_CmdOptionConflictsSource).WithArguments("System.Reflection.AssemblyKeyNameAttribute", "CryptoKeyContainer") ); } [WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyFileCmdLine(CSharpParseOptions parseOptions) { string s = "public class C {}"; var options = TestOptions.SigningReleaseModule.WithCryptoKeyFile(s_keyPairFile); var other = CreateCompilation(s, options: options, parseOptions: parseOptions); var outStrm = new MemoryStream(); var success = other.Emit(outStrm); Assert.True(success.Success); ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyFileAttribute, parseOptions); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void BothLegacyAndNonLegacyGiveTheSameOutput(CSharpParseOptions parseOptions) { string s = "public class C {}"; var options = TestOptions.SigningReleaseDll .WithDeterministic(true) .WithModuleName("a.dll") .WithCryptoKeyFile(s_keyPairFile); var emitOptions = EmitOptions.Default.WithOutputNameOverride("a.dll"); var compilation = CreateCompilation(s, options: options, parseOptions: parseOptions); var stream = compilation.EmitToStream(emitOptions); stream.Position = 0; using (var metadata = AssemblyMetadata.CreateFromStream(stream)) { var key = metadata.GetAssembly().Identity.PublicKey; Assert.True(s_publicKey.SequenceEqual(key)); } } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignRefAssemblyKeyFileCmdLine(CSharpParseOptions parseOptions) { string s = "public class C {}"; var options = TestOptions.SigningDebugDll.WithCryptoKeyFile(s_keyPairFile); var other = CreateCompilation(s, options: options, parseOptions: parseOptions); var outStrm = new MemoryStream(); var refStrm = new MemoryStream(); var success = other.Emit(outStrm, metadataPEStream: refStrm); Assert.True(success.Success); outStrm.Position = 0; refStrm.Position = 0; Assert.True(ILValidation.IsStreamFullSigned(outStrm)); Assert.True(ILValidation.IsStreamFullSigned(refStrm)); } [WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyFileCmdLine_1(CSharpParseOptions parseOptions) { var x = s_keyPairFile; string s = String.Format("{0}{1}{2}", @"[assembly: System.Reflection.AssemblyKeyFile(@""", x, @""")] public class C {}"); var options = TestOptions.SigningReleaseModule.WithCryptoKeyFile(s_keyPairFile); var other = CreateCompilation(s, options: options, parseOptions: parseOptions); var outStrm = new MemoryStream(); var success = other.Emit(outStrm); Assert.True(success.Success); ConfirmModuleAttributePresentAndAddingToAssemblyResultsInSignedOutput(outStrm, AttributeDescription.AssemblyKeyFileAttribute, parseOptions); } [WorkItem(531195, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531195")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignModuleKeyFileCmdLine_2(CSharpParseOptions parseOptions) { var x = s_keyPairFile; string s = @"[assembly: System.Reflection.AssemblyKeyFile(""bogus"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.SigningReleaseModule.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); var outStrm = new MemoryStream(); var success = other.Emit(outStrm); Assert.False(success.Success); success.Diagnostics.Verify( // error CS7091: Attribute 'System.Reflection.AssemblyKeyFileAttribute' given in a source file conflicts with option 'CryptoKeyFile'. Diagnostic(ErrorCode.ERR_CmdOptionConflictsSource).WithArguments("System.Reflection.AssemblyKeyFileAttribute", "CryptoKeyFile")); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignItWithOnlyPublicKey(CSharpParseOptions parseOptions) { var other = CreateCompilation( @" public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_publicKeyFile), parseOptions: parseOptions); var outStrm = new MemoryStream(); var emitResult = other.Emit(outStrm); other.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_SignButNoPrivateKey).WithArguments(s_publicKeyFile)); other = other.WithOptions(TestOptions.SigningReleaseModule.WithCryptoKeyFile(s_publicKeyFile)); var assembly = CreateCompilation("", references: new[] { other.EmitToImageReference() }, options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); assembly.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_SignButNoPrivateKey).WithArguments(s_publicKeyFile)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void AssemblySignatureKeyOnNetModule(CSharpParseOptions parseOptions) { var other = CreateCompilation(@" [assembly: System.Reflection.AssemblySignatureKeyAttribute( ""00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"", ""bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseModule, parseOptions: parseOptions); var comp = CreateCompilation("", references: new[] { other.EmitToImageReference() }, options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); comp.VerifyDiagnostics(); Assert.StartsWith("0024000004", ((SourceAssemblySymbol)comp.Assembly.Modules[1].ContainingAssembly).SignatureKey); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void DelaySignItWithOnlyPublicKey(CSharpParseOptions parseOptions) { var other = CreateCompilation( @" [assembly: System.Reflection.AssemblyDelaySign(true)] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_publicKeyFile), parseOptions: parseOptions); using (var outStrm = new MemoryStream()) { var emitResult = other.Emit(outStrm); Assert.True(emitResult.Success); } } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void DelaySignButNoKey(CSharpParseOptions parseOptions) { var other = CreateCompilation( @" [assembly: System.Reflection.AssemblyDelaySign(true)] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); var outStrm = new MemoryStream(); var emitResult = other.Emit(outStrm); // Dev11: warning CS1699: Use command line option '/delaysign' or appropriate project settings instead of 'AssemblyDelaySignAttribute' // warning CS1607: Assembly generation -- Delay signing was requested, but no key was given // Roslyn: warning CS7033: Delay signing was specified and requires a public key, but no public key was specified other.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_DelaySignButNoKey)); Assert.True(emitResult.Success); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void SignInMemory(CSharpParseOptions parseOptions) { var other = CreateCompilation( @" public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); var outStrm = new MemoryStream(); var emitResult = other.Emit(outStrm); Assert.True(emitResult.Success); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void DelaySignConflict(CSharpParseOptions parseOptions) { var other = CreateCompilation( @" [assembly: System.Reflection.AssemblyDelaySign(true)] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithDelaySign(false), parseOptions: parseOptions); var outStrm = new MemoryStream(); //shouldn't get any key warning. other.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_CmdOptionConflictsSource).WithArguments("DelaySign", "System.Reflection.AssemblyDelaySignAttribute")); var emitResult = other.Emit(outStrm); Assert.True(emitResult.Success); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void DelaySignNoConflict(CSharpParseOptions parseOptions) { var other = CreateCompilation( @" [assembly: System.Reflection.AssemblyDelaySign(true)] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithDelaySign(true).WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); var outStrm = new MemoryStream(); //shouldn't get any key warning. other.VerifyDiagnostics(); var emitResult = other.Emit(outStrm); Assert.True(emitResult.Success); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void DelaySignWithAssemblySignatureKey(CSharpParseOptions parseOptions) { DelaySignWithAssemblySignatureKeyHelper(); void DelaySignWithAssemblySignatureKeyHelper() { //Note that this SignatureKey is some random one that I found in the devdiv build. //It is not related to the other keys we use in these tests. //In the native compiler, when the AssemblySignatureKey attribute is present, and //the binary is configured for delay signing, the contents of the assemblySignatureKey attribute //(rather than the contents of the keyfile or container) are used to compute the size needed to //reserve in the binary for its signature. Signing using this key is only supported via sn.exe var options = TestOptions.SigningReleaseDll .WithDelaySign(true) .WithCryptoKeyFile(s_keyPairFile); var other = CreateCompilation( @" [assembly: System.Reflection.AssemblyDelaySign(true)] [assembly: System.Reflection.AssemblySignatureKey(""002400000c800000140100000602000000240000525341310008000001000100613399aff18ef1a2c2514a273a42d9042b72321f1757102df9ebada69923e2738406c21e5b801552ab8d200a65a235e001ac9adc25f2d811eb09496a4c6a59d4619589c69f5baf0c4179a47311d92555cd006acc8b5959f2bd6e10e360c34537a1d266da8085856583c85d81da7f3ec01ed9564c58d93d713cd0172c8e23a10f0239b80c96b07736f5d8b022542a4e74251a5f432824318b3539a5a087f8e53d2f135f9ca47f3bb2e10aff0af0849504fb7cea3ff192dc8de0edad64c68efde34c56d302ad55fd6e80f302d5efcdeae953658d3452561b5f36c542efdbdd9f888538d374cef106acf7d93a4445c3c73cd911f0571aaf3d54da12b11ddec375b3"", ""a5a866e1ee186f807668209f3b11236ace5e21f117803a3143abb126dd035d7d2f876b6938aaf2ee3414d5420d753621400db44a49c486ce134300a2106adb6bdb433590fef8ad5c43cba82290dc49530effd86523d9483c00f458af46890036b0e2c61d077d7fbac467a506eba29e467a87198b053c749aa2a4d2840c784e6d"")] public class C { static void Goo() {} }", options: options, parseOptions: parseOptions); using (var metadata = ModuleMetadata.CreateFromImage(other.EmitToArray())) { var header = metadata.Module.PEReaderOpt.PEHeaders.CorHeader; //confirm header has expected SN signature size Assert.Equal(256, header.StrongNameSignatureDirectory.Size); // Delay sign should not have the strong name flag set Assert.Equal(CorFlags.ILOnly, header.Flags); } } } [WorkItem(545720, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545720")] [WorkItem(530050, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530050")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void InvalidAssemblyName(CSharpParseOptions parseOptions) { var il = @" .assembly extern mscorlib { } .assembly asm1 { .custom instance void [mscorlib]System.Runtime.CompilerServices.InternalsVisibleToAttribute::.ctor(string) = ( 01 00 09 2F 5C 3A 2A 3F 27 3C 3E 7C 00 00 ) // .../\:*?'<>|.. } .class private auto ansi beforefieldinit Base extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; var csharp = @" class Derived : Base { } "; var ilRef = CompileIL(il, prependDefaultHeader: false); var comp = CreateCompilation(csharp, new[] { ilRef }, assemblyName: "asm2", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); comp.VerifyDiagnostics( // NOTE: dev10 reports WRN_InvalidAssemblyName, but Roslyn won't (DevDiv #15099). // (2,17): error CS0122: 'Base' is inaccessible due to its protection level // class Derived : Base Diagnostic(ErrorCode.ERR_BadAccess, "Base").WithArguments("Base").WithLocation(2, 17) ); } [WorkItem(546331, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546331")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IvtVirtualCall1(CSharpParseOptions parseOptions) { var source1 = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm2"")] public class A { internal virtual void M() { } internal virtual int P { get { return 0; } } internal virtual event System.Action E { add { } remove { } } } "; var source2 = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm3"")] public class B : A { internal override void M() { } internal override int P { get { return 0; } } internal override event System.Action E { add { } remove { } } } "; var source3 = @" using System; using System.Linq.Expressions; public class C : B { internal override void M() { } void Test() { C c = new C(); c.M(); int x = c.P; c.E += null; } void TestET() { C c = new C(); Expression<Action> expr = () => c.M(); } } "; var comp1 = CreateCompilationWithMscorlib45(source1, options: TestOptions.SigningReleaseDll, assemblyName: "asm1", parseOptions: parseOptions); comp1.VerifyDiagnostics(); var ref1 = new CSharpCompilationReference(comp1); var comp2 = CreateCompilationWithMscorlib45(source2, new[] { ref1 }, options: TestOptions.SigningReleaseDll, assemblyName: "asm2", parseOptions: parseOptions); comp2.VerifyDiagnostics(); var ref2 = new CSharpCompilationReference(comp2); var comp3 = CreateCompilationWithMscorlib45(source3, new[] { SystemCoreRef, ref1, ref2 }, options: TestOptions.SigningReleaseDll, assemblyName: "asm3", parseOptions: parseOptions); comp3.VerifyDiagnostics(); // Note: calls B.M, not A.M, since asm1 is not accessible. var verifier = CompileAndVerify(comp3); verifier.VerifyIL("C.Test", @" { // Code size 25 (0x19) .maxstack 2 IL_0000: newobj ""C..ctor()"" IL_0005: dup IL_0006: callvirt ""void B.M()"" IL_000b: dup IL_000c: callvirt ""int B.P.get"" IL_0011: pop IL_0012: ldnull IL_0013: callvirt ""void B.E.add"" IL_0018: ret }"); verifier.VerifyIL("C.TestET", @" { // Code size 85 (0x55) .maxstack 3 IL_0000: newobj ""C.<>c__DisplayClass2_0..ctor()"" IL_0005: dup IL_0006: newobj ""C..ctor()"" IL_000b: stfld ""C C.<>c__DisplayClass2_0.c"" IL_0010: ldtoken ""C.<>c__DisplayClass2_0"" IL_0015: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001a: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_001f: ldtoken ""C C.<>c__DisplayClass2_0.c"" IL_0024: call ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle)"" IL_0029: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)"" IL_002e: ldtoken ""void B.M()"" IL_0033: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0038: castclass ""System.Reflection.MethodInfo"" IL_003d: ldc.i4.0 IL_003e: newarr ""System.Linq.Expressions.Expression"" IL_0043: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_0048: ldc.i4.0 IL_0049: newarr ""System.Linq.Expressions.ParameterExpression"" IL_004e: call ""System.Linq.Expressions.Expression<System.Action> System.Linq.Expressions.Expression.Lambda<System.Action>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0053: pop IL_0054: ret } "); } [WorkItem(546331, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546331")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IvtVirtualCall2(CSharpParseOptions parseOptions) { var source1 = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm2"")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm4"")] public class A { internal virtual void M() { } internal virtual int P { get { return 0; } } internal virtual event System.Action E { add { } remove { } } } "; var source2 = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm3"")] public class B : A { internal override void M() { } internal override int P { get { return 0; } } internal override event System.Action E { add { } remove { } } } "; var source3 = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm4"")] public class C : B { internal override void M() { } internal override int P { get { return 0; } } internal override event System.Action E { add { } remove { } } } "; var source4 = @" using System; using System.Linq.Expressions; public class D : C { internal override void M() { } void Test() { D d = new D(); d.M(); int x = d.P; d.E += null; } void TestET() { D d = new D(); Expression<Action> expr = () => d.M(); } } "; var comp1 = CreateCompilationWithMscorlib45(source1, options: TestOptions.SigningReleaseDll, assemblyName: "asm1", parseOptions: parseOptions); comp1.VerifyDiagnostics(); var ref1 = new CSharpCompilationReference(comp1); var comp2 = CreateCompilationWithMscorlib45(source2, new[] { ref1 }, options: TestOptions.SigningReleaseDll, assemblyName: "asm2", parseOptions: parseOptions); comp2.VerifyDiagnostics(); var ref2 = new CSharpCompilationReference(comp2); var comp3 = CreateCompilationWithMscorlib45(source3, new[] { ref1, ref2 }, options: TestOptions.SigningReleaseDll, assemblyName: "asm3", parseOptions: parseOptions); comp3.VerifyDiagnostics(); var ref3 = new CSharpCompilationReference(comp3); var comp4 = CreateCompilationWithMscorlib45(source4, new[] { SystemCoreRef, ref1, ref2, ref3 }, options: TestOptions.SigningReleaseDll, assemblyName: "asm4", parseOptions: parseOptions); comp4.VerifyDiagnostics(); // Note: calls C.M, not A.M, since asm2 is not accessible (stops search). // Confirmed in Dev11. var verifier = CompileAndVerify(comp4); verifier.VerifyIL("D.Test", @" { // Code size 25 (0x19) .maxstack 2 IL_0000: newobj ""D..ctor()"" IL_0005: dup IL_0006: callvirt ""void C.M()"" IL_000b: dup IL_000c: callvirt ""int C.P.get"" IL_0011: pop IL_0012: ldnull IL_0013: callvirt ""void C.E.add"" IL_0018: ret }"); verifier.VerifyIL("D.TestET", @" { // Code size 85 (0x55) .maxstack 3 IL_0000: newobj ""D.<>c__DisplayClass2_0..ctor()"" IL_0005: dup IL_0006: newobj ""D..ctor()"" IL_000b: stfld ""D D.<>c__DisplayClass2_0.d"" IL_0010: ldtoken ""D.<>c__DisplayClass2_0"" IL_0015: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_001a: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_001f: ldtoken ""D D.<>c__DisplayClass2_0.d"" IL_0024: call ""System.Reflection.FieldInfo System.Reflection.FieldInfo.GetFieldFromHandle(System.RuntimeFieldHandle)"" IL_0029: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Field(System.Linq.Expressions.Expression, System.Reflection.FieldInfo)"" IL_002e: ldtoken ""void C.M()"" IL_0033: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0038: castclass ""System.Reflection.MethodInfo"" IL_003d: ldc.i4.0 IL_003e: newarr ""System.Linq.Expressions.Expression"" IL_0043: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_0048: ldc.i4.0 IL_0049: newarr ""System.Linq.Expressions.ParameterExpression"" IL_004e: call ""System.Linq.Expressions.Expression<System.Action> System.Linq.Expressions.Expression.Lambda<System.Action>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0053: pop IL_0054: ret }"); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void IvtVirtual_ParamsAndDynamic(CSharpParseOptions parseOptions) { var source1 = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm2"")] public class A { internal virtual void F(params int[] a) { } internal virtual void G(System.Action<dynamic> a) { } [System.Obsolete(""obsolete"", true)] internal virtual void H() { } internal virtual int this[int x, params int[] a] { get { return 0; } } } "; // use IL to generate code that doesn't have synthesized ParamArrayAttribute on int[] parameters: // [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""asm3"")] // public class B : A // { // internal override void F(int[] a) { } // internal override void G(System.Action<object> a) { } // internal override void H() { } // internal override int this[int x, int[] a] { get { return 0; } } // } var source2 = @" .assembly extern asm1 { .ver 0:0:0:0 } .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly asm2 { .custom instance void [mscorlib]System.Runtime.CompilerServices.InternalsVisibleToAttribute::.ctor(string) = ( 01 00 04 61 73 6D 33 00 00 ) // ...asm3.. } .class public auto ansi beforefieldinit B extends [asm1]A { .custom instance void [mscorlib]System.Reflection.DefaultMemberAttribute::.ctor(string) = ( 01 00 04 49 74 65 6D 00 00 ) // ...Item.. .method assembly hidebysig strict virtual instance void F(int32[] a) cil managed { nop ret } .method assembly hidebysig strict virtual instance void G(class [mscorlib]System.Action`1<object> a) cil managed { nop ret } .method assembly hidebysig strict virtual instance void H() cil managed { nop ret } .method assembly hidebysig specialname strict virtual instance int32 get_Item(int32 x, int32[] a) cil managed { ldloc.0 ret } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [asm1]A::.ctor() ret } .property instance int32 Item(int32, int32[]) { .get instance int32 B::get_Item(int32, int32[]) } }"; var source3 = @" public class C : B { void Test() { C c = new C(); c.F(); c.G(x => x.Bar()); c.H(); var z = c[1]; } } "; var comp1 = CreateCompilation(source1, options: TestOptions.SigningReleaseDll, assemblyName: "asm1", parseOptions: parseOptions); comp1.VerifyDiagnostics(); var ref1 = new CSharpCompilationReference(comp1); var ref2 = CompileIL(source2, prependDefaultHeader: false); var comp3 = CreateCompilation(source3, new[] { ref1, ref2 }, options: TestOptions.SigningReleaseDll, assemblyName: "asm3", parseOptions: parseOptions); comp3.VerifyDiagnostics( // (7,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'a' of 'B.F(int[])' Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "F").WithArguments("a", "B.F(int[])").WithLocation(7, 11), // (8,20): error CS1061: 'object' does not contain a definition for 'Bar' and no extension method 'Bar' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Bar").WithArguments("object", "Bar").WithLocation(8, 20), // (10,17): error CS7036: There is no argument given that corresponds to the required formal parameter 'a' of 'B.this[int, int[]]' Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "c[1]").WithArguments("a", "B.this[int, int[]]").WithLocation(10, 17)); } [WorkItem(529779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529779")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void Bug529779_1(CSharpParseOptions parseOptions) { CSharpCompilation unsigned = CreateCompilation( @" public class C1 {} ", options: TestOptions.SigningReleaseDll, assemblyName: "Unsigned", parseOptions: parseOptions); CSharpCompilation other = CreateCompilation( @" public class C { internal void Goo() { var x = new System.Guid(); System.Console.WriteLine(x); } } ", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); CompileAndVerify(other.WithReferences(new[] { other.References.ElementAt(0), new CSharpCompilationReference(unsigned) })).VerifyDiagnostics(); CompileAndVerify(other.WithReferences(new[] { other.References.ElementAt(0), MetadataReference.CreateFromStream(unsigned.EmitToStream()) })).VerifyDiagnostics(); } [WorkItem(529779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529779")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void Bug529779_2(CSharpParseOptions parseOptions) { CSharpCompilation unsigned = CreateCompilation( @" public class C1 {} ", options: TestOptions.SigningReleaseDll, assemblyName: "Unsigned", parseOptions: parseOptions); CSharpCompilation other = CreateCompilation( @" public class C { internal void Goo() { var x = new C1(); System.Console.WriteLine(x); } } ", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), parseOptions: parseOptions); var comps = new[] {other.WithReferences(new []{other.References.ElementAt(0), new CSharpCompilationReference(unsigned)}), other.WithReferences(new []{other.References.ElementAt(0), MetadataReference.CreateFromStream(unsigned.EmitToStream()) })}; foreach (var comp in comps) { var outStrm = new MemoryStream(); var emitResult = comp.Emit(outStrm); // Dev12 reports an error Assert.True(emitResult.Success); emitResult.Diagnostics.Verify( // warning CS8002: Referenced assembly 'Unsigned, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' does not have a strong name. Diagnostic(ErrorCode.WRN_ReferencedAssemblyDoesNotHaveStrongName).WithArguments("Unsigned, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } } #if !NETCOREAPP [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] [WorkItem(399, "https://github.com/dotnet/roslyn/issues/399")] public void Bug399() { // The referenced assembly Signed.dll from the repro steps var signed = Roslyn.Test.Utilities.Desktop.DesktopRuntimeUtil.CreateMetadataReferenceFromHexGZipImage(@" 1f8b0800000000000400f38d9ac0c0ccc0c0c002c4ffff3330ec6080000706c2a00188f9e477f1316ce13cabb883d1e7ac62 484666b14241517e7a5162ae4272625e5e7e894252aa4251699e42669e828b7fb0426e7e4aaa1e2f2f970ad48c005706061f 4626869e0db74260e63e606052e466e486388a0922f64f094828c01d26006633419430302068860488f8790f06a0bf1c5a41 4a410841c32930580334d71f9f2781f6f11011161800e83e0e242e0790ef81c4d72b49ad2801b99b19a216d9af484624e815 a5e6e42743dde00055c386e14427729c08020f9420b407d86856860b404bef30323070a2a90b5080c4372120f781b1f3ada8 5ec1078b0a8f606f87dacdfeae3b162edb7de055d1af12c942bde5a267ef37e6c6b787945936b0ece367e8f6f87566c6f7bd 46a67f5da4f50d2f8a7e95e159552d1bf747b3ccdae1679c666dd10626bb1bf9815ad1c1876d04a76d78163e4b32a8a77fb3 a77adbec4d15c75de79cd9a3a4a5155dd1fc50b86ce5bd7797cce73b057b3931323082dd020ab332133d033d630363434b90 082b430e90ac0162e53a06861740da00c40e2e29cacc4b2f06a9906084c49b72683083022324ad28bb877aba80d402f96b40 7ca79cfc24a87f81d1c1c8ca000daf5faac60c620c60db41d1c408c50c0c5c509a012e0272e3425078c1792c0d0c48aa407a d41890d2355895288263e39b9f529a936ac7109c999e979aa2979293c3905b9c9c5f949399c4e0091184ca81d5332b80a9a9 8764e24b67aff2dff0feb1f6c7b7e6d50c1cdbab62c2244d1e74362c6000664a902ba600d5b1813c00e407053b1a821c0172 e1dddd9665aa576abb26acf9f6e2eaeaab7527ed1f49174726fc8f395ad7c676f650da9c159bbcd6a73cd031d8a9762d8d6b 47f9eac4955b0566f61fbc9010e4bbf0c405d6e6cc8392f63e6f4bc5339f2d9bb9725d79c0d5cecbacacc9af4522debeb30a bebd207fe9963cbbe995f66bb227ac4c0cfd91c3dce095617a66ce0e9d0b9e8eae9b25965c514278ff1dac3cc0021e2821f3 e29df38b5c72727c1333f32001949a0a0e2c10f8af0a344300ab2123052840cb16e30176c72818100000c85fc49900080000", filePath: "Signed.dll"); var compilation = CreateCompilation( "interface IDerived : ISigned { }", references: new[] { signed }, options: TestOptions.SigningReleaseDll .WithGeneralDiagnosticOption(ReportDiagnostic.Error) .WithCryptoKeyFile(s_keyPairFile)); // ACTUAL: error CS8002: Referenced assembly 'Signed, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' does not have a strong name. // EXPECTED: no errors compilation.VerifyEmitDiagnostics(); } #endif [ConditionalTheory(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionNeedsWindowsTypes)] [MemberData(nameof(AllProviderParseOptions))] public void AssemblySignatureKeyAttribute_1(CSharpParseOptions parseOptions) { var other = CreateEmptyCompilation( @" [assembly: System.Reflection.AssemblySignatureKeyAttribute( ""00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"", ""bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), references: new[] { MscorlibRef_v4_0_30316_17626 }, parseOptions: parseOptions); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.True(success.Success); } Assert.True(IsFileFullSigned(tempFile)); } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void AssemblySignatureKeyAttribute_2(CSharpParseOptions parseOptions) { var other = CreateEmptyCompilation( @" [assembly: System.Reflection.AssemblySignatureKeyAttribute( ""xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"", ""bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile), references: new[] { MscorlibRef_v4_0_30316_17626 }, parseOptions: parseOptions); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.False(success.Success); success.Diagnostics.Verify( // (3,1): error CS8003: Invalid signature public key specified in AssemblySignatureKeyAttribute. // "xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb", Diagnostic(ErrorCode.ERR_InvalidSignaturePublicKey, @"""xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb""")); } } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void AssemblySignatureKeyAttribute_3(CSharpParseOptions parseOptions) { var source = @" [assembly: System.Reflection.AssemblySignatureKeyAttribute( ""00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"", ""FFFFbc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")] public class C { static void Goo() {} }"; var options = TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_keyPairFile); var other = CreateEmptyCompilation(source, options: options, references: new[] { MscorlibRef_v4_0_30316_17626 }, parseOptions: parseOptions); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var result = other.Emit(outStrm); Assert.False(result.Success); result.Diagnostics.VerifyErrorCodes( // error CS7027: Error signing output with public key from file 'KeyPairFile.snk' -- Invalid countersignature specified in AssemblySignatureKeyAttribute. (Exception from HRESULT: 0x80131423) Diagnostic(ErrorCode.ERR_PublicKeyFileFailure)); } } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void AssemblySignatureKeyAttribute_4(CSharpParseOptions parseOptions) { var other = CreateEmptyCompilation( @" [assembly: System.Reflection.AssemblySignatureKeyAttribute( ""xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"", ""bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithDelaySign(true), references: new[] { MscorlibRef_v4_0_30316_17626 }, parseOptions: parseOptions); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.False(success.Success); success.Diagnostics.Verify( // (3,1): error CS8003: Invalid signature public key specified in AssemblySignatureKeyAttribute. // "xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb", Diagnostic(ErrorCode.ERR_InvalidSignaturePublicKey, @"""xxx 00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb""") ); } } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void AssemblySignatureKeyAttribute_5(CSharpParseOptions parseOptions) { var other = CreateEmptyCompilation( @" [assembly: System.Reflection.AssemblySignatureKeyAttribute( ""00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"", ""FFFFbc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithDelaySign(true), references: new[] { MscorlibRef_v4_0_30316_17626 }, parseOptions: parseOptions); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.True(success.Success); } } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void AssemblySignatureKeyAttribute_6(CSharpParseOptions parseOptions) { var other = CreateEmptyCompilation( @" [assembly: System.Reflection.AssemblySignatureKeyAttribute( null, ""bc6402e37ad723580b576953f40475ceae4b784d3661b90c3c6f5a1f7283388a7880683e0821610bee977f70506bb75584080e01b2ec97483c4d601ce1c981752a07276b420d78594d0ef28f8ec016d0a5b6d56cfc22e9f25a2ed9545942ccbf2d6295b9528641d98776e06a3273ab233271a3c9f53099b4d4e029582a6d5819"")] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithDelaySign(true), references: new[] { MscorlibRef_v4_0_30316_17626 }, parseOptions: parseOptions); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.False(success.Success); success.Diagnostics.Verify( // (3,1): error CS8003: Invalid signature public key specified in AssemblySignatureKeyAttribute. // null, Diagnostic(ErrorCode.ERR_InvalidSignaturePublicKey, "null") ); } } [Theory] [MemberData(nameof(AllProviderParseOptions))] public void AssemblySignatureKeyAttribute_7(CSharpParseOptions parseOptions) { var other = CreateEmptyCompilation( @" [assembly: System.Reflection.AssemblySignatureKeyAttribute( ""00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"", null)] public class C { static void Goo() {} }", options: TestOptions.SigningReleaseDll.WithCryptoKeyFile(s_publicKeyFile).WithDelaySign(true), references: new[] { MscorlibRef_v4_0_30316_17626 }, parseOptions: parseOptions); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.True(success.Success); } } [WorkItem(781312, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/781312")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void Bug781312(CSharpParseOptions parseOptions) { var ca = CreateCompilation( @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Bug781312_B, PublicKey = 0024000004800000940000000602000000240000525341310004000001000100458a131798af87d9e33088a3ab1c6101cbd462760f023d4f41d97f691033649e60b42001e94f4d79386b5e087b0a044c54b7afce151b3ad19b33b332b83087e3b8b022f45b5e4ff9b9a1077b0572ff0679ce38f884c7bd3d9b4090e4a7ee086b7dd292dc20f81a3b1b8a0b67ee77023131e59831c709c81d11c6856669974cc4"")] internal class A { public int Value = 3; } ", options: TestOptions.SigningReleaseDll, assemblyName: "Bug769840_A", parseOptions: parseOptions); CompileAndVerify(ca); var cb = CreateCompilation( @" internal class B { public A GetA() { return new A(); } }", options: TestOptions.SigningReleaseModule, assemblyName: "Bug781312_B", references: new[] { new CSharpCompilationReference(ca) }, parseOptions: parseOptions); CompileAndVerify(cb, verify: Verification.Fails).Diagnostics.Verify(); } [WorkItem(1072350, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1072350")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void Bug1072350(CSharpParseOptions parseOptions) { const string sourceA = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""X "")] internal class A { internal static int I = 42; }"; const string sourceB = @" class B { static void Main() { System.Console.Write(A.I); } }"; var ca = CreateCompilation(sourceA, options: TestOptions.ReleaseDll, assemblyName: "ClassLibrary2", parseOptions: parseOptions); CompileAndVerify(ca); var cb = CreateCompilation(sourceB, options: TestOptions.ReleaseExe, assemblyName: "X", references: new[] { new CSharpCompilationReference(ca) }, parseOptions: parseOptions); CompileAndVerify(cb, expectedOutput: "42").Diagnostics.Verify(); } [WorkItem(1072339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1072339")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void Bug1072339(CSharpParseOptions parseOptions) { const string sourceA = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""x"")] internal class A { internal static int I = 42; }"; const string sourceB = @" class B { static void Main() { System.Console.Write(A.I); } }"; var ca = CreateCompilation(sourceA, options: TestOptions.ReleaseDll, assemblyName: "ClassLibrary2", parseOptions: parseOptions); CompileAndVerify(ca); var cb = CreateCompilation(sourceB, options: TestOptions.ReleaseExe, assemblyName: "X", references: new[] { new CSharpCompilationReference(ca) }, parseOptions: parseOptions); CompileAndVerify(cb, expectedOutput: "42").Diagnostics.Verify(); } [WorkItem(1095618, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1095618")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void Bug1095618(CSharpParseOptions parseOptions) { const string source = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""System.Runtime.Serialization, PublicKey = 10000000000000000400000000000000"")]"; var ca = CreateCompilation(source, parseOptions: parseOptions); ca.VerifyDiagnostics( // (1,12): warning CS1700: Assembly reference 'System.Runtime.Serialization, PublicKey = 10000000000000000400000000000000' is invalid and cannot be resolved // [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("System.Runtime.Serialization, PublicKey = 10000000000000000400000000000000")] Diagnostic(ErrorCode.WRN_InvalidAssemblyName, @"System.Runtime.CompilerServices.InternalsVisibleTo(""System.Runtime.Serialization, PublicKey = 10000000000000000400000000000000"")").WithArguments("System.Runtime.Serialization, PublicKey = 10000000000000000400000000000000").WithLocation(1, 12)); var verifier = CompileAndVerify(ca, symbolValidator: module => { var assembly = module.ContainingAssembly; Assert.NotNull(assembly); Assert.False(assembly.GetAttributes().Any(attr => attr.IsTargetAttribute(assembly, AttributeDescription.InternalsVisibleToAttribute))); }); } [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void ConsistentErrorMessageWhenProvidingNullKeyFile(CSharpParseOptions parseOptions) { var options = TestOptions.DebugDll; Assert.Null(options.CryptoKeyFile); var compilation = CreateCompilation(string.Empty, options: options, parseOptions: parseOptions).VerifyDiagnostics(); VerifySignedBitSetAfterEmit(compilation, expectedToBeSigned: false); } [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void ConsistentErrorMessageWhenProvidingEmptyKeyFile(CSharpParseOptions parseOptions) { var options = TestOptions.DebugDll.WithCryptoKeyFile(string.Empty); var compilation = CreateCompilation(string.Empty, options: options, parseOptions: parseOptions).VerifyDiagnostics(); VerifySignedBitSetAfterEmit(compilation, expectedToBeSigned: false); } [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void ConsistentErrorMessageWhenProvidingNullKeyFile_PublicSign(CSharpParseOptions parseOptions) { var options = TestOptions.DebugDll.WithPublicSign(true); Assert.Null(options.CryptoKeyFile); CreateCompilation(string.Empty, options: options, parseOptions: parseOptions).VerifyDiagnostics( // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1)); } [WorkItem(11497, "https://github.com/dotnet/roslyn/issues/11497")] [Theory] [MemberData(nameof(AllProviderParseOptions))] public void ConsistentErrorMessageWhenProvidingEmptyKeyFile_PublicSign(CSharpParseOptions parseOptions) { var options = TestOptions.DebugDll.WithCryptoKeyFile(string.Empty).WithPublicSign(true); CreateCompilation(string.Empty, options: options, parseOptions: parseOptions).VerifyDiagnostics( // error CS8102: Public signing was specified and requires a public key, but no public key was specified. Diagnostic(ErrorCode.ERR_PublicSignButNoKey).WithLocation(1, 1)); } [ConditionalFact(typeof(WindowsOnly), Reason = ConditionalSkipReason.TestExecutionHasCOMInterop)] public void LegacyDoesNotUseBuilder() { var provider = new TestDesktopStrongNameProvider(fileSystem: new VirtualizedStrongNameFileSystem()) { SignBuilderFunc = delegate { throw null; } }; var options = TestOptions.ReleaseDll .WithStrongNameProvider(provider) .WithCryptoKeyFile(s_keyPairFile); var other = CreateCompilation( @" public class C { static void Goo() {} }", options: options, parseOptions: TestOptions.RegularWithLegacyStrongName); var tempFile = Temp.CreateFile(); using (var outStrm = tempFile.Open()) { var success = other.Emit(outStrm); Assert.True(success.Success); } Assert.True(IsFileFullSigned(tempFile)); } #endregion [Theory] [MemberData(nameof(AllProviderParseOptions))] [WorkItem(1341051, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1341051")] public void IVT_Circularity(CSharpParseOptions parseOptions) { string lib_cs = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""WantsIVTAccess"")] public abstract class TestBaseClass { protected internal virtual bool SupportSvgImages { get; } } "; var libRef = CreateCompilation(lib_cs, options: TestOptions.SigningReleaseDll, parseOptions: parseOptions).EmitToImageReference(); string source1 = @" [assembly: Class1] "; string source2 = @" public class Class1 : TestBaseClass { protected internal override bool SupportSvgImages { get { return true; } } } "; // To find what the property overrides, an IVT check is involved so we need to bind assembly-level attributes var c2 = CreateCompilation(new[] { source1, source2 }, new[] { libRef }, assemblyName: "WantsIVTAccess", options: TestOptions.SigningReleaseDll, parseOptions: parseOptions); c2.VerifyEmitDiagnostics( // (2,12): error CS0616: 'Class1' is not an attribute class // [assembly: Class1] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Class1").WithArguments("Class1").WithLocation(2, 12) ); } [Fact, WorkItem(1341051, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1341051")] public void IVT_Circularity_AttributeReferencesProperty() { string lib_cs = @" [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""WantsIVTAccess"")] public abstract class TestBaseClass { protected internal virtual bool SupportSvgImages { get; } } public class MyAttribute : System.Attribute { public MyAttribute(string s) { } } "; var libRef = CreateCompilation(lib_cs, options: TestOptions.SigningReleaseDll).EmitToImageReference(); string source1 = @" [assembly: MyAttribute(Class1.Constant)] "; string source2 = @" public class Class1 : TestBaseClass { internal const string Constant = ""text""; protected internal override bool SupportSvgImages { get { return true; } } } "; // To find what the property overrides, an IVT check is involved so we need to bind assembly-level attributes var c2 = CreateCompilation(new[] { source1, source2 }, new[] { libRef }, assemblyName: "WantsIVTAccess", options: TestOptions.SigningReleaseDll); c2.VerifyEmitDiagnostics(); } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/Core/Portable/Simplification/Simplifiers/AbstractSimplifier.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Simplification.Simplifiers { internal abstract class AbstractSimplifier<TSyntax, TSimplifiedSyntax> where TSyntax : SyntaxNode where TSimplifiedSyntax : SyntaxNode { public abstract bool TrySimplify( TSyntax syntax, SemanticModel semanticModel, OptionSet optionSet, out TSimplifiedSyntax replacementNode, out TextSpan issueSpan, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Simplification.Simplifiers { internal abstract class AbstractSimplifier<TSyntax, TSimplifiedSyntax> where TSyntax : SyntaxNode where TSimplifiedSyntax : SyntaxNode { public abstract bool TrySimplify( TSyntax syntax, SemanticModel semanticModel, OptionSet optionSet, out TSimplifiedSyntax replacementNode, out TextSpan issueSpan, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/VisualStudio/IntegrationTest/IntegrationTests/AbstractInteractiveWindowTest.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.VisualStudio.IntegrationTest.Utilities; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests { public abstract class AbstractInteractiveWindowTest : AbstractIntegrationTest { protected AbstractInteractiveWindowTest(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory) { } public override async Task InitializeAsync() { await base.InitializeAsync().ConfigureAwait(true); ClearInteractiveWindow(); } protected void ClearInteractiveWindow() { VisualStudio.InteractiveWindow.Initialize(); VisualStudio.InteractiveWindow.ClearScreen(); VisualStudio.InteractiveWindow.ShowWindow(); VisualStudio.InteractiveWindow.Reset(); } } }
// Licensed to the .NET Foundation under one or more 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.VisualStudio.IntegrationTest.Utilities; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests { public abstract class AbstractInteractiveWindowTest : AbstractIntegrationTest { protected AbstractInteractiveWindowTest(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory) { } public override async Task InitializeAsync() { await base.InitializeAsync().ConfigureAwait(true); ClearInteractiveWindow(); } protected void ClearInteractiveWindow() { VisualStudio.InteractiveWindow.Initialize(); VisualStudio.InteractiveWindow.ClearScreen(); VisualStudio.InteractiveWindow.ShowWindow(); VisualStudio.InteractiveWindow.Reset(); } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/Core/Portable/Rename/RenameUtilities.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 Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Rename { internal static class RenameUtilities { internal static SyntaxToken UpdateAliasAnnotation(SyntaxToken token, ISymbol aliasSymbol, string replacementText) { // If the below Single() assert fails then it means the token has gone through a rename session where // it obtained an AliasSyntaxAnnotation and it is going through another rename session. Make sure the token // has only one annotation pertaining to the current session or try to extract only the current session annotation var originalAliasAnnotation = token.GetAnnotations(AliasAnnotation.Kind).Single(); var originalAliasName = AliasAnnotation.GetAliasName(originalAliasAnnotation); if (originalAliasName == aliasSymbol.Name) { token = token.WithoutAnnotations(originalAliasAnnotation); var replacementAliasAnnotation = AliasAnnotation.Create(replacementText); token = token.WithAdditionalAnnotations(replacementAliasAnnotation); } return token; } internal static ImmutableArray<ISymbol> GetSymbolsTouchingPosition( int position, SemanticModel semanticModel, Workspace workspace, CancellationToken cancellationToken) { var bindableToken = semanticModel.SyntaxTree.GetRoot(cancellationToken).FindToken(position, findInsideTrivia: true); var semanticInfo = semanticModel.GetSemanticInfo(bindableToken, workspace, cancellationToken); var symbols = semanticInfo.DeclaredSymbol != null ? ImmutableArray.Create<ISymbol>(semanticInfo.DeclaredSymbol) : semanticInfo.GetSymbols(includeType: false); // if there are more than one symbol, then remove the alias symbols. // When using (not declaring) an alias, the alias symbol and the target symbol are returned // by GetSymbols if (symbols.Length > 1) { symbols = symbols.WhereAsArray(s => s.Kind != SymbolKind.Alias); } if (symbols.Length == 0) { var info = semanticModel.GetSymbolInfo(bindableToken, cancellationToken); if (info.CandidateReason == CandidateReason.MemberGroup) { return info.CandidateSymbols; } } return symbols; } private static bool IsSymbolDefinedInsideMethod(ISymbol symbol) { return symbol.Kind == SymbolKind.Local || symbol.Kind == SymbolKind.Label || symbol.Kind == SymbolKind.RangeVariable || symbol.Kind == SymbolKind.Parameter; } internal static IEnumerable<Document> GetDocumentsAffectedByRename(ISymbol symbol, Solution solution, IEnumerable<RenameLocation> renameLocations) { if (IsSymbolDefinedInsideMethod(symbol)) { // if the symbol was declared inside of a method, don't check for conflicts in non-renamed documents. return renameLocations.Select(l => solution.GetDocument(l.DocumentId)); } else { var documentsOfRenameSymbolDeclaration = symbol.Locations.Where(l => l.IsInSource).Select(l => solution.GetDocument(l.SourceTree)); var projectIdsOfRenameSymbolDeclaration = documentsOfRenameSymbolDeclaration.SelectMany(d => d.GetLinkedDocumentIds()) .Concat(documentsOfRenameSymbolDeclaration.First().Id) .Select(d => d.ProjectId).Distinct(); // perf optimization: only look in declaring project when possible if (ShouldRenameOnlyAffectDeclaringProject(symbol)) { var isSubset = renameLocations.Select(l => l.DocumentId.ProjectId).Distinct().Except(projectIdsOfRenameSymbolDeclaration).IsEmpty(); Contract.ThrowIfFalse(isSubset); return projectIdsOfRenameSymbolDeclaration.SelectMany(p => solution.GetProject(p).Documents); } else { // We are trying to figure out the projects that directly depend on the project that contains the declaration for // the rename symbol. Other projects should not be affected by the rename. var relevantProjects = projectIdsOfRenameSymbolDeclaration.Concat(projectIdsOfRenameSymbolDeclaration.SelectMany(p => solution.GetProjectDependencyGraph().GetProjectsThatDirectlyDependOnThisProject(p))).Distinct(); return relevantProjects.SelectMany(p => solution.GetProject(p).Documents); } } } /// <summary> /// Renaming a private symbol typically confines the set of references and potential /// conflicts to that symbols declaring project. However, rename may cascade to /// non-public symbols which may then require other projects be considered. /// </summary> private static bool ShouldRenameOnlyAffectDeclaringProject(ISymbol symbol) { if (symbol.DeclaredAccessibility != Accessibility.Private) { // non-private members can influence other projects. return false; } if (symbol.ExplicitInterfaceImplementations().Any()) { // Explicit interface implementations can cascade to other projects return false; } if (symbol.IsOverride) { // private-overrides aren't actually legal. But if we see one, we tolerate it and search other projects in case // they override it. // https://github.com/dotnet/roslyn/issues/25682 return false; } return true; } internal static TokenRenameInfo GetTokenRenameInfo( ISemanticFactsService semanticFacts, SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken) { var symbol = semanticFacts.GetDeclaredSymbol(semanticModel, token, cancellationToken); if (symbol != null) { return TokenRenameInfo.CreateSingleSymbolTokenInfo(symbol); } var symbolInfo = semanticModel.GetSymbolInfo(token, cancellationToken); if (symbolInfo.Symbol != null) { if (symbolInfo.Symbol.IsTupleType()) { return TokenRenameInfo.NoSymbolsTokenInfo; } return TokenRenameInfo.CreateSingleSymbolTokenInfo(symbolInfo.Symbol); } if (symbolInfo.CandidateReason == CandidateReason.MemberGroup && symbolInfo.CandidateSymbols.Any()) { // This is a reference from a nameof expression. Allow the rename but set the RenameOverloads option return TokenRenameInfo.CreateMemberGroupTokenInfo(symbolInfo.CandidateSymbols); } if (RenameLocation.ShouldRename(symbolInfo.CandidateReason) && symbolInfo.CandidateSymbols.Length == 1) { // TODO(cyrusn): We're allowing rename here, but we likely should let the user // know that there is an error in the code and that rename results might be // inaccurate. return TokenRenameInfo.CreateSingleSymbolTokenInfo(symbolInfo.CandidateSymbols[0]); } return TokenRenameInfo.NoSymbolsTokenInfo; } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Rename { internal static class RenameUtilities { internal static SyntaxToken UpdateAliasAnnotation(SyntaxToken token, ISymbol aliasSymbol, string replacementText) { // If the below Single() assert fails then it means the token has gone through a rename session where // it obtained an AliasSyntaxAnnotation and it is going through another rename session. Make sure the token // has only one annotation pertaining to the current session or try to extract only the current session annotation var originalAliasAnnotation = token.GetAnnotations(AliasAnnotation.Kind).Single(); var originalAliasName = AliasAnnotation.GetAliasName(originalAliasAnnotation); if (originalAliasName == aliasSymbol.Name) { token = token.WithoutAnnotations(originalAliasAnnotation); var replacementAliasAnnotation = AliasAnnotation.Create(replacementText); token = token.WithAdditionalAnnotations(replacementAliasAnnotation); } return token; } internal static ImmutableArray<ISymbol> GetSymbolsTouchingPosition( int position, SemanticModel semanticModel, Workspace workspace, CancellationToken cancellationToken) { var bindableToken = semanticModel.SyntaxTree.GetRoot(cancellationToken).FindToken(position, findInsideTrivia: true); var semanticInfo = semanticModel.GetSemanticInfo(bindableToken, workspace, cancellationToken); var symbols = semanticInfo.DeclaredSymbol != null ? ImmutableArray.Create<ISymbol>(semanticInfo.DeclaredSymbol) : semanticInfo.GetSymbols(includeType: false); // if there are more than one symbol, then remove the alias symbols. // When using (not declaring) an alias, the alias symbol and the target symbol are returned // by GetSymbols if (symbols.Length > 1) { symbols = symbols.WhereAsArray(s => s.Kind != SymbolKind.Alias); } if (symbols.Length == 0) { var info = semanticModel.GetSymbolInfo(bindableToken, cancellationToken); if (info.CandidateReason == CandidateReason.MemberGroup) { return info.CandidateSymbols; } } return symbols; } private static bool IsSymbolDefinedInsideMethod(ISymbol symbol) { return symbol.Kind == SymbolKind.Local || symbol.Kind == SymbolKind.Label || symbol.Kind == SymbolKind.RangeVariable || symbol.Kind == SymbolKind.Parameter; } internal static IEnumerable<Document> GetDocumentsAffectedByRename(ISymbol symbol, Solution solution, IEnumerable<RenameLocation> renameLocations) { if (IsSymbolDefinedInsideMethod(symbol)) { // if the symbol was declared inside of a method, don't check for conflicts in non-renamed documents. return renameLocations.Select(l => solution.GetDocument(l.DocumentId)); } else { var documentsOfRenameSymbolDeclaration = symbol.Locations.Where(l => l.IsInSource).Select(l => solution.GetDocument(l.SourceTree)); var projectIdsOfRenameSymbolDeclaration = documentsOfRenameSymbolDeclaration.SelectMany(d => d.GetLinkedDocumentIds()) .Concat(documentsOfRenameSymbolDeclaration.First().Id) .Select(d => d.ProjectId).Distinct(); // perf optimization: only look in declaring project when possible if (ShouldRenameOnlyAffectDeclaringProject(symbol)) { var isSubset = renameLocations.Select(l => l.DocumentId.ProjectId).Distinct().Except(projectIdsOfRenameSymbolDeclaration).IsEmpty(); Contract.ThrowIfFalse(isSubset); return projectIdsOfRenameSymbolDeclaration.SelectMany(p => solution.GetProject(p).Documents); } else { // We are trying to figure out the projects that directly depend on the project that contains the declaration for // the rename symbol. Other projects should not be affected by the rename. var relevantProjects = projectIdsOfRenameSymbolDeclaration.Concat(projectIdsOfRenameSymbolDeclaration.SelectMany(p => solution.GetProjectDependencyGraph().GetProjectsThatDirectlyDependOnThisProject(p))).Distinct(); return relevantProjects.SelectMany(p => solution.GetProject(p).Documents); } } } /// <summary> /// Renaming a private symbol typically confines the set of references and potential /// conflicts to that symbols declaring project. However, rename may cascade to /// non-public symbols which may then require other projects be considered. /// </summary> private static bool ShouldRenameOnlyAffectDeclaringProject(ISymbol symbol) { if (symbol.DeclaredAccessibility != Accessibility.Private) { // non-private members can influence other projects. return false; } if (symbol.ExplicitInterfaceImplementations().Any()) { // Explicit interface implementations can cascade to other projects return false; } if (symbol.IsOverride) { // private-overrides aren't actually legal. But if we see one, we tolerate it and search other projects in case // they override it. // https://github.com/dotnet/roslyn/issues/25682 return false; } return true; } internal static TokenRenameInfo GetTokenRenameInfo( ISemanticFactsService semanticFacts, SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken) { var symbol = semanticFacts.GetDeclaredSymbol(semanticModel, token, cancellationToken); if (symbol != null) { return TokenRenameInfo.CreateSingleSymbolTokenInfo(symbol); } var symbolInfo = semanticModel.GetSymbolInfo(token, cancellationToken); if (symbolInfo.Symbol != null) { if (symbolInfo.Symbol.IsTupleType()) { return TokenRenameInfo.NoSymbolsTokenInfo; } return TokenRenameInfo.CreateSingleSymbolTokenInfo(symbolInfo.Symbol); } if (symbolInfo.CandidateReason == CandidateReason.MemberGroup && symbolInfo.CandidateSymbols.Any()) { // This is a reference from a nameof expression. Allow the rename but set the RenameOverloads option return TokenRenameInfo.CreateMemberGroupTokenInfo(symbolInfo.CandidateSymbols); } if (RenameLocation.ShouldRename(symbolInfo.CandidateReason) && symbolInfo.CandidateSymbols.Length == 1) { // TODO(cyrusn): We're allowing rename here, but we likely should let the user // know that there is an error in the code and that rename results might be // inaccurate. return TokenRenameInfo.CreateSingleSymbolTokenInfo(symbolInfo.CandidateSymbols[0]); } return TokenRenameInfo.NoSymbolsTokenInfo; } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/VisualStudio/Xaml/Impl/Features/InlineRename/XamlEditorInlineRenameService.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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Rename; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.Xaml.Features.InlineRename { [ExportLanguageService(typeof(IEditorInlineRenameService), StringConstants.XamlLanguageName), Shared] internal class XamlEditorInlineRenameService : IEditorInlineRenameService { private readonly IXamlRenameInfoService _renameService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XamlEditorInlineRenameService(IXamlRenameInfoService renameService) { _renameService = renameService; } public async Task<IInlineRenameInfo> GetRenameInfoAsync(Document document, int position, CancellationToken cancellationToken) { var renameInfo = await _renameService.GetRenameInfoAsync(document, position, cancellationToken).ConfigureAwait(false); return new InlineRenameInfo(document, renameInfo); } private class InlineRenameInfo : IInlineRenameInfo { private readonly Document _document; private readonly IXamlRenameInfo _renameInfo; public InlineRenameInfo(Document document, IXamlRenameInfo renameInfo) { _document = document; _renameInfo = renameInfo; } public bool CanRename => _renameInfo.CanRename; public string DisplayName => _renameInfo.DisplayName; public string FullDisplayName => _renameInfo.FullDisplayName; public Glyph Glyph => InlineRenameInfo.FromSymbolKind(_renameInfo.Kind); public bool HasOverloads => false; public bool ForceRenameOverloads => false; public string LocalizedErrorMessage => _renameInfo.LocalizedErrorMessage; public TextSpan TriggerSpan => _renameInfo.TriggerSpan; // This property isn't currently supported in XAML since it would involve modifying the IXamlRenameInfo interface. public ImmutableArray<CodeAnalysis.DocumentSpan> DefinitionLocations => default; public async Task<IInlineRenameLocationSet> FindRenameLocationsAsync(OptionSet optionSet, CancellationToken cancellationToken) { var references = new List<InlineRenameLocation>(); var renameLocations = await _renameInfo.FindRenameLocationsAsync( renameInStrings: optionSet.GetOption(RenameOptions.RenameInStrings), renameInComments: optionSet.GetOption(RenameOptions.RenameInComments), cancellationToken: cancellationToken).ConfigureAwait(false); references.AddRange(renameLocations.Select( ds => new InlineRenameLocation(ds.Document, ds.TextSpan))); return new InlineRenameLocationSet( _renameInfo, _document.Project.Solution, references.ToImmutableArray()); } public TextSpan? GetConflictEditSpan(InlineRenameLocation location, string triggerText, string replacementText, CancellationToken cancellationToken) { return location.TextSpan; } public string GetFinalSymbolName(string replacementText) { return replacementText; } public TextSpan GetReferenceEditSpan(InlineRenameLocation location, string triggerText, CancellationToken cancellationToken) { return location.TextSpan; } public bool TryOnAfterGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, string replacementText) { return true; } public bool TryOnBeforeGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, string replacementText) { return true; } private static Glyph FromSymbolKind(SymbolKind kind) { var glyph = Glyph.Error; switch (kind) { case SymbolKind.Namespace: glyph = Glyph.Namespace; break; case SymbolKind.NamedType: glyph = Glyph.ClassPublic; break; case SymbolKind.Property: glyph = Glyph.PropertyPublic; break; case SymbolKind.Event: glyph = Glyph.EventPublic; break; } return glyph; } private class InlineRenameLocationSet : IInlineRenameLocationSet { private readonly IXamlRenameInfo _renameInfo; private readonly Solution _oldSolution; public InlineRenameLocationSet(IXamlRenameInfo renameInfo, Solution solution, ImmutableArray<InlineRenameLocation> locations) { _renameInfo = renameInfo; _oldSolution = solution; Locations = locations; } public IList<InlineRenameLocation> Locations { get; } public bool IsReplacementTextValid(string replacementText) { return _renameInfo.IsReplacementTextValid(replacementText); } public async Task<IInlineRenameReplacementInfo> GetReplacementsAsync(string replacementText, OptionSet optionSet, CancellationToken cancellationToken) { var newSolution = _oldSolution; foreach (var group in Locations.GroupBy(l => l.Document)) { var document = group.Key; var oldSource = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var newSource = oldSource.WithChanges(group.Select(l => new TextChange(l.TextSpan, replacementText))); newSolution = newSolution.WithDocumentText(document.Id, newSource); } return new InlineRenameReplacementInfo(this, newSolution, replacementText); } private class InlineRenameReplacementInfo : IInlineRenameReplacementInfo { private readonly InlineRenameLocationSet _inlineRenameLocationSet; private readonly string _replacementText; public InlineRenameReplacementInfo(InlineRenameLocationSet inlineRenameLocationSet, Solution newSolution, string replacementText) { NewSolution = newSolution; _inlineRenameLocationSet = inlineRenameLocationSet; _replacementText = replacementText; } public Solution NewSolution { get; } public IEnumerable<DocumentId> DocumentIds => _inlineRenameLocationSet.Locations.Select(l => l.Document.Id).Distinct(); public bool ReplacementTextValid => _inlineRenameLocationSet.IsReplacementTextValid(_replacementText); public IEnumerable<InlineRenameReplacement> GetReplacements(DocumentId documentId) { yield break; } } } } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Rename; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.Xaml.Features.InlineRename { [ExportLanguageService(typeof(IEditorInlineRenameService), StringConstants.XamlLanguageName), Shared] internal class XamlEditorInlineRenameService : IEditorInlineRenameService { private readonly IXamlRenameInfoService _renameService; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public XamlEditorInlineRenameService(IXamlRenameInfoService renameService) { _renameService = renameService; } public async Task<IInlineRenameInfo> GetRenameInfoAsync(Document document, int position, CancellationToken cancellationToken) { var renameInfo = await _renameService.GetRenameInfoAsync(document, position, cancellationToken).ConfigureAwait(false); return new InlineRenameInfo(document, renameInfo); } private class InlineRenameInfo : IInlineRenameInfo { private readonly Document _document; private readonly IXamlRenameInfo _renameInfo; public InlineRenameInfo(Document document, IXamlRenameInfo renameInfo) { _document = document; _renameInfo = renameInfo; } public bool CanRename => _renameInfo.CanRename; public string DisplayName => _renameInfo.DisplayName; public string FullDisplayName => _renameInfo.FullDisplayName; public Glyph Glyph => InlineRenameInfo.FromSymbolKind(_renameInfo.Kind); public bool HasOverloads => false; public bool ForceRenameOverloads => false; public string LocalizedErrorMessage => _renameInfo.LocalizedErrorMessage; public TextSpan TriggerSpan => _renameInfo.TriggerSpan; // This property isn't currently supported in XAML since it would involve modifying the IXamlRenameInfo interface. public ImmutableArray<CodeAnalysis.DocumentSpan> DefinitionLocations => default; public async Task<IInlineRenameLocationSet> FindRenameLocationsAsync(OptionSet optionSet, CancellationToken cancellationToken) { var references = new List<InlineRenameLocation>(); var renameLocations = await _renameInfo.FindRenameLocationsAsync( renameInStrings: optionSet.GetOption(RenameOptions.RenameInStrings), renameInComments: optionSet.GetOption(RenameOptions.RenameInComments), cancellationToken: cancellationToken).ConfigureAwait(false); references.AddRange(renameLocations.Select( ds => new InlineRenameLocation(ds.Document, ds.TextSpan))); return new InlineRenameLocationSet( _renameInfo, _document.Project.Solution, references.ToImmutableArray()); } public TextSpan? GetConflictEditSpan(InlineRenameLocation location, string triggerText, string replacementText, CancellationToken cancellationToken) { return location.TextSpan; } public string GetFinalSymbolName(string replacementText) { return replacementText; } public TextSpan GetReferenceEditSpan(InlineRenameLocation location, string triggerText, CancellationToken cancellationToken) { return location.TextSpan; } public bool TryOnAfterGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, string replacementText) { return true; } public bool TryOnBeforeGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, string replacementText) { return true; } private static Glyph FromSymbolKind(SymbolKind kind) { var glyph = Glyph.Error; switch (kind) { case SymbolKind.Namespace: glyph = Glyph.Namespace; break; case SymbolKind.NamedType: glyph = Glyph.ClassPublic; break; case SymbolKind.Property: glyph = Glyph.PropertyPublic; break; case SymbolKind.Event: glyph = Glyph.EventPublic; break; } return glyph; } private class InlineRenameLocationSet : IInlineRenameLocationSet { private readonly IXamlRenameInfo _renameInfo; private readonly Solution _oldSolution; public InlineRenameLocationSet(IXamlRenameInfo renameInfo, Solution solution, ImmutableArray<InlineRenameLocation> locations) { _renameInfo = renameInfo; _oldSolution = solution; Locations = locations; } public IList<InlineRenameLocation> Locations { get; } public bool IsReplacementTextValid(string replacementText) { return _renameInfo.IsReplacementTextValid(replacementText); } public async Task<IInlineRenameReplacementInfo> GetReplacementsAsync(string replacementText, OptionSet optionSet, CancellationToken cancellationToken) { var newSolution = _oldSolution; foreach (var group in Locations.GroupBy(l => l.Document)) { var document = group.Key; var oldSource = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); var newSource = oldSource.WithChanges(group.Select(l => new TextChange(l.TextSpan, replacementText))); newSolution = newSolution.WithDocumentText(document.Id, newSource); } return new InlineRenameReplacementInfo(this, newSolution, replacementText); } private class InlineRenameReplacementInfo : IInlineRenameReplacementInfo { private readonly InlineRenameLocationSet _inlineRenameLocationSet; private readonly string _replacementText; public InlineRenameReplacementInfo(InlineRenameLocationSet inlineRenameLocationSet, Solution newSolution, string replacementText) { NewSolution = newSolution; _inlineRenameLocationSet = inlineRenameLocationSet; _replacementText = replacementText; } public Solution NewSolution { get; } public IEnumerable<DocumentId> DocumentIds => _inlineRenameLocationSet.Locations.Select(l => l.Document.Id).Distinct(); public bool ReplacementTextValid => _inlineRenameLocationSet.IsReplacementTextValid(_replacementText); public IEnumerable<InlineRenameReplacement> GetReplacements(DocumentId documentId) { yield break; } } } } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/CSharpTest/BraceMatching/CSharpBraceMatcherTests.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.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.BraceMatching; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.BraceMatching { public class CSharpBraceMatcherTests : AbstractBraceMatcherTests { protected override TestWorkspace CreateWorkspaceFromCode(string code, ParseOptions options) => TestWorkspace.CreateCSharp(code, options); [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestEmptyFile() { var code = @"$$"; var expected = @""; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestAtFirstPositionInFile() { var code = @"$$public class C { }"; var expected = @"public class C { }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestAtLastPositionInFile() { var code = @"public class C { }$$"; var expected = @"public class C [|{|] }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestCurlyBrace1() { var code = @"public class C $${ }"; var expected = @"public class C { [|}|]"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestCurlyBrace2() { var code = @"public class C {$$ }"; var expected = @"public class C { [|}|]"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestCurlyBrace3() { var code = @"public class C { $$}"; var expected = @"public class C [|{|] }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestCurlyBrace4() { var code = @"public class C { }$$"; var expected = @"public class C [|{|] }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestParen1() { var code = @"public class C { void Goo$$() { } }"; var expected = @"public class C { void Goo([|)|] { } }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestParen2() { var code = @"public class C { void Goo($$) { } }"; var expected = @"public class C { void Goo([|)|] { } }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestParen3() { var code = @"public class C { void Goo($$ ) { } }"; var expected = @"public class C { void Goo( [|)|] { } }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestParen4() { var code = @"public class C { void Goo( $$) { } }"; var expected = @"public class C { void Goo[|(|] ) { } }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestParen5() { var code = @"public class C { void Goo( )$$ { } }"; var expected = @"public class C { void Goo[|(|] ) { } }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestParen6() { var code = @"public class C { void Goo()$$ { } }"; var expected = @"public class C { void Goo[|(|]) { } }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestSquareBracket1() { var code = @"public class C { int$$[] i; }"; var expected = @"public class C { int[[|]|] i; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestSquareBracket2() { var code = @"public class C { int[$$] i; }"; var expected = @"public class C { int[[|]|] i; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestSquareBracket3() { var code = @"public class C { int[$$ ] i; }"; var expected = @"public class C { int[ [|]|] i; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestSquareBracket4() { var code = @"public class C { int[ $$] i; }"; var expected = @"public class C { int[|[|] ] i; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestSquareBracket5() { var code = @"public class C { int[ ]$$ i; }"; var expected = @"public class C { int[|[|] ] i; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestSquareBracket6() { var code = @"public class C { int[]$$ i; }"; var expected = @"public class C { int[|[|]] i; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestAngleBracket1() { var code = @"public class C { Goo$$<int> f; }"; var expected = @"public class C { Goo<int[|>|] f; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestAngleBracket2() { var code = @"public class C { Goo<$$int> f; }"; var expected = @"public class C { Goo<int[|>|] f; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestAngleBracket3() { var code = @"public class C { Goo<int$$> f; }"; var expected = @"public class C { Goo[|<|]int> f; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestAngleBracket4() { var code = @"public class C { Goo<int>$$ f; }"; var expected = @"public class C { Goo[|<|]int> f; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestNestedAngleBracket1() { var code = @"public class C { Func$$<Func<int,int>> f; }"; var expected = @"public class C { Func<Func<int,int>[|>|] f; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestNestedAngleBracket2() { var code = @"public class C { Func<$$Func<int,int>> f; }"; var expected = @"public class C { Func<Func<int,int>[|>|] f; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestNestedAngleBracket3() { var code = @"public class C { Func<Func$$<int,int>> f; }"; var expected = @"public class C { Func<Func<int,int[|>|]> f; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestNestedAngleBracket4() { var code = @"public class C { Func<Func<$$int,int>> f; }"; var expected = @"public class C { Func<Func<int,int[|>|]> f; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestNestedAngleBracket5() { var code = @"public class C { Func<Func<int,int$$>> f; }"; var expected = @"public class C { Func<Func[|<|]int,int>> f; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestNestedAngleBracket6() { var code = @"public class C { Func<Func<int,int>$$> f; }"; var expected = @"public class C { Func<Func[|<|]int,int>> f; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestNestedAngleBracket7() { var code = @"public class C { Func<Func<int,int> $$> f; }"; var expected = @"public class C { Func[|<|]Func<int,int> > f; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestNestedAngleBracket8() { var code = @"public class C { Func<Func<int,int>>$$ f; }"; var expected = @"public class C { Func[|<|]Func<int,int>> f; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestString1() { var code = @"public class C { string s = $$""Goo""; }"; var expected = @"public class C { string s = ""Goo[|""|]; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestString2() { var code = @"public class C { string s = ""$$Goo""; }"; var expected = @"public class C { string s = ""Goo[|""|]; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestString3() { var code = @"public class C { string s = ""Goo$$""; }"; var expected = @"public class C { string s = [|""|]Goo""; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestString4() { var code = @"public class C { string s = ""Goo""$$; }"; var expected = @"public class C { string s = [|""|]Goo""; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestString5() { var code = @"public class C { string s = ""Goo$$ "; var expected = @"public class C { string s = ""Goo "; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestVerbatimString1() { var code = @"public class C { string s = $$@""Goo""; }"; var expected = @"public class C { string s = @""Goo[|""|]; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestVerbatimString2() { var code = @"public class C { string s = @$$""Goo""; }"; var expected = @"public class C { string s = @""Goo[|""|]; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestVerbatimString3() { var code = @"public class C { string s = @""$$Goo""; }"; var expected = @"public class C { string s = @""Goo[|""|]; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestVerbatimString4() { var code = @"public class C { string s = @""Goo$$""; }"; var expected = @"public class C { string s = [|@""|]Goo""; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestVerbatimString5() { var code = @"public class C { string s = @""Goo""$$; }"; var expected = @"public class C { string s = [|@""|]Goo""; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString1() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""$${x}, {y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x[|}|], {y}""; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString2() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{$$x}, {y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x[|}|], {y}""; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString3() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x$$}, {y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""[|{|]x}, {y}""; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString4() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}$$, {y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""[|{|]x}, {y}""; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString5() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, $${y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y[|}|]""; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString6() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {$$y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y[|}|]""; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString7() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y$$}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, [|{|]y}""; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString8() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y}$$""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, [|{|]y}""; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString9() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $$[||]$""{x}, {y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y}[|""|]; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString10() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $[||]$$""{x}, {y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y}[|""|]; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString11() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $$[||]$@""{x}, {y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $@""{x}, {y}[|""|]; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString12() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $[||]$$@""{x}, {y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $@""{x}, {y}[|""|]; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString13() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $@$$""{x}, {y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $@""{x}, {y}[|""|]; }"; await TestAsync(code, expected); } [WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestConditionalDirectiveWithSingleMatchingDirective() { var code = @" public class C { #if$$ CHK #endif }"; var expected = @" public class C { #if$$ CHK [|#endif|] }"; await TestAsync(code, expected); } [WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestConditionalDirectiveWithTwoMatchingDirectives() { var code = @" public class C { #if$$ CHK #else #endif }"; var expected = @" public class C { #if$$ CHK [|#else|] #endif }"; await TestAsync(code, expected); } [WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestConditionalDirectiveWithAllMatchingDirectives() { var code = @" public class C { #if CHK #elif RET #else #endif$$ }"; var expected = @" public class C { [|#if|] CHK #elif RET #else #endif }"; await TestAsync(code, expected); } [WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestRegionDirective() { var code = @" public class C { $$#region test #endregion }"; var expected = @" public class C { #region test [|#endregion|] }"; await TestAsync(code, expected); } [WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterleavedDirectivesInner() { var code = @" #define CHK public class C { void Test() { #if CHK $$#region test var x = 5; #endregion #else var y = 6; #endif } }"; var expected = @" #define CHK public class C { void Test() { #if CHK #region test var x = 5; [|#endregion|] #else var y = 6; #endif } }"; await TestAsync(code, expected); } [WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterleavedDirectivesOuter() { var code = @" #define CHK public class C { void Test() { #if$$ CHK #region test var x = 5; #endregion #else var y = 6; #endif } }"; var expected = @" #define CHK public class C { void Test() { #if CHK #region test var x = 5; #endregion [|#else|] var y = 6; #endif } }"; await TestAsync(code, expected); } [WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestUnmatchedDirective1() { var code = @" public class C { $$#region test }"; var expected = @" public class C { #region test }"; await TestAsync(code, expected); } [WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestUnmatchedDirective2() { var code = @" #d$$efine CHK public class C { }"; var expected = @" #define CHK public class C { }"; await TestAsync(code, expected); } [WorkItem(7534, "https://github.com/dotnet/roslyn/issues/7534")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestUnmatchedConditionalDirective() { var code = @" class Program { static void Main(string[] args) {#if$$ } }"; var expected = @" class Program { static void Main(string[] args) {#if } }"; await TestAsync(code, expected); } [WorkItem(7534, "https://github.com/dotnet/roslyn/issues/7534")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestUnmatchedConditionalDirective2() { var code = @" class Program { static void Main(string[] args) {#else$$ } }"; var expected = @" class Program { static void Main(string[] args) {#else } }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task StartTupleDeclaration() { var code = @"public class C { $$(int, int, int, int, int, int, int, int) x; }"; var expected = @"public class C { (int, int, int, int, int, int, int, int[|)|] x; }"; await TestAsync(code, expected, TestOptions.Regular); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task EndTupleDeclaration() { var code = @"public class C { (int, int, int, int, int, int, int, int)$$ x; }"; var expected = @"public class C { [|(|]int, int, int, int, int, int, int, int) x; }"; await TestAsync(code, expected, TestOptions.Regular); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task StartTupleLiteral() { var code = @"public class C { var x = $$(1, 2, 3, 4, 5, 6, 7, 8); }"; var expected = @"public class C { var x = (1, 2, 3, 4, 5, 6, 7, 8[|)|]; }"; await TestAsync(code, expected, TestOptions.Regular); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task EndTupleLiteral() { var code = @"public class C { var x = (1, 2, 3, 4, 5, 6, 7, 8)$$; }"; var expected = @"public class C { var x = [|(|]1, 2, 3, 4, 5, 6, 7, 8); }"; await TestAsync(code, expected, TestOptions.Regular); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task StartNestedTupleLiteral() { var code = @"public class C { var x = $$((1, 1, 1), 2, 3, 4, 5, 6, 7, 8); }"; var expected = @"public class C { var x = ((1, 1, 1), 2, 3, 4, 5, 6, 7, 8[|)|]; }"; await TestAsync(code, expected, TestOptions.Regular); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task StartInnerNestedTupleLiteral() { var code = @"public class C { var x = ($$(1, 1, 1), 2, 3, 4, 5, 6, 7, 8); }"; var expected = @"public class C { var x = ((1, 1, 1[|)|], 2, 3, 4, 5, 6, 7, 8); }"; await TestAsync(code, expected, TestOptions.Regular); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task EndNestedTupleLiteral() { var code = @"public class C { var x = (1, 2, 3, 4, 5, 6, 7, (8, 8, 8))$$; }"; var expected = @"public class C { var x = [|(|]1, 2, 3, 4, 5, 6, 7, (8, 8, 8)); }"; await TestAsync(code, expected, TestOptions.Regular); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task EndInnerNestedTupleLiteral() { var code = @"public class C { var x = ((1, 1, 1)$$, 2, 3, 4, 5, 6, 7, 8); }"; var expected = @"public class C { var x = ([|(|]1, 1, 1), 2, 3, 4, 5, 6, 7, 8); }"; await TestAsync(code, expected, TestOptions.Regular); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestFunctionPointer() { var code = @"public unsafe class C { delegate*<$$int, int> functionPointer; }"; var expected = @"public unsafe class C { delegate*<int, int[|>|] functionPointer; }"; await TestAsync(code, expected, TestOptions.Regular); } } }
// Licensed to the .NET Foundation under one or more 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.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.BraceMatching; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.BraceMatching { public class CSharpBraceMatcherTests : AbstractBraceMatcherTests { protected override TestWorkspace CreateWorkspaceFromCode(string code, ParseOptions options) => TestWorkspace.CreateCSharp(code, options); [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestEmptyFile() { var code = @"$$"; var expected = @""; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestAtFirstPositionInFile() { var code = @"$$public class C { }"; var expected = @"public class C { }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestAtLastPositionInFile() { var code = @"public class C { }$$"; var expected = @"public class C [|{|] }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestCurlyBrace1() { var code = @"public class C $${ }"; var expected = @"public class C { [|}|]"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestCurlyBrace2() { var code = @"public class C {$$ }"; var expected = @"public class C { [|}|]"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestCurlyBrace3() { var code = @"public class C { $$}"; var expected = @"public class C [|{|] }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestCurlyBrace4() { var code = @"public class C { }$$"; var expected = @"public class C [|{|] }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestParen1() { var code = @"public class C { void Goo$$() { } }"; var expected = @"public class C { void Goo([|)|] { } }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestParen2() { var code = @"public class C { void Goo($$) { } }"; var expected = @"public class C { void Goo([|)|] { } }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestParen3() { var code = @"public class C { void Goo($$ ) { } }"; var expected = @"public class C { void Goo( [|)|] { } }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestParen4() { var code = @"public class C { void Goo( $$) { } }"; var expected = @"public class C { void Goo[|(|] ) { } }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestParen5() { var code = @"public class C { void Goo( )$$ { } }"; var expected = @"public class C { void Goo[|(|] ) { } }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestParen6() { var code = @"public class C { void Goo()$$ { } }"; var expected = @"public class C { void Goo[|(|]) { } }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestSquareBracket1() { var code = @"public class C { int$$[] i; }"; var expected = @"public class C { int[[|]|] i; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestSquareBracket2() { var code = @"public class C { int[$$] i; }"; var expected = @"public class C { int[[|]|] i; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestSquareBracket3() { var code = @"public class C { int[$$ ] i; }"; var expected = @"public class C { int[ [|]|] i; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestSquareBracket4() { var code = @"public class C { int[ $$] i; }"; var expected = @"public class C { int[|[|] ] i; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestSquareBracket5() { var code = @"public class C { int[ ]$$ i; }"; var expected = @"public class C { int[|[|] ] i; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestSquareBracket6() { var code = @"public class C { int[]$$ i; }"; var expected = @"public class C { int[|[|]] i; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestAngleBracket1() { var code = @"public class C { Goo$$<int> f; }"; var expected = @"public class C { Goo<int[|>|] f; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestAngleBracket2() { var code = @"public class C { Goo<$$int> f; }"; var expected = @"public class C { Goo<int[|>|] f; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestAngleBracket3() { var code = @"public class C { Goo<int$$> f; }"; var expected = @"public class C { Goo[|<|]int> f; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestAngleBracket4() { var code = @"public class C { Goo<int>$$ f; }"; var expected = @"public class C { Goo[|<|]int> f; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestNestedAngleBracket1() { var code = @"public class C { Func$$<Func<int,int>> f; }"; var expected = @"public class C { Func<Func<int,int>[|>|] f; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestNestedAngleBracket2() { var code = @"public class C { Func<$$Func<int,int>> f; }"; var expected = @"public class C { Func<Func<int,int>[|>|] f; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestNestedAngleBracket3() { var code = @"public class C { Func<Func$$<int,int>> f; }"; var expected = @"public class C { Func<Func<int,int[|>|]> f; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestNestedAngleBracket4() { var code = @"public class C { Func<Func<$$int,int>> f; }"; var expected = @"public class C { Func<Func<int,int[|>|]> f; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestNestedAngleBracket5() { var code = @"public class C { Func<Func<int,int$$>> f; }"; var expected = @"public class C { Func<Func[|<|]int,int>> f; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestNestedAngleBracket6() { var code = @"public class C { Func<Func<int,int>$$> f; }"; var expected = @"public class C { Func<Func[|<|]int,int>> f; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestNestedAngleBracket7() { var code = @"public class C { Func<Func<int,int> $$> f; }"; var expected = @"public class C { Func[|<|]Func<int,int> > f; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestNestedAngleBracket8() { var code = @"public class C { Func<Func<int,int>>$$ f; }"; var expected = @"public class C { Func[|<|]Func<int,int>> f; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestString1() { var code = @"public class C { string s = $$""Goo""; }"; var expected = @"public class C { string s = ""Goo[|""|]; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestString2() { var code = @"public class C { string s = ""$$Goo""; }"; var expected = @"public class C { string s = ""Goo[|""|]; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestString3() { var code = @"public class C { string s = ""Goo$$""; }"; var expected = @"public class C { string s = [|""|]Goo""; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestString4() { var code = @"public class C { string s = ""Goo""$$; }"; var expected = @"public class C { string s = [|""|]Goo""; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestString5() { var code = @"public class C { string s = ""Goo$$ "; var expected = @"public class C { string s = ""Goo "; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestVerbatimString1() { var code = @"public class C { string s = $$@""Goo""; }"; var expected = @"public class C { string s = @""Goo[|""|]; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestVerbatimString2() { var code = @"public class C { string s = @$$""Goo""; }"; var expected = @"public class C { string s = @""Goo[|""|]; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestVerbatimString3() { var code = @"public class C { string s = @""$$Goo""; }"; var expected = @"public class C { string s = @""Goo[|""|]; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestVerbatimString4() { var code = @"public class C { string s = @""Goo$$""; }"; var expected = @"public class C { string s = [|@""|]Goo""; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestVerbatimString5() { var code = @"public class C { string s = @""Goo""$$; }"; var expected = @"public class C { string s = [|@""|]Goo""; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString1() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""$${x}, {y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x[|}|], {y}""; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString2() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{$$x}, {y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x[|}|], {y}""; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString3() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x$$}, {y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""[|{|]x}, {y}""; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString4() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}$$, {y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""[|{|]x}, {y}""; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString5() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, $${y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y[|}|]""; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString6() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {$$y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y[|}|]""; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString7() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y$$}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, [|{|]y}""; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString8() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y}$$""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, [|{|]y}""; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString9() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $$[||]$""{x}, {y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y}[|""|]; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString10() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $[||]$$""{x}, {y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y}[|""|]; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString11() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $$[||]$@""{x}, {y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $@""{x}, {y}[|""|]; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString12() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $[||]$$@""{x}, {y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $@""{x}, {y}[|""|]; }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString13() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $@$$""{x}, {y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $@""{x}, {y}[|""|]; }"; await TestAsync(code, expected); } [WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestConditionalDirectiveWithSingleMatchingDirective() { var code = @" public class C { #if$$ CHK #endif }"; var expected = @" public class C { #if$$ CHK [|#endif|] }"; await TestAsync(code, expected); } [WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestConditionalDirectiveWithTwoMatchingDirectives() { var code = @" public class C { #if$$ CHK #else #endif }"; var expected = @" public class C { #if$$ CHK [|#else|] #endif }"; await TestAsync(code, expected); } [WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestConditionalDirectiveWithAllMatchingDirectives() { var code = @" public class C { #if CHK #elif RET #else #endif$$ }"; var expected = @" public class C { [|#if|] CHK #elif RET #else #endif }"; await TestAsync(code, expected); } [WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestRegionDirective() { var code = @" public class C { $$#region test #endregion }"; var expected = @" public class C { #region test [|#endregion|] }"; await TestAsync(code, expected); } [WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterleavedDirectivesInner() { var code = @" #define CHK public class C { void Test() { #if CHK $$#region test var x = 5; #endregion #else var y = 6; #endif } }"; var expected = @" #define CHK public class C { void Test() { #if CHK #region test var x = 5; [|#endregion|] #else var y = 6; #endif } }"; await TestAsync(code, expected); } [WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterleavedDirectivesOuter() { var code = @" #define CHK public class C { void Test() { #if$$ CHK #region test var x = 5; #endregion #else var y = 6; #endif } }"; var expected = @" #define CHK public class C { void Test() { #if CHK #region test var x = 5; #endregion [|#else|] var y = 6; #endif } }"; await TestAsync(code, expected); } [WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestUnmatchedDirective1() { var code = @" public class C { $$#region test }"; var expected = @" public class C { #region test }"; await TestAsync(code, expected); } [WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestUnmatchedDirective2() { var code = @" #d$$efine CHK public class C { }"; var expected = @" #define CHK public class C { }"; await TestAsync(code, expected); } [WorkItem(7534, "https://github.com/dotnet/roslyn/issues/7534")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestUnmatchedConditionalDirective() { var code = @" class Program { static void Main(string[] args) {#if$$ } }"; var expected = @" class Program { static void Main(string[] args) {#if } }"; await TestAsync(code, expected); } [WorkItem(7534, "https://github.com/dotnet/roslyn/issues/7534")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestUnmatchedConditionalDirective2() { var code = @" class Program { static void Main(string[] args) {#else$$ } }"; var expected = @" class Program { static void Main(string[] args) {#else } }"; await TestAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task StartTupleDeclaration() { var code = @"public class C { $$(int, int, int, int, int, int, int, int) x; }"; var expected = @"public class C { (int, int, int, int, int, int, int, int[|)|] x; }"; await TestAsync(code, expected, TestOptions.Regular); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task EndTupleDeclaration() { var code = @"public class C { (int, int, int, int, int, int, int, int)$$ x; }"; var expected = @"public class C { [|(|]int, int, int, int, int, int, int, int) x; }"; await TestAsync(code, expected, TestOptions.Regular); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task StartTupleLiteral() { var code = @"public class C { var x = $$(1, 2, 3, 4, 5, 6, 7, 8); }"; var expected = @"public class C { var x = (1, 2, 3, 4, 5, 6, 7, 8[|)|]; }"; await TestAsync(code, expected, TestOptions.Regular); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task EndTupleLiteral() { var code = @"public class C { var x = (1, 2, 3, 4, 5, 6, 7, 8)$$; }"; var expected = @"public class C { var x = [|(|]1, 2, 3, 4, 5, 6, 7, 8); }"; await TestAsync(code, expected, TestOptions.Regular); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task StartNestedTupleLiteral() { var code = @"public class C { var x = $$((1, 1, 1), 2, 3, 4, 5, 6, 7, 8); }"; var expected = @"public class C { var x = ((1, 1, 1), 2, 3, 4, 5, 6, 7, 8[|)|]; }"; await TestAsync(code, expected, TestOptions.Regular); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task StartInnerNestedTupleLiteral() { var code = @"public class C { var x = ($$(1, 1, 1), 2, 3, 4, 5, 6, 7, 8); }"; var expected = @"public class C { var x = ((1, 1, 1[|)|], 2, 3, 4, 5, 6, 7, 8); }"; await TestAsync(code, expected, TestOptions.Regular); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task EndNestedTupleLiteral() { var code = @"public class C { var x = (1, 2, 3, 4, 5, 6, 7, (8, 8, 8))$$; }"; var expected = @"public class C { var x = [|(|]1, 2, 3, 4, 5, 6, 7, (8, 8, 8)); }"; await TestAsync(code, expected, TestOptions.Regular); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task EndInnerNestedTupleLiteral() { var code = @"public class C { var x = ((1, 1, 1)$$, 2, 3, 4, 5, 6, 7, 8); }"; var expected = @"public class C { var x = ([|(|]1, 1, 1), 2, 3, 4, 5, 6, 7, 8); }"; await TestAsync(code, expected, TestOptions.Regular); } [Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestFunctionPointer() { var code = @"public unsafe class C { delegate*<$$int, int> functionPointer; }"; var expected = @"public unsafe class C { delegate*<int, int[|>|] functionPointer; }"; await TestAsync(code, expected, TestOptions.Regular); } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/CSharpTest/CodeGeneration/SyntaxGeneratorTests.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 Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Editing { [UseExportProvider] public class SyntaxGeneratorTests { private readonly CSharpCompilation _emptyCompilation = CSharpCompilation.Create("empty", references: new[] { TestMetadata.Net451.mscorlib, TestMetadata.Net451.System }); private Workspace _workspace; private SyntaxGenerator _generator; public SyntaxGeneratorTests() { } private Workspace Workspace => _workspace ??= new AdhocWorkspace(); private SyntaxGenerator Generator => _generator ??= SyntaxGenerator.GetGenerator(Workspace, LanguageNames.CSharp); public static Compilation Compile(string code) { return CSharpCompilation.Create("test") .AddReferences(TestMetadata.Net451.mscorlib) .AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(code)); } private static void VerifySyntax<TSyntax>(SyntaxNode node, string expectedText) where TSyntax : SyntaxNode { Assert.IsAssignableFrom<TSyntax>(node); var normalized = node.NormalizeWhitespace().ToFullString(); Assert.Equal(expectedText, normalized); } private static void VerifySyntaxRaw<TSyntax>(SyntaxNode node, string expectedText) where TSyntax : SyntaxNode { Assert.IsAssignableFrom<TSyntax>(node); var normalized = node.ToFullString(); Assert.Equal(expectedText, normalized); } #region Expressions and Statements [Fact] public void TestLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1), "1"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1), "-1"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(int.MinValue), "global::System.Int32.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(int.MaxValue), "global::System.Int32.MaxValue"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0L), "0L"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1L), "1L"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1L), "-1L"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(long.MinValue), "global::System.Int64.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(long.MaxValue), "global::System.Int64.MaxValue"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0UL), "0UL"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1UL), "1UL"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(ulong.MinValue), "0UL"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(ulong.MaxValue), "global::System.UInt64.MaxValue"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.0f), "0F"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1.0f), "1F"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1.0f), "-1F"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.MinValue), "global::System.Single.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.MaxValue), "global::System.Single.MaxValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.Epsilon), "global::System.Single.Epsilon"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.NaN), "global::System.Single.NaN"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.NegativeInfinity), "global::System.Single.NegativeInfinity"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.PositiveInfinity), "global::System.Single.PositiveInfinity"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.0), "0D"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1.0), "1D"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1.0), "-1D"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.MinValue), "global::System.Double.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.MaxValue), "global::System.Double.MaxValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.Epsilon), "global::System.Double.Epsilon"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.NaN), "global::System.Double.NaN"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.NegativeInfinity), "global::System.Double.NegativeInfinity"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.PositiveInfinity), "global::System.Double.PositiveInfinity"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0m), "0M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.00m), "0.00M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1.00m), "1.00M"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1.00m), "-1.00M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1.0000000000m), "1.0000000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.000000m), "0.000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.0000000m), "0.0000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1000000000m), "1000000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(123456789.123456789m), "123456789.123456789M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1E-28m), "0.0000000000000000000000000001M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0E-28m), "0.0000000000000000000000000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1E-29m), "0.0000000000000000000000000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(-1E-29m), "0.0000000000000000000000000000M"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(decimal.MinValue), "global::System.Decimal.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(decimal.MaxValue), "global::System.Decimal.MaxValue"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression('c'), "'c'"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression("str"), "\"str\""); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression("s\"t\"r"), "\"s\\\"t\\\"r\""); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(true), "true"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(false), "false"); } [Fact] public void TestShortLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((short)0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((short)1), "1"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression((short)-1), "-1"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(short.MinValue), "global::System.Int16.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(short.MaxValue), "global::System.Int16.MaxValue"); } [Fact] public void TestUshortLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((ushort)0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((ushort)1), "1"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(ushort.MinValue), "0"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(ushort.MaxValue), "global::System.UInt16.MaxValue"); } [Fact] public void TestSbyteLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((sbyte)0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((sbyte)1), "1"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression((sbyte)-1), "-1"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(sbyte.MinValue), "global::System.SByte.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(sbyte.MaxValue), "global::System.SByte.MaxValue"); } [Fact] public void TestByteLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((byte)0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((byte)1), "1"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(byte.MinValue), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(byte.MaxValue), "255"); } [Fact] public void TestAttributeData() { VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { }", @"[MyAttribute]")), @"[global::MyAttribute]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(object value) { } }", @"[MyAttribute(null)]")), @"[global::MyAttribute(null)]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(int value) { } }", @"[MyAttribute(123)]")), @"[global::MyAttribute(123)]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(double value) { } }", @"[MyAttribute(12.3)]")), @"[global::MyAttribute(12.3)]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(string value) { } }", @"[MyAttribute(""value"")]")), @"[global::MyAttribute(""value"")]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public enum E { A, B, C } public class MyAttribute : Attribute { public MyAttribute(E value) { } }", @"[MyAttribute(E.A)]")), @"[global::MyAttribute(global::E.A)]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(Type value) { } }", @"[MyAttribute(typeof (MyAttribute))]")), @"[global::MyAttribute(typeof(global::MyAttribute))]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(int[] values) { } }", @"[MyAttribute(new [] {1, 2, 3})]")), @"[global::MyAttribute(new[]{1, 2, 3})]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public int Value {get; set;} }", @"[MyAttribute(Value = 123)]")), @"[global::MyAttribute(Value = 123)]"); var attributes = Generator.GetAttributes(Generator.AddAttributes( Generator.NamespaceDeclaration("n"), Generator.Attribute("Attr"))); Assert.True(attributes.Count == 1); } private static AttributeData GetAttributeData(string decl, string use) { var compilation = Compile(decl + "\r\n" + use + "\r\nclass C { }"); var typeC = compilation.GlobalNamespace.GetMembers("C").First() as INamedTypeSymbol; return typeC.GetAttributes().First(); } [Fact] public void TestNameExpressions() { VerifySyntax<IdentifierNameSyntax>(Generator.IdentifierName("x"), "x"); VerifySyntax<QualifiedNameSyntax>(Generator.QualifiedName(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x.y"); VerifySyntax<QualifiedNameSyntax>(Generator.DottedName("x.y"), "x.y"); VerifySyntax<GenericNameSyntax>(Generator.GenericName("x", Generator.IdentifierName("y")), "x<y>"); VerifySyntax<GenericNameSyntax>(Generator.GenericName("x", Generator.IdentifierName("y"), Generator.IdentifierName("z")), "x<y, z>"); // convert identifier name into generic name VerifySyntax<GenericNameSyntax>(Generator.WithTypeArguments(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x<y>"); // convert qualified name into qualified generic name VerifySyntax<QualifiedNameSyntax>(Generator.WithTypeArguments(Generator.DottedName("x.y"), Generator.IdentifierName("z")), "x.y<z>"); // convert member access expression into generic member access expression VerifySyntax<MemberAccessExpressionSyntax>(Generator.WithTypeArguments(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x.y<z>"); // convert existing generic name into a different generic name var gname = Generator.WithTypeArguments(Generator.IdentifierName("x"), Generator.IdentifierName("y")); VerifySyntax<GenericNameSyntax>(gname, "x<y>"); VerifySyntax<GenericNameSyntax>(Generator.WithTypeArguments(gname, Generator.IdentifierName("z")), "x<z>"); } [Fact] public void TestTypeExpressions() { // these are all type syntax too VerifySyntax<TypeSyntax>(Generator.IdentifierName("x"), "x"); VerifySyntax<TypeSyntax>(Generator.QualifiedName(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x.y"); VerifySyntax<TypeSyntax>(Generator.DottedName("x.y"), "x.y"); VerifySyntax<TypeSyntax>(Generator.GenericName("x", Generator.IdentifierName("y")), "x<y>"); VerifySyntax<TypeSyntax>(Generator.GenericName("x", Generator.IdentifierName("y"), Generator.IdentifierName("z")), "x<y, z>"); VerifySyntax<TypeSyntax>(Generator.ArrayTypeExpression(Generator.IdentifierName("x")), "x[]"); VerifySyntax<TypeSyntax>(Generator.ArrayTypeExpression(Generator.ArrayTypeExpression(Generator.IdentifierName("x"))), "x[][]"); VerifySyntax<TypeSyntax>(Generator.NullableTypeExpression(Generator.IdentifierName("x")), "x?"); VerifySyntax<TypeSyntax>(Generator.NullableTypeExpression(Generator.NullableTypeExpression(Generator.IdentifierName("x"))), "x?"); var intType = _emptyCompilation.GetSpecialType(SpecialType.System_Int32); VerifySyntax<TupleElementSyntax>(Generator.TupleElementExpression(Generator.IdentifierName("x")), "x"); VerifySyntax<TupleElementSyntax>(Generator.TupleElementExpression(Generator.IdentifierName("x"), "y"), "x y"); VerifySyntax<TupleElementSyntax>(Generator.TupleElementExpression(intType), "global::System.Int32"); VerifySyntax<TupleElementSyntax>(Generator.TupleElementExpression(intType, "y"), "global::System.Int32 y"); VerifySyntax<TypeSyntax>(Generator.TupleTypeExpression(Generator.TupleElementExpression(Generator.IdentifierName("x")), Generator.TupleElementExpression(Generator.IdentifierName("y"))), "(x, y)"); VerifySyntax<TypeSyntax>(Generator.TupleTypeExpression(new[] { intType, intType }), "(global::System.Int32, global::System.Int32)"); VerifySyntax<TypeSyntax>(Generator.TupleTypeExpression(new[] { intType, intType }, new[] { "x", "y" }), "(global::System.Int32 x, global::System.Int32 y)"); } [Fact] public void TestSpecialTypeExpression() { VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Byte), "byte"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_SByte), "sbyte"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Int16), "short"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_UInt16), "ushort"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Int32), "int"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_UInt32), "uint"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Int64), "long"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_UInt64), "ulong"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Single), "float"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Double), "double"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Char), "char"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_String), "string"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Object), "object"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Decimal), "decimal"); } [Fact] public void TestSymbolTypeExpressions() { var genericType = _emptyCompilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T); VerifySyntax<QualifiedNameSyntax>(Generator.TypeExpression(genericType), "global::System.Collections.Generic.IEnumerable<T>"); var arrayType = _emptyCompilation.CreateArrayTypeSymbol(_emptyCompilation.GetSpecialType(SpecialType.System_Int32)); VerifySyntax<ArrayTypeSyntax>(Generator.TypeExpression(arrayType), "global::System.Int32[]"); } [Fact] public void TestMathAndLogicExpressions() { VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.NegateExpression(Generator.IdentifierName("x")), "-(x)"); VerifySyntax<BinaryExpressionSyntax>(Generator.AddExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) + (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.SubtractExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) - (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.MultiplyExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) * (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.DivideExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) / (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.ModuloExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) % (y)"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.BitwiseNotExpression(Generator.IdentifierName("x")), "~(x)"); VerifySyntax<BinaryExpressionSyntax>(Generator.BitwiseAndExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) & (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.BitwiseOrExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) | (y)"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LogicalNotExpression(Generator.IdentifierName("x")), "!(x)"); VerifySyntax<BinaryExpressionSyntax>(Generator.LogicalAndExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) && (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.LogicalOrExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) || (y)"); } [Fact] public void TestEqualityAndInequalityExpressions() { VerifySyntax<BinaryExpressionSyntax>(Generator.ReferenceEqualsExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) == (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.ValueEqualsExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) == (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.ReferenceNotEqualsExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) != (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.ValueNotEqualsExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) != (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.LessThanExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) < (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.LessThanOrEqualExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) <= (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.GreaterThanExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) > (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.GreaterThanOrEqualExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) >= (y)"); } [Fact] public void TestConditionalExpressions() { VerifySyntax<BinaryExpressionSyntax>(Generator.CoalesceExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) ?? (y)"); VerifySyntax<ConditionalExpressionSyntax>(Generator.ConditionalExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"), Generator.IdentifierName("z")), "(x) ? (y) : (z)"); } [Fact] public void TestMemberAccessExpressions() { VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x.y"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.IdentifierName("x"), "y"), "x.y"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x.y.z"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x(y).z"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x[y].z"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.AddExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "((x) + (y)).z"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.NegateExpression(Generator.IdentifierName("x")), Generator.IdentifierName("y")), "(-(x)).y"); } [Fact] public void TestArrayCreationExpressions() { VerifySyntax<ArrayCreationExpressionSyntax>( Generator.ArrayCreationExpression(Generator.IdentifierName("x"), Generator.LiteralExpression(10)), "new x[10]"); VerifySyntax<ArrayCreationExpressionSyntax>( Generator.ArrayCreationExpression(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y"), Generator.IdentifierName("z") }), "new x[]{y, z}"); } [Fact] public void TestObjectCreationExpressions() { VerifySyntax<ObjectCreationExpressionSyntax>( Generator.ObjectCreationExpression(Generator.IdentifierName("x")), "new x()"); VerifySyntax<ObjectCreationExpressionSyntax>( Generator.ObjectCreationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "new x(y)"); var intType = _emptyCompilation.GetSpecialType(SpecialType.System_Int32); var listType = _emptyCompilation.GetTypeByMetadataName("System.Collections.Generic.List`1"); var listOfIntType = listType.Construct(intType); VerifySyntax<ObjectCreationExpressionSyntax>( Generator.ObjectCreationExpression(listOfIntType, Generator.IdentifierName("y")), "new global::System.Collections.Generic.List<global::System.Int32>(y)"); // should this be 'int' or if not shouldn't it have global::? } [Fact] public void TestElementAccessExpressions() { VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x[y]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"), Generator.IdentifierName("z")), "x[y, z]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x.y[z]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x[y][z]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x(y)[z]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.AddExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "((x) + (y))[z]"); } [Fact] public void TestCastAndConvertExpressions() { VerifySyntax<CastExpressionSyntax>(Generator.CastExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x)(y)"); VerifySyntax<CastExpressionSyntax>(Generator.ConvertExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x)(y)"); } [Fact] public void TestIsAndAsExpressions() { VerifySyntax<BinaryExpressionSyntax>(Generator.IsTypeExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) is y"); VerifySyntax<BinaryExpressionSyntax>(Generator.TryCastExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) as y"); VerifySyntax<TypeOfExpressionSyntax>(Generator.TypeOfExpression(Generator.IdentifierName("x")), "typeof(x)"); } [Fact] public void TestInvocationExpressions() { // without explicit arguments VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x")), "x()"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x(y)"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"), Generator.IdentifierName("z")), "x(y, z)"); // using explicit arguments VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.Argument(Generator.IdentifierName("y"))), "x(y)"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.Argument(RefKind.Ref, Generator.IdentifierName("y"))), "x(ref y)"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.Argument(RefKind.Out, Generator.IdentifierName("y"))), "x(out y)"); // auto parenthesizing VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), "x.y()"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), "x[y]()"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), "x(y)()"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.AddExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), "((x) + (y))()"); } [Fact] public void TestAssignmentStatement() => VerifySyntax<AssignmentExpressionSyntax>(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x = (y)"); [Fact] public void TestExpressionStatement() { VerifySyntax<ExpressionStatementSyntax>(Generator.ExpressionStatement(Generator.IdentifierName("x")), "x;"); VerifySyntax<ExpressionStatementSyntax>(Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("x"))), "x();"); } [Fact] public void TestLocalDeclarationStatements() { VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "y"), "x y;"); VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "y", Generator.IdentifierName("z")), "x y = z;"); VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "y", isConst: true), "const x y;"); VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "y", Generator.IdentifierName("z"), isConst: true), "const x y = z;"); VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement("y", Generator.IdentifierName("z")), "var y = z;"); } [Fact] public void TestAddHandlerExpressions() { VerifySyntax<AssignmentExpressionSyntax>( Generator.AddEventHandler(Generator.IdentifierName("@event"), Generator.IdentifierName("handler")), "@event += (handler)"); } [Fact] public void TestSubtractHandlerExpressions() { VerifySyntax<AssignmentExpressionSyntax>( Generator.RemoveEventHandler(Generator.IdentifierName("@event"), Generator.IdentifierName("handler")), "@event -= (handler)"); } [Fact] public void TestAwaitExpressions() => VerifySyntax<AwaitExpressionSyntax>(Generator.AwaitExpression(Generator.IdentifierName("x")), "await x"); [Fact] public void TestNameOfExpressions() => VerifySyntax<InvocationExpressionSyntax>(Generator.NameOfExpression(Generator.IdentifierName("x")), "nameof(x)"); [Fact] public void TestTupleExpression() { VerifySyntax<TupleExpressionSyntax>(Generator.TupleExpression( new[] { Generator.IdentifierName("x"), Generator.IdentifierName("y") }), "(x, y)"); VerifySyntax<TupleExpressionSyntax>(Generator.TupleExpression( new[] { Generator.Argument("goo", RefKind.None, Generator.IdentifierName("x")), Generator.Argument("bar", RefKind.None, Generator.IdentifierName("y")) }), "(goo: x, bar: y)"); } [Fact] public void TestReturnStatements() { VerifySyntax<ReturnStatementSyntax>(Generator.ReturnStatement(), "return;"); VerifySyntax<ReturnStatementSyntax>(Generator.ReturnStatement(Generator.IdentifierName("x")), "return x;"); } [Fact] public void TestYieldReturnStatements() { VerifySyntax<YieldStatementSyntax>(Generator.YieldReturnStatement(Generator.LiteralExpression(1)), "yield return 1;"); VerifySyntax<YieldStatementSyntax>(Generator.YieldReturnStatement(Generator.IdentifierName("x")), "yield return x;"); } [Fact] public void TestThrowStatements() { VerifySyntax<ThrowStatementSyntax>(Generator.ThrowStatement(), "throw;"); VerifySyntax<ThrowStatementSyntax>(Generator.ThrowStatement(Generator.IdentifierName("x")), "throw x;"); } [Fact] public void TestIfStatements() { VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { }), "if (x)\r\n{\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { }, new SyntaxNode[] { }), "if (x)\r\n{\r\n}\r\nelse\r\n{\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y") }), "if (x)\r\n{\r\n y;\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y") }, new SyntaxNode[] { Generator.IdentifierName("z") }), "if (x)\r\n{\r\n y;\r\n}\r\nelse\r\n{\r\n z;\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y") }, Generator.IfStatement(Generator.IdentifierName("p"), new SyntaxNode[] { Generator.IdentifierName("q") })), "if (x)\r\n{\r\n y;\r\n}\r\nelse if (p)\r\n{\r\n q;\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y") }, Generator.IfStatement(Generator.IdentifierName("p"), new SyntaxNode[] { Generator.IdentifierName("q") }, Generator.IdentifierName("z"))), "if (x)\r\n{\r\n y;\r\n}\r\nelse if (p)\r\n{\r\n q;\r\n}\r\nelse\r\n{\r\n z;\r\n}"); } [Fact] public void TestSwitchStatements() { VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") })), "switch (x)\r\n{\r\n case y:\r\n z;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection( new[] { Generator.IdentifierName("y"), Generator.IdentifierName("p"), Generator.IdentifierName("q") }, new[] { Generator.IdentifierName("z") })), "switch (x)\r\n{\r\n case y:\r\n case p:\r\n case q:\r\n z;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") }), Generator.SwitchSection(Generator.IdentifierName("a"), new[] { Generator.IdentifierName("b") })), "switch (x)\r\n{\r\n case y:\r\n z;\r\n case a:\r\n b;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") }), Generator.DefaultSwitchSection( new[] { Generator.IdentifierName("b") })), "switch (x)\r\n{\r\n case y:\r\n z;\r\n default:\r\n b;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.ExitSwitchStatement() })), "switch (x)\r\n{\r\n case y:\r\n break;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.TupleExpression(new[] { Generator.IdentifierName("x1"), Generator.IdentifierName("x2") }), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") })), "switch (x1, x2)\r\n{\r\n case y:\r\n z;\r\n}"); } [Fact] public void TestUsingStatements() { VerifySyntax<UsingStatementSyntax>( Generator.UsingStatement(Generator.IdentifierName("x"), new[] { Generator.IdentifierName("y") }), "using (x)\r\n{\r\n y;\r\n}"); VerifySyntax<UsingStatementSyntax>( Generator.UsingStatement("x", Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") }), "using (var x = y)\r\n{\r\n z;\r\n}"); VerifySyntax<UsingStatementSyntax>( Generator.UsingStatement(Generator.IdentifierName("x"), "y", Generator.IdentifierName("z"), new[] { Generator.IdentifierName("q") }), "using (x y = z)\r\n{\r\n q;\r\n}"); } [Fact] public void TestLockStatements() { VerifySyntax<LockStatementSyntax>( Generator.LockStatement(Generator.IdentifierName("x"), new[] { Generator.IdentifierName("y") }), "lock (x)\r\n{\r\n y;\r\n}"); } [Fact] public void TestTryCatchStatements() { VerifySyntax<TryStatementSyntax>( Generator.TryCatchStatement( new[] { Generator.IdentifierName("x") }, Generator.CatchClause(Generator.IdentifierName("y"), "z", new[] { Generator.IdentifierName("a") })), "try\r\n{\r\n x;\r\n}\r\ncatch (y z)\r\n{\r\n a;\r\n}"); VerifySyntax<TryStatementSyntax>( Generator.TryCatchStatement( new[] { Generator.IdentifierName("s") }, Generator.CatchClause(Generator.IdentifierName("x"), "y", new[] { Generator.IdentifierName("z") }), Generator.CatchClause(Generator.IdentifierName("a"), "b", new[] { Generator.IdentifierName("c") })), "try\r\n{\r\n s;\r\n}\r\ncatch (x y)\r\n{\r\n z;\r\n}\r\ncatch (a b)\r\n{\r\n c;\r\n}"); VerifySyntax<TryStatementSyntax>( Generator.TryCatchStatement( new[] { Generator.IdentifierName("s") }, new[] { Generator.CatchClause(Generator.IdentifierName("x"), "y", new[] { Generator.IdentifierName("z") }) }, new[] { Generator.IdentifierName("a") }), "try\r\n{\r\n s;\r\n}\r\ncatch (x y)\r\n{\r\n z;\r\n}\r\nfinally\r\n{\r\n a;\r\n}"); VerifySyntax<TryStatementSyntax>( Generator.TryFinallyStatement( new[] { Generator.IdentifierName("x") }, new[] { Generator.IdentifierName("a") }), "try\r\n{\r\n x;\r\n}\r\nfinally\r\n{\r\n a;\r\n}"); } [Fact] public void TestWhileStatements() { VerifySyntax<WhileStatementSyntax>( Generator.WhileStatement(Generator.IdentifierName("x"), new[] { Generator.IdentifierName("y") }), "while (x)\r\n{\r\n y;\r\n}"); VerifySyntax<WhileStatementSyntax>( Generator.WhileStatement(Generator.IdentifierName("x"), null), "while (x)\r\n{\r\n}"); } [Fact] public void TestLambdaExpressions() { VerifySyntax<SimpleLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression("x", Generator.IdentifierName("y")), "x => y"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new[] { Generator.LambdaParameter("x"), Generator.LambdaParameter("y") }, Generator.IdentifierName("z")), "(x, y) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new SyntaxNode[] { }, Generator.IdentifierName("y")), "() => y"); VerifySyntax<SimpleLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression("x", Generator.IdentifierName("y")), "x => y"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new[] { Generator.LambdaParameter("x"), Generator.LambdaParameter("y") }, Generator.IdentifierName("z")), "(x, y) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new SyntaxNode[] { }, Generator.IdentifierName("y")), "() => y"); VerifySyntax<SimpleLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression("x", new[] { Generator.ReturnStatement(Generator.IdentifierName("y")) }), "x =>\r\n{\r\n return y;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new[] { Generator.LambdaParameter("x"), Generator.LambdaParameter("y") }, new[] { Generator.ReturnStatement(Generator.IdentifierName("z")) }), "(x, y) =>\r\n{\r\n return z;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new SyntaxNode[] { }, new[] { Generator.ReturnStatement(Generator.IdentifierName("y")) }), "() =>\r\n{\r\n return y;\r\n}"); VerifySyntax<SimpleLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression("x", new[] { Generator.IdentifierName("y") }), "x =>\r\n{\r\n y;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new[] { Generator.LambdaParameter("x"), Generator.LambdaParameter("y") }, new[] { Generator.IdentifierName("z") }), "(x, y) =>\r\n{\r\n z;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new SyntaxNode[] { }, new[] { Generator.IdentifierName("y") }), "() =>\r\n{\r\n y;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new[] { Generator.LambdaParameter("x", Generator.IdentifierName("y")) }, Generator.IdentifierName("z")), "(y x) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new[] { Generator.LambdaParameter("x", Generator.IdentifierName("y")), Generator.LambdaParameter("a", Generator.IdentifierName("b")) }, Generator.IdentifierName("z")), "(y x, b a) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new[] { Generator.LambdaParameter("x", Generator.IdentifierName("y")) }, Generator.IdentifierName("z")), "(y x) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new[] { Generator.LambdaParameter("x", Generator.IdentifierName("y")), Generator.LambdaParameter("a", Generator.IdentifierName("b")) }, Generator.IdentifierName("z")), "(y x, b a) => z"); } #endregion #region Declarations [Fact] public void TestFieldDeclarations() { VerifySyntax<FieldDeclarationSyntax>( Generator.FieldDeclaration("fld", Generator.TypeExpression(SpecialType.System_Int32)), "int fld;"); VerifySyntax<FieldDeclarationSyntax>( Generator.FieldDeclaration("fld", Generator.TypeExpression(SpecialType.System_Int32), initializer: Generator.LiteralExpression(0)), "int fld = 0;"); VerifySyntax<FieldDeclarationSyntax>( Generator.FieldDeclaration("fld", Generator.TypeExpression(SpecialType.System_Int32), accessibility: Accessibility.Public), "public int fld;"); VerifySyntax<FieldDeclarationSyntax>( Generator.FieldDeclaration("fld", Generator.TypeExpression(SpecialType.System_Int32), accessibility: Accessibility.NotApplicable, modifiers: DeclarationModifiers.Static | DeclarationModifiers.ReadOnly), "static readonly int fld;"); } [Fact] public void TestMethodDeclarations() { VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m"), "void m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", typeParameters: new[] { "x", "y" }), "void m<x, y>()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x")), "x m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x"), statements: new[] { Generator.IdentifierName("y") }), "x m()\r\n{\r\n y;\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", parameters: new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, returnType: Generator.IdentifierName("x")), "x m(y z)\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", parameters: new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y"), Generator.IdentifierName("a")) }, returnType: Generator.IdentifierName("x")), "x m(y z = a)\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x"), accessibility: Accessibility.Public), "public x m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Abstract), "public abstract x m();"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Partial), "partial void m();"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Partial, statements: new[] { Generator.IdentifierName("y") }), "partial void m()\r\n{\r\n y;\r\n}"); } [Fact] public void TestOperatorDeclaration() { var parameterTypes = new[] { _emptyCompilation.GetSpecialType(SpecialType.System_Int32), _emptyCompilation.GetSpecialType(SpecialType.System_String) }; var parameters = parameterTypes.Select((t, i) => Generator.ParameterDeclaration("p" + i, Generator.TypeExpression(t))).ToList(); var returnType = Generator.TypeExpression(SpecialType.System_Boolean); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Addition, parameters, returnType), "bool operator +(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.BitwiseAnd, parameters, returnType), "bool operator &(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.BitwiseOr, parameters, returnType), "bool operator |(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Decrement, parameters, returnType), "bool operator --(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Division, parameters, returnType), "bool operator /(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Equality, parameters, returnType), "bool operator ==(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.ExclusiveOr, parameters, returnType), "bool operator ^(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.False, parameters, returnType), "bool operator false (global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.GreaterThan, parameters, returnType), "bool operator>(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.GreaterThanOrEqual, parameters, returnType), "bool operator >=(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Increment, parameters, returnType), "bool operator ++(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Inequality, parameters, returnType), "bool operator !=(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.LeftShift, parameters, returnType), "bool operator <<(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.LessThan, parameters, returnType), "bool operator <(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.LessThanOrEqual, parameters, returnType), "bool operator <=(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.LogicalNot, parameters, returnType), "bool operator !(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Modulus, parameters, returnType), "bool operator %(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Multiply, parameters, returnType), "bool operator *(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.OnesComplement, parameters, returnType), "bool operator ~(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.RightShift, parameters, returnType), "bool operator >>(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Subtraction, parameters, returnType), "bool operator -(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.True, parameters, returnType), "bool operator true (global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.UnaryNegation, parameters, returnType), "bool operator -(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.UnaryPlus, parameters, returnType), "bool operator +(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); // Conversion operators VerifySyntax<ConversionOperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.ImplicitConversion, parameters, returnType), "implicit operator bool (global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<ConversionOperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.ExplicitConversion, parameters, returnType), "explicit operator bool (global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); } [Fact] public void TestConstructorDeclaration() { VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration(), "ctor()\r\n{\r\n}"); VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration("c"), "c()\r\n{\r\n}"); VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration("c", accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Static), "public static c()\r\n{\r\n}"); VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration("c", new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }), "c(t p)\r\n{\r\n}"); VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration("c", parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, baseConstructorArguments: new[] { Generator.IdentifierName("p") }), "c(t p) : base(p)\r\n{\r\n}"); } [Fact] public void TestPropertyDeclarations() { VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract | DeclarationModifiers.ReadOnly), "abstract x p { get; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract | DeclarationModifiers.WriteOnly), "abstract x p { set; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly), "x p { get; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly, getAccessorStatements: Array.Empty<SyntaxNode>()), "x p\r\n{\r\n get\r\n {\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly), "x p { set; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly, setAccessorStatements: Array.Empty<SyntaxNode>()), "x p\r\n{\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract), "abstract x p { get; set; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly, getAccessorStatements: new[] { Generator.IdentifierName("y") }), "x p\r\n{\r\n get\r\n {\r\n y;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly, setAccessorStatements: new[] { Generator.IdentifierName("y") }), "x p\r\n{\r\n set\r\n {\r\n y;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), setAccessorStatements: new[] { Generator.IdentifierName("y") }), "x p\r\n{\r\n get;\r\n set\r\n {\r\n y;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), getAccessorStatements: Array.Empty<SyntaxNode>(), setAccessorStatements: new[] { Generator.IdentifierName("y") }), "x p\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n y;\r\n }\r\n}"); } [Fact] public void TestIndexerDeclarations() { VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract | DeclarationModifiers.ReadOnly), "abstract x this[y z] { get; }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract | DeclarationModifiers.WriteOnly), "abstract x this[y z] { set; }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract), "abstract x this[y z] { get; set; }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly), "x this[y z]\r\n{\r\n get\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly), "x this[y z]\r\n{\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly, getAccessorStatements: new[] { Generator.IdentifierName("a") }), "x this[y z]\r\n{\r\n get\r\n {\r\n a;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly, setAccessorStatements: new[] { Generator.IdentifierName("a") }), "x this[y z]\r\n{\r\n set\r\n {\r\n a;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x")), "x this[y z]\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), setAccessorStatements: new[] { Generator.IdentifierName("a") }), "x this[y z]\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n a;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), getAccessorStatements: new[] { Generator.IdentifierName("a") }, setAccessorStatements: new[] { Generator.IdentifierName("b") }), "x this[y z]\r\n{\r\n get\r\n {\r\n a;\r\n }\r\n\r\n set\r\n {\r\n b;\r\n }\r\n}"); } [Fact] public void TestEventFieldDeclarations() { VerifySyntax<EventFieldDeclarationSyntax>( Generator.EventDeclaration("ef", Generator.IdentifierName("t")), "event t ef;"); VerifySyntax<EventFieldDeclarationSyntax>( Generator.EventDeclaration("ef", Generator.IdentifierName("t"), accessibility: Accessibility.Public), "public event t ef;"); VerifySyntax<EventFieldDeclarationSyntax>( Generator.EventDeclaration("ef", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Static), "static event t ef;"); } [Fact] public void TestEventPropertyDeclarations() { VerifySyntax<EventDeclarationSyntax>( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), "abstract event t ep { add; remove; }"); VerifySyntax<EventDeclarationSyntax>( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Abstract), "public abstract event t ep { add; remove; }"); VerifySyntax<EventDeclarationSyntax>( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t")), "event t ep\r\n{\r\n add\r\n {\r\n }\r\n\r\n remove\r\n {\r\n }\r\n}"); VerifySyntax<EventDeclarationSyntax>( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), addAccessorStatements: new[] { Generator.IdentifierName("s") }, removeAccessorStatements: new[] { Generator.IdentifierName("s2") }), "event t ep\r\n{\r\n add\r\n {\r\n s;\r\n }\r\n\r\n remove\r\n {\r\n s2;\r\n }\r\n}"); } [Fact] public void TestAsPublicInterfaceImplementation() { VerifySyntax<MethodDeclarationSyntax>( Generator.AsPublicInterfaceImplementation( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "public t m()\r\n{\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.AsPublicInterfaceImplementation( Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Private, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "public t p\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.AsPublicInterfaceImplementation( Generator.IndexerDeclaration(parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("a")) }, type: Generator.IdentifierName("t"), accessibility: Accessibility.Internal, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "public t this[a p]\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); // convert private to public var pim = Generator.AsPrivateInterfaceImplementation( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), accessibility: Accessibility.Private, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")); VerifySyntax<MethodDeclarationSyntax>( Generator.AsPublicInterfaceImplementation(pim, Generator.IdentifierName("i2")), "public t m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.AsPublicInterfaceImplementation(pim, Generator.IdentifierName("i2"), "m2"), "public t m2()\r\n{\r\n}"); } [Fact] public void TestAsPrivateInterfaceImplementation() { VerifySyntax<MethodDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), accessibility: Accessibility.Private, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "t i.m()\r\n{\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation( Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Internal, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "t i.p\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation( Generator.IndexerDeclaration(parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("a")) }, type: Generator.IdentifierName("t"), accessibility: Accessibility.Protected, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "t i.this[a p]\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<EventDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "event t i.ep\r\n{\r\n add\r\n {\r\n }\r\n\r\n remove\r\n {\r\n }\r\n}"); // convert public to private var pim = Generator.AsPublicInterfaceImplementation( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), accessibility: Accessibility.Private, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")); VerifySyntax<MethodDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation(pim, Generator.IdentifierName("i2")), "t i2.m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation(pim, Generator.IdentifierName("i2"), "m2"), "t i2.m2()\r\n{\r\n}"); } [WorkItem(3928, "https://github.com/dotnet/roslyn/issues/3928")] [Fact] public void TestAsPrivateInterfaceImplementationRemovesConstraints() { var code = @" public interface IFace { void Method<T>() where T : class; }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var iface = cu.Members[0]; var method = Generator.GetMembers(iface)[0]; var privateMethod = Generator.AsPrivateInterfaceImplementation(method, Generator.IdentifierName("IFace")); VerifySyntax<MethodDeclarationSyntax>( privateMethod, "void IFace.Method<T>()\r\n{\r\n}"); } [Fact] public void TestClassDeclarations() { VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c"), "class c\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", typeParameters: new[] { "x", "y" }), "class c<x, y>\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", baseType: Generator.IdentifierName("x")), "class c : x\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", interfaceTypes: new[] { Generator.IdentifierName("x") }), "class c : x\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", baseType: Generator.IdentifierName("x"), interfaceTypes: new[] { Generator.IdentifierName("y") }), "class c : x, y\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", interfaceTypes: new SyntaxNode[] { }), "class c\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", members: new[] { Generator.FieldDeclaration("y", type: Generator.IdentifierName("x")) }), "class c\r\n{\r\n x y;\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", members: new[] { Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t")) }), "class c\r\n{\r\n t m()\r\n {\r\n }\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", members: new[] { Generator.ConstructorDeclaration() }), "class c\r\n{\r\n c()\r\n {\r\n }\r\n}"); } [Fact] public void TestStructDeclarations() { VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s"), "struct s\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", typeParameters: new[] { "x", "y" }), "struct s<x, y>\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", interfaceTypes: new[] { Generator.IdentifierName("x") }), "struct s : x\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", interfaceTypes: new[] { Generator.IdentifierName("x"), Generator.IdentifierName("y") }), "struct s : x, y\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", interfaceTypes: new SyntaxNode[] { }), "struct s\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", members: new[] { Generator.FieldDeclaration("y", Generator.IdentifierName("x")) }), "struct s\r\n{\r\n x y;\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t")) }), "struct s\r\n{\r\n t m()\r\n {\r\n }\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", members: new[] { Generator.ConstructorDeclaration("xxx") }), "struct s\r\n{\r\n s()\r\n {\r\n }\r\n}"); } [Fact] public void TestInterfaceDeclarations() { VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i"), "interface i\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", typeParameters: new[] { "x", "y" }), "interface i<x, y>\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", interfaceTypes: new[] { Generator.IdentifierName("a") }), "interface i : a\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", interfaceTypes: new[] { Generator.IdentifierName("a"), Generator.IdentifierName("b") }), "interface i : a, b\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", interfaceTypes: new SyntaxNode[] { }), "interface i\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Sealed) }), "interface i\r\n{\r\n t m();\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Sealed) }), "interface i\r\n{\r\n t p { get; set; }\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.ReadOnly) }), "interface i\r\n{\r\n t p { get; }\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("y", Generator.IdentifierName("x")) }, Generator.IdentifierName("t"), Accessibility.Public, DeclarationModifiers.Sealed) }), "interface i\r\n{\r\n t this[x y] { get; set; }\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("y", Generator.IdentifierName("x")) }, Generator.IdentifierName("t"), Accessibility.Public, DeclarationModifiers.ReadOnly) }), "interface i\r\n{\r\n t this[x y] { get; }\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Static) }), "interface i\r\n{\r\n event t ep;\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.EventDeclaration("ef", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Static) }), "interface i\r\n{\r\n event t ef;\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.FieldDeclaration("f", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Sealed) }), "interface i\r\n{\r\n t f { get; set; }\r\n}"); } [Fact] public void TestEnumDeclarations() { VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e"), "enum e\r\n{\r\n}"); VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e", members: new[] { Generator.EnumMember("a"), Generator.EnumMember("b"), Generator.EnumMember("c") }), "enum e\r\n{\r\n a,\r\n b,\r\n c\r\n}"); VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e", members: new[] { Generator.IdentifierName("a"), Generator.EnumMember("b"), Generator.IdentifierName("c") }), "enum e\r\n{\r\n a,\r\n b,\r\n c\r\n}"); VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e", members: new[] { Generator.EnumMember("a", Generator.LiteralExpression(0)), Generator.EnumMember("b"), Generator.EnumMember("c", Generator.LiteralExpression(5)) }), "enum e\r\n{\r\n a = 0,\r\n b,\r\n c = 5\r\n}"); VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e", members: new[] { Generator.FieldDeclaration("a", Generator.IdentifierName("e"), initializer: Generator.LiteralExpression(1)) }), "enum e\r\n{\r\n a = 1\r\n}"); } [Fact] public void TestDelegateDeclarations() { VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d"), "delegate void d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", returnType: Generator.IdentifierName("t")), "delegate t d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", returnType: Generator.IdentifierName("t"), parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("pt")) }), "delegate t d(pt p);"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", accessibility: Accessibility.Public), "public delegate void d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", accessibility: Accessibility.Public), "public delegate void d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", modifiers: DeclarationModifiers.New), "new delegate void d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", typeParameters: new[] { "T", "S" }), "delegate void d<T, S>();"); } [Fact] public void TestNamespaceImportDeclarations() { VerifySyntax<UsingDirectiveSyntax>( Generator.NamespaceImportDeclaration(Generator.IdentifierName("n")), "using n;"); VerifySyntax<UsingDirectiveSyntax>( Generator.NamespaceImportDeclaration("n"), "using n;"); VerifySyntax<UsingDirectiveSyntax>( Generator.NamespaceImportDeclaration("n.m"), "using n.m;"); } [Fact] public void TestNamespaceDeclarations() { VerifySyntax<NamespaceDeclarationSyntax>( Generator.NamespaceDeclaration("n"), "namespace n\r\n{\r\n}"); VerifySyntax<NamespaceDeclarationSyntax>( Generator.NamespaceDeclaration("n.m"), "namespace n.m\r\n{\r\n}"); VerifySyntax<NamespaceDeclarationSyntax>( Generator.NamespaceDeclaration("n", Generator.NamespaceImportDeclaration("m")), "namespace n\r\n{\r\n using m;\r\n}"); VerifySyntax<NamespaceDeclarationSyntax>( Generator.NamespaceDeclaration("n", Generator.ClassDeclaration("c"), Generator.NamespaceImportDeclaration("m")), "namespace n\r\n{\r\n using m;\r\n\r\n class c\r\n {\r\n }\r\n}"); } [Fact] public void TestCompilationUnits() { VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit(), ""); VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit( Generator.NamespaceDeclaration("n")), "namespace n\r\n{\r\n}"); VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit( Generator.NamespaceImportDeclaration("n")), "using n;"); VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit( Generator.ClassDeclaration("c"), Generator.NamespaceImportDeclaration("m")), "using m;\r\n\r\nclass c\r\n{\r\n}"); VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit( Generator.NamespaceImportDeclaration("n"), Generator.NamespaceDeclaration("n", Generator.NamespaceImportDeclaration("m"), Generator.ClassDeclaration("c"))), "using n;\r\n\r\nnamespace n\r\n{\r\n using m;\r\n\r\n class c\r\n {\r\n }\r\n}"); } [Fact] public void TestAttributeDeclarations() { VerifySyntax<AttributeListSyntax>( Generator.Attribute(Generator.IdentifierName("a")), "[a]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a"), "[a]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a.b"), "[a.b]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new SyntaxNode[] { }), "[a()]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new[] { Generator.IdentifierName("x") }), "[a(x)]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new[] { Generator.AttributeArgument(Generator.IdentifierName("x")) }), "[a(x)]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new[] { Generator.AttributeArgument("x", Generator.IdentifierName("y")) }), "[a(x = y)]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new[] { Generator.IdentifierName("x"), Generator.IdentifierName("y") }), "[a(x, y)]"); } [Fact] public void TestAddAttributes() { VerifySyntax<FieldDeclarationSyntax>( Generator.AddAttributes( Generator.FieldDeclaration("y", Generator.IdentifierName("x")), Generator.Attribute("a")), "[a]\r\nx y;"); VerifySyntax<FieldDeclarationSyntax>( Generator.AddAttributes( Generator.AddAttributes( Generator.FieldDeclaration("y", Generator.IdentifierName("x")), Generator.Attribute("a")), Generator.Attribute("b")), "[a]\r\n[b]\r\nx y;"); VerifySyntax<MethodDeclarationSyntax>( Generator.AddAttributes( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[a]\r\nabstract t m();"); VerifySyntax<MethodDeclarationSyntax>( Generator.AddReturnAttributes( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[return: a]\r\nabstract t m();"); VerifySyntax<PropertyDeclarationSyntax>( Generator.AddAttributes( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), accessibility: Accessibility.NotApplicable, modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[a]\r\nabstract x p { get; set; }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.AddAttributes( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[a]\r\nabstract x this[y z] { get; set; }"); VerifySyntax<EventDeclarationSyntax>( Generator.AddAttributes( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[a]\r\nabstract event t ep { add; remove; }"); VerifySyntax<EventFieldDeclarationSyntax>( Generator.AddAttributes( Generator.EventDeclaration("ef", Generator.IdentifierName("t")), Generator.Attribute("a")), "[a]\r\nevent t ef;"); VerifySyntax<ClassDeclarationSyntax>( Generator.AddAttributes( Generator.ClassDeclaration("c"), Generator.Attribute("a")), "[a]\r\nclass c\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.AddAttributes( Generator.StructDeclaration("s"), Generator.Attribute("a")), "[a]\r\nstruct s\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.AddAttributes( Generator.InterfaceDeclaration("i"), Generator.Attribute("a")), "[a]\r\ninterface i\r\n{\r\n}"); VerifySyntax<DelegateDeclarationSyntax>( Generator.AddAttributes( Generator.DelegateDeclaration("d"), Generator.Attribute("a")), "[a]\r\ndelegate void d();"); VerifySyntax<ParameterSyntax>( Generator.AddAttributes( Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.Attribute("a")), "[a] t p"); VerifySyntax<CompilationUnitSyntax>( Generator.AddAttributes( Generator.CompilationUnit(Generator.NamespaceDeclaration("n")), Generator.Attribute("a")), "[assembly: a]\r\nnamespace n\r\n{\r\n}"); } [Fact] [WorkItem(5066, "https://github.com/dotnet/roslyn/issues/5066")] public void TestAddAttributesToAccessors() { var prop = Generator.PropertyDeclaration("P", Generator.IdentifierName("T")); var evnt = Generator.CustomEventDeclaration("E", Generator.IdentifierName("T")); CheckAddRemoveAttribute(Generator.GetAccessor(prop, DeclarationKind.GetAccessor)); CheckAddRemoveAttribute(Generator.GetAccessor(prop, DeclarationKind.SetAccessor)); CheckAddRemoveAttribute(Generator.GetAccessor(evnt, DeclarationKind.AddAccessor)); CheckAddRemoveAttribute(Generator.GetAccessor(evnt, DeclarationKind.RemoveAccessor)); } private void CheckAddRemoveAttribute(SyntaxNode declaration) { var initialAttributes = Generator.GetAttributes(declaration); Assert.Equal(0, initialAttributes.Count); var withAttribute = Generator.AddAttributes(declaration, Generator.Attribute("a")); var attrsAdded = Generator.GetAttributes(withAttribute); Assert.Equal(1, attrsAdded.Count); var withoutAttribute = Generator.RemoveNode(withAttribute, attrsAdded[0]); var attrsRemoved = Generator.GetAttributes(withoutAttribute); Assert.Equal(0, attrsRemoved.Count); } [Fact] public void TestAddRemoveAttributesPerservesTrivia() { var cls = SyntaxFactory.ParseCompilationUnit(@"// comment public class C { } // end").Members[0]; var added = Generator.AddAttributes(cls, Generator.Attribute("a")); VerifySyntax<ClassDeclarationSyntax>(added, "// comment\r\n[a]\r\npublic class C\r\n{\r\n} // end\r\n"); var removed = Generator.RemoveAllAttributes(added); VerifySyntax<ClassDeclarationSyntax>(removed, "// comment\r\npublic class C\r\n{\r\n} // end\r\n"); var attrWithComment = Generator.GetAttributes(added).First(); VerifySyntax<AttributeListSyntax>(attrWithComment, "// comment\r\n[a]"); } [Fact] public void TestWithTypeParameters() { VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeParameters( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "abstract void m<a>();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeParameters( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract)), "abstract void m();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeParameters( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a", "b"), "abstract void m<a, b>();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeParameters(Generator.WithTypeParameters( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a", "b")), "abstract void m();"); VerifySyntax<ClassDeclarationSyntax>( Generator.WithTypeParameters( Generator.ClassDeclaration("c"), "a", "b"), "class c<a, b>\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.WithTypeParameters( Generator.StructDeclaration("s"), "a", "b"), "struct s<a, b>\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.WithTypeParameters( Generator.InterfaceDeclaration("i"), "a", "b"), "interface i<a, b>\r\n{\r\n}"); VerifySyntax<DelegateDeclarationSyntax>( Generator.WithTypeParameters( Generator.DelegateDeclaration("d"), "a", "b"), "delegate void d<a, b>();"); } [Fact] public void TestWithTypeConstraint() { VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", Generator.IdentifierName("b")), "abstract void m<a>()\r\n where a : b;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", Generator.IdentifierName("b"), Generator.IdentifierName("c")), "abstract void m<a>()\r\n where a : b, c;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a"), "abstract void m<a>();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint(Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", Generator.IdentifierName("b"), Generator.IdentifierName("c")), "a"), "abstract void m<a>();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a", "x"), "a", Generator.IdentifierName("b"), Generator.IdentifierName("c")), "x", Generator.IdentifierName("y")), "abstract void m<a, x>()\r\n where a : b, c where x : y;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.Constructor), "abstract void m<a>()\r\n where a : new();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ReferenceType), "abstract void m<a>()\r\n where a : class;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ValueType), "abstract void m<a>()\r\n where a : struct;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ReferenceType | SpecialTypeConstraintKind.Constructor), "abstract void m<a>()\r\n where a : class, new();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ReferenceType | SpecialTypeConstraintKind.ValueType), "abstract void m<a>()\r\n where a : class;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ReferenceType, Generator.IdentifierName("b"), Generator.IdentifierName("c")), "abstract void m<a>()\r\n where a : class, b, c;"); // type declarations VerifySyntax<ClassDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters( Generator.ClassDeclaration("c"), "a", "b"), "a", Generator.IdentifierName("x")), "class c<a, b>\r\n where a : x\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters( Generator.StructDeclaration("s"), "a", "b"), "a", Generator.IdentifierName("x")), "struct s<a, b>\r\n where a : x\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters( Generator.InterfaceDeclaration("i"), "a", "b"), "a", Generator.IdentifierName("x")), "interface i<a, b>\r\n where a : x\r\n{\r\n}"); VerifySyntax<DelegateDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters( Generator.DelegateDeclaration("d"), "a", "b"), "a", Generator.IdentifierName("x")), "delegate void d<a, b>()\r\n where a : x;"); } [Fact] public void TestInterfaceDeclarationWithEventFromSymbol() { VerifySyntax<InterfaceDeclarationSyntax>( Generator.Declaration(_emptyCompilation.GetTypeByMetadataName("System.ComponentModel.INotifyPropertyChanged")), @"public interface INotifyPropertyChanged { event global::System.ComponentModel.PropertyChangedEventHandler PropertyChanged; }"); } [WorkItem(38379, "https://github.com/dotnet/roslyn/issues/38379")] [Fact] public void TestUnsafeFieldDeclarationFromSymbol() { VerifySyntax<MethodDeclarationSyntax>( Generator.Declaration( _emptyCompilation.GetTypeByMetadataName("System.IntPtr").GetMembers("ToPointer").Single()), @"public unsafe void* ToPointer() { }"); } [Fact] public void TestEnumDeclarationFromSymbol() { VerifySyntax<EnumDeclarationSyntax>( Generator.Declaration( _emptyCompilation.GetTypeByMetadataName("System.DateTimeKind")), @"public enum DateTimeKind { Unspecified = 0, Utc = 1, Local = 2 }"); } [Fact] public void TestEnumWithUnderlyingTypeFromSymbol() { VerifySyntax<EnumDeclarationSyntax>( Generator.Declaration( _emptyCompilation.GetTypeByMetadataName("System.Security.SecurityRuleSet")), @"public enum SecurityRuleSet : byte { None = 0, Level1 = 1, Level2 = 2 }"); } #endregion #region Add/Insert/Remove/Get declarations & members/elements private void AssertNamesEqual(string[] expectedNames, IEnumerable<SyntaxNode> actualNodes) { var actualNames = actualNodes.Select(n => Generator.GetName(n)).ToArray(); var expected = string.Join(", ", expectedNames); var actual = string.Join(", ", actualNames); Assert.Equal(expected, actual); } private void AssertNamesEqual(string name, IEnumerable<SyntaxNode> actualNodes) => AssertNamesEqual(new[] { name }, actualNodes); private void AssertMemberNamesEqual(string[] expectedNames, SyntaxNode declaration) => AssertNamesEqual(expectedNames, Generator.GetMembers(declaration)); private void AssertMemberNamesEqual(string expectedName, SyntaxNode declaration) => AssertNamesEqual(new[] { expectedName }, Generator.GetMembers(declaration)); [Fact] public void TestAddNamespaceImports() { AssertNamesEqual("x.y", Generator.GetNamespaceImports(Generator.AddNamespaceImports(Generator.CompilationUnit(), Generator.NamespaceImportDeclaration("x.y")))); AssertNamesEqual(new[] { "x.y", "z" }, Generator.GetNamespaceImports(Generator.AddNamespaceImports(Generator.CompilationUnit(), Generator.NamespaceImportDeclaration("x.y"), Generator.IdentifierName("z")))); AssertNamesEqual("", Generator.GetNamespaceImports(Generator.AddNamespaceImports(Generator.CompilationUnit(), Generator.MethodDeclaration("m")))); AssertNamesEqual(new[] { "x", "y.z" }, Generator.GetNamespaceImports(Generator.AddNamespaceImports(Generator.CompilationUnit(Generator.IdentifierName("x")), Generator.DottedName("y.z")))); } [Fact] public void TestRemoveNamespaceImports() { TestRemoveAllNamespaceImports(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x"))); TestRemoveAllNamespaceImports(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x"), Generator.IdentifierName("y"))); TestRemoveNamespaceImport(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x")), "x", new string[] { }); TestRemoveNamespaceImport(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x"), Generator.IdentifierName("y")), "x", new[] { "y" }); TestRemoveNamespaceImport(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x"), Generator.IdentifierName("y")), "y", new[] { "x" }); } private void TestRemoveAllNamespaceImports(SyntaxNode declaration) => Assert.Equal(0, Generator.GetNamespaceImports(Generator.RemoveNodes(declaration, Generator.GetNamespaceImports(declaration))).Count); private void TestRemoveNamespaceImport(SyntaxNode declaration, string name, string[] remainingNames) { var newDecl = Generator.RemoveNode(declaration, Generator.GetNamespaceImports(declaration).First(m => Generator.GetName(m) == name)); AssertNamesEqual(remainingNames, Generator.GetNamespaceImports(newDecl)); } [Fact] public void TestRemoveNodeInTrivia() { var code = @" ///<summary> ... </summary> public class C { }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var summary = cls.DescendantNodes(descendIntoTrivia: true).OfType<XmlElementSyntax>().First(); var newCu = Generator.RemoveNode(cu, summary); VerifySyntaxRaw<CompilationUnitSyntax>( newCu, @" public class C { }"); } [Fact] public void TestReplaceNodeInTrivia() { var code = @" ///<summary> ... </summary> public class C { }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var summary = cls.DescendantNodes(descendIntoTrivia: true).OfType<XmlElementSyntax>().First(); var summary2 = summary.WithContent(default); var newCu = Generator.ReplaceNode(cu, summary, summary2); VerifySyntaxRaw<CompilationUnitSyntax>( newCu, @" ///<summary></summary> public class C { }"); } [Fact] public void TestInsertAfterNodeInTrivia() { var code = @" ///<summary> ... </summary> public class C { }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var text = cls.DescendantNodes(descendIntoTrivia: true).OfType<XmlTextSyntax>().First(); var newCu = Generator.InsertNodesAfter(cu, text, new SyntaxNode[] { text }); VerifySyntaxRaw<CompilationUnitSyntax>( newCu, @" ///<summary> ... ... </summary> public class C { }"); } [Fact] public void TestInsertBeforeNodeInTrivia() { var code = @" ///<summary> ... </summary> public class C { }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var text = cls.DescendantNodes(descendIntoTrivia: true).OfType<XmlTextSyntax>().First(); var newCu = Generator.InsertNodesBefore(cu, text, new SyntaxNode[] { text }); VerifySyntaxRaw<CompilationUnitSyntax>( newCu, @" ///<summary> ... ... </summary> public class C { }"); } [Fact] public void TestAddMembers() { AssertMemberNamesEqual("m", Generator.AddMembers(Generator.ClassDeclaration("d"), new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("m", Generator.AddMembers(Generator.StructDeclaration("s"), new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("m", Generator.AddMembers(Generator.InterfaceDeclaration("i"), new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("v", Generator.AddMembers(Generator.EnumDeclaration("e"), new[] { Generator.EnumMember("v") })); AssertMemberNamesEqual("n2", Generator.AddMembers(Generator.NamespaceDeclaration("n"), new[] { Generator.NamespaceDeclaration("n2") })); AssertMemberNamesEqual("n", Generator.AddMembers(Generator.CompilationUnit(), new[] { Generator.NamespaceDeclaration("n") })); AssertMemberNamesEqual(new[] { "m", "m2" }, Generator.AddMembers(Generator.ClassDeclaration("d", members: new[] { Generator.MethodDeclaration("m") }), new[] { Generator.MethodDeclaration("m2") })); AssertMemberNamesEqual(new[] { "m", "m2" }, Generator.AddMembers(Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m") }), new[] { Generator.MethodDeclaration("m2") })); AssertMemberNamesEqual(new[] { "m", "m2" }, Generator.AddMembers(Generator.InterfaceDeclaration("i", members: new[] { Generator.MethodDeclaration("m") }), new[] { Generator.MethodDeclaration("m2") })); AssertMemberNamesEqual(new[] { "v", "v2" }, Generator.AddMembers(Generator.EnumDeclaration("i", members: new[] { Generator.EnumMember("v") }), new[] { Generator.EnumMember("v2") })); AssertMemberNamesEqual(new[] { "n1", "n2" }, Generator.AddMembers(Generator.NamespaceDeclaration("n", new[] { Generator.NamespaceDeclaration("n1") }), new[] { Generator.NamespaceDeclaration("n2") })); AssertMemberNamesEqual(new[] { "n1", "n2" }, Generator.AddMembers(Generator.CompilationUnit(declarations: new[] { Generator.NamespaceDeclaration("n1") }), new[] { Generator.NamespaceDeclaration("n2") })); } [Fact] public void TestRemoveMembers() { // remove all members TestRemoveAllMembers(Generator.ClassDeclaration("c", members: new[] { Generator.MethodDeclaration("m") })); TestRemoveAllMembers(Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m") })); TestRemoveAllMembers(Generator.InterfaceDeclaration("i", members: new[] { Generator.MethodDeclaration("m") })); TestRemoveAllMembers(Generator.EnumDeclaration("i", members: new[] { Generator.EnumMember("v") })); TestRemoveAllMembers(Generator.NamespaceDeclaration("n", new[] { Generator.NamespaceDeclaration("n") })); TestRemoveAllMembers(Generator.CompilationUnit(declarations: new[] { Generator.NamespaceDeclaration("n") })); TestRemoveMember(Generator.ClassDeclaration("c", members: new[] { Generator.MethodDeclaration("m1"), Generator.MethodDeclaration("m2") }), "m1", new[] { "m2" }); TestRemoveMember(Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m1"), Generator.MethodDeclaration("m2") }), "m1", new[] { "m2" }); } private void TestRemoveAllMembers(SyntaxNode declaration) => Assert.Equal(0, Generator.GetMembers(Generator.RemoveNodes(declaration, Generator.GetMembers(declaration))).Count); private void TestRemoveMember(SyntaxNode declaration, string name, string[] remainingNames) { var newDecl = Generator.RemoveNode(declaration, Generator.GetMembers(declaration).First(m => Generator.GetName(m) == name)); AssertMemberNamesEqual(remainingNames, newDecl); } [Fact] public void TestGetMembers() { AssertMemberNamesEqual("m", Generator.ClassDeclaration("c", members: new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("m", Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("m", Generator.InterfaceDeclaration("i", members: new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("v", Generator.EnumDeclaration("e", members: new[] { Generator.EnumMember("v") })); AssertMemberNamesEqual("c", Generator.NamespaceDeclaration("n", declarations: new[] { Generator.ClassDeclaration("c") })); AssertMemberNamesEqual("c", Generator.CompilationUnit(declarations: new[] { Generator.ClassDeclaration("c") })); } [Fact] public void TestGetDeclarationKind() { Assert.Equal(DeclarationKind.CompilationUnit, Generator.GetDeclarationKind(Generator.CompilationUnit())); Assert.Equal(DeclarationKind.Class, Generator.GetDeclarationKind(Generator.ClassDeclaration("c"))); Assert.Equal(DeclarationKind.Struct, Generator.GetDeclarationKind(Generator.StructDeclaration("s"))); Assert.Equal(DeclarationKind.Interface, Generator.GetDeclarationKind(Generator.InterfaceDeclaration("i"))); Assert.Equal(DeclarationKind.Enum, Generator.GetDeclarationKind(Generator.EnumDeclaration("e"))); Assert.Equal(DeclarationKind.Delegate, Generator.GetDeclarationKind(Generator.DelegateDeclaration("d"))); Assert.Equal(DeclarationKind.Method, Generator.GetDeclarationKind(Generator.MethodDeclaration("m"))); Assert.Equal(DeclarationKind.Constructor, Generator.GetDeclarationKind(Generator.ConstructorDeclaration())); Assert.Equal(DeclarationKind.Parameter, Generator.GetDeclarationKind(Generator.ParameterDeclaration("p"))); Assert.Equal(DeclarationKind.Property, Generator.GetDeclarationKind(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.Indexer, Generator.GetDeclarationKind(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(Generator.FieldDeclaration("f", Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.EnumMember, Generator.GetDeclarationKind(Generator.EnumMember("v"))); Assert.Equal(DeclarationKind.Event, Generator.GetDeclarationKind(Generator.EventDeclaration("ef", Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.CustomEvent, Generator.GetDeclarationKind(Generator.CustomEventDeclaration("e", Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.Namespace, Generator.GetDeclarationKind(Generator.NamespaceDeclaration("n"))); Assert.Equal(DeclarationKind.NamespaceImport, Generator.GetDeclarationKind(Generator.NamespaceImportDeclaration("u"))); Assert.Equal(DeclarationKind.Variable, Generator.GetDeclarationKind(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"))); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(Generator.Attribute("a"))); } [Fact] public void TestGetName() { Assert.Equal("c", Generator.GetName(Generator.ClassDeclaration("c"))); Assert.Equal("s", Generator.GetName(Generator.StructDeclaration("s"))); Assert.Equal("i", Generator.GetName(Generator.EnumDeclaration("i"))); Assert.Equal("e", Generator.GetName(Generator.EnumDeclaration("e"))); Assert.Equal("d", Generator.GetName(Generator.DelegateDeclaration("d"))); Assert.Equal("m", Generator.GetName(Generator.MethodDeclaration("m"))); Assert.Equal("", Generator.GetName(Generator.ConstructorDeclaration())); Assert.Equal("p", Generator.GetName(Generator.ParameterDeclaration("p"))); Assert.Equal("p", Generator.GetName(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")))); Assert.Equal("", Generator.GetName(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")))); Assert.Equal("f", Generator.GetName(Generator.FieldDeclaration("f", Generator.IdentifierName("t")))); Assert.Equal("v", Generator.GetName(Generator.EnumMember("v"))); Assert.Equal("ef", Generator.GetName(Generator.EventDeclaration("ef", Generator.IdentifierName("t")))); Assert.Equal("ep", Generator.GetName(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t")))); Assert.Equal("n", Generator.GetName(Generator.NamespaceDeclaration("n"))); Assert.Equal("u", Generator.GetName(Generator.NamespaceImportDeclaration("u"))); Assert.Equal("loc", Generator.GetName(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"))); Assert.Equal("a", Generator.GetName(Generator.Attribute("a"))); } [Fact] public void TestWithName() { Assert.Equal("c", Generator.GetName(Generator.WithName(Generator.ClassDeclaration("x"), "c"))); Assert.Equal("s", Generator.GetName(Generator.WithName(Generator.StructDeclaration("x"), "s"))); Assert.Equal("i", Generator.GetName(Generator.WithName(Generator.EnumDeclaration("x"), "i"))); Assert.Equal("e", Generator.GetName(Generator.WithName(Generator.EnumDeclaration("x"), "e"))); Assert.Equal("d", Generator.GetName(Generator.WithName(Generator.DelegateDeclaration("x"), "d"))); Assert.Equal("m", Generator.GetName(Generator.WithName(Generator.MethodDeclaration("x"), "m"))); Assert.Equal("", Generator.GetName(Generator.WithName(Generator.ConstructorDeclaration(), ".ctor"))); Assert.Equal("p", Generator.GetName(Generator.WithName(Generator.ParameterDeclaration("x"), "p"))); Assert.Equal("p", Generator.GetName(Generator.WithName(Generator.PropertyDeclaration("x", Generator.IdentifierName("t")), "p"))); Assert.Equal("", Generator.GetName(Generator.WithName(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")), "this"))); Assert.Equal("f", Generator.GetName(Generator.WithName(Generator.FieldDeclaration("x", Generator.IdentifierName("t")), "f"))); Assert.Equal("v", Generator.GetName(Generator.WithName(Generator.EnumMember("x"), "v"))); Assert.Equal("ef", Generator.GetName(Generator.WithName(Generator.EventDeclaration("x", Generator.IdentifierName("t")), "ef"))); Assert.Equal("ep", Generator.GetName(Generator.WithName(Generator.CustomEventDeclaration("x", Generator.IdentifierName("t")), "ep"))); Assert.Equal("n", Generator.GetName(Generator.WithName(Generator.NamespaceDeclaration("x"), "n"))); Assert.Equal("u", Generator.GetName(Generator.WithName(Generator.NamespaceImportDeclaration("x"), "u"))); Assert.Equal("loc", Generator.GetName(Generator.WithName(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "x"), "loc"))); Assert.Equal("a", Generator.GetName(Generator.WithName(Generator.Attribute("x"), "a"))); } [Fact] public void TestGetAccessibility() { Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.ClassDeclaration("c", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.StructDeclaration("s", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.EnumDeclaration("i", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.EnumDeclaration("e", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.DelegateDeclaration("d", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.MethodDeclaration("m", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.ConstructorDeclaration(accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.ParameterDeclaration("p"))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.FieldDeclaration("f", Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.EnumMember("v"))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.EventDeclaration("ef", Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.NamespaceDeclaration("n"))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.NamespaceImportDeclaration("u"))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.Attribute("a"))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(SyntaxFactory.TypeParameter("tp"))); } [Fact] public void TestWithAccessibility() { Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.ClassDeclaration("c", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.StructDeclaration("s", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.EnumDeclaration("i", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.EnumDeclaration("e", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.DelegateDeclaration("d", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.MethodDeclaration("m", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.ConstructorDeclaration(accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.ParameterDeclaration("p"), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.FieldDeclaration("f", Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.EnumMember("v"), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.EventDeclaration("ef", Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.NamespaceDeclaration("n"), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.NamespaceImportDeclaration("u"), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.Attribute("a"), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(SyntaxFactory.TypeParameter("tp"), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(SyntaxFactory.AccessorDeclaration(SyntaxKind.InitAccessorDeclaration), Accessibility.Private))); } [Fact] public void TestGetModifiers() { Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.ClassDeclaration("c", modifiers: DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Partial, Generator.GetModifiers(Generator.StructDeclaration("s", modifiers: DeclarationModifiers.Partial))); Assert.Equal(DeclarationModifiers.New, Generator.GetModifiers(Generator.EnumDeclaration("e", modifiers: DeclarationModifiers.New))); Assert.Equal(DeclarationModifiers.New, Generator.GetModifiers(Generator.DelegateDeclaration("d", modifiers: DeclarationModifiers.New))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.ConstructorDeclaration(modifiers: DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.ParameterDeclaration("p"))); Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Const, Generator.GetModifiers(Generator.FieldDeclaration("f", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Const))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.EventDeclaration("ef", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.EnumMember("v"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.NamespaceDeclaration("n"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.NamespaceImportDeclaration("u"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.Attribute("a"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(SyntaxFactory.TypeParameter("tp"))); } [Fact] public void TestWithModifiers() { Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.WithModifiers(Generator.ClassDeclaration("c"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Partial, Generator.GetModifiers(Generator.WithModifiers(Generator.StructDeclaration("s"), DeclarationModifiers.Partial))); Assert.Equal(DeclarationModifiers.New, Generator.GetModifiers(Generator.WithModifiers(Generator.EnumDeclaration("e"), DeclarationModifiers.New))); Assert.Equal(DeclarationModifiers.New, Generator.GetModifiers(Generator.WithModifiers(Generator.DelegateDeclaration("d"), DeclarationModifiers.New))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.WithModifiers(Generator.MethodDeclaration("m"), DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.WithModifiers(Generator.ConstructorDeclaration(), DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.ParameterDeclaration("p"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.WithModifiers(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.WithModifiers(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Const, Generator.GetModifiers(Generator.WithModifiers(Generator.FieldDeclaration("f", Generator.IdentifierName("t")), DeclarationModifiers.Const))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.WithModifiers(Generator.EventDeclaration("ef", Generator.IdentifierName("t")), DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.WithModifiers(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t")), DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.EnumMember("v"), DeclarationModifiers.Partial))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.NamespaceDeclaration("n"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.NamespaceImportDeclaration("u"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.Attribute("a"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(SyntaxFactory.TypeParameter("tp"), DeclarationModifiers.Abstract))); } [Fact] public void TestWithModifiers_AllowedModifiers() { var allModifiers = new DeclarationModifiers(true, true, true, true, true, true, true, true, true, true, true, true, true); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.ClassDeclaration("c"), allModifiers))); Assert.Equal( DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Unsafe | DeclarationModifiers.ReadOnly, Generator.GetModifiers(Generator.WithModifiers(Generator.StructDeclaration("s"), allModifiers))); Assert.Equal( DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.InterfaceDeclaration("i"), allModifiers))); Assert.Equal( DeclarationModifiers.New | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.DelegateDeclaration("d"), allModifiers))); Assert.Equal( DeclarationModifiers.New, Generator.GetModifiers(Generator.WithModifiers(Generator.EnumDeclaration("e"), allModifiers))); Assert.Equal( DeclarationModifiers.Const | DeclarationModifiers.New | DeclarationModifiers.ReadOnly | DeclarationModifiers.Static | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.FieldDeclaration("f", Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.Static | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.ConstructorDeclaration("c"), allModifiers))); Assert.Equal( DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(SyntaxFactory.DestructorDeclaration("c"), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.Async | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe | DeclarationModifiers.ReadOnly, Generator.GetModifiers(Generator.WithModifiers(Generator.MethodDeclaration("m"), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.New | DeclarationModifiers.Static | DeclarationModifiers.Unsafe | DeclarationModifiers.ReadOnly, Generator.GetModifiers(Generator.WithModifiers(Generator.EventDeclaration("ef", Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe | DeclarationModifiers.ReadOnly, Generator.GetModifiers(Generator.WithModifiers(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Virtual, Generator.GetModifiers(Generator.WithModifiers(SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration), allModifiers))); } [Fact] public void TestGetType() { Assert.Equal("t", Generator.GetType(Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"))).ToString()); Assert.Null(Generator.GetType(Generator.MethodDeclaration("m"))); Assert.Equal("t", Generator.GetType(Generator.FieldDeclaration("f", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("pt")) }, Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.ParameterDeclaration("p", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.EventDeclaration("ef", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.DelegateDeclaration("t", returnType: Generator.IdentifierName("t"))).ToString()); Assert.Null(Generator.GetType(Generator.DelegateDeclaration("d"))); Assert.Equal("t", Generator.GetType(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "v")).ToString()); Assert.Null(Generator.GetType(Generator.ClassDeclaration("c"))); Assert.Null(Generator.GetType(Generator.IdentifierName("x"))); } [Fact] public void TestWithType() { Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.FieldDeclaration("f", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.PropertyDeclaration("p", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("pt")) }, Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.ParameterDeclaration("p", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.DelegateDeclaration("t"), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.EventDeclaration("ef", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "v"), Generator.IdentifierName("t"))).ToString()); Assert.Null(Generator.GetType(Generator.WithType(Generator.ClassDeclaration("c"), Generator.IdentifierName("t")))); Assert.Null(Generator.GetType(Generator.WithType(Generator.IdentifierName("x"), Generator.IdentifierName("t")))); } [Fact] public void TestGetParameters() { Assert.Equal(0, Generator.GetParameters(Generator.MethodDeclaration("m")).Count); Assert.Equal(1, Generator.GetParameters(Generator.MethodDeclaration("m", parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(2, Generator.GetParameters(Generator.MethodDeclaration("m", parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.ParameterDeclaration("p2", Generator.IdentifierName("t2")) })).Count); Assert.Equal(0, Generator.GetParameters(Generator.ConstructorDeclaration()).Count); Assert.Equal(1, Generator.GetParameters(Generator.ConstructorDeclaration(parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(2, Generator.GetParameters(Generator.ConstructorDeclaration(parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.ParameterDeclaration("p2", Generator.IdentifierName("t2")) })).Count); Assert.Equal(1, Generator.GetParameters(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetParameters(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.ParameterDeclaration("p2", Generator.IdentifierName("t2")) }, Generator.IdentifierName("t"))).Count); Assert.Equal(0, Generator.GetParameters(Generator.ValueReturningLambdaExpression(Generator.IdentifierName("expr"))).Count); Assert.Equal(1, Generator.GetParameters(Generator.ValueReturningLambdaExpression("p1", Generator.IdentifierName("expr"))).Count); Assert.Equal(0, Generator.GetParameters(Generator.VoidReturningLambdaExpression(Generator.IdentifierName("expr"))).Count); Assert.Equal(1, Generator.GetParameters(Generator.VoidReturningLambdaExpression("p1", Generator.IdentifierName("expr"))).Count); Assert.Equal(0, Generator.GetParameters(Generator.DelegateDeclaration("d")).Count); Assert.Equal(1, Generator.GetParameters(Generator.DelegateDeclaration("d", parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(0, Generator.GetParameters(Generator.ClassDeclaration("c")).Count); Assert.Equal(0, Generator.GetParameters(Generator.IdentifierName("x")).Count); } [Fact] public void TestAddParameters() { Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.MethodDeclaration("m"), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.ConstructorDeclaration(), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(3, Generator.GetParameters(Generator.AddParameters(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("t")), new[] { Generator.ParameterDeclaration("p2", Generator.IdentifierName("t2")), Generator.ParameterDeclaration("p3", Generator.IdentifierName("t3")) })).Count); Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.ValueReturningLambdaExpression(Generator.IdentifierName("expr")), new[] { Generator.LambdaParameter("p") })).Count); Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.VoidReturningLambdaExpression(Generator.IdentifierName("expr")), new[] { Generator.LambdaParameter("p") })).Count); Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.DelegateDeclaration("d"), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(0, Generator.GetParameters(Generator.AddParameters(Generator.ClassDeclaration("c"), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(0, Generator.GetParameters(Generator.AddParameters(Generator.IdentifierName("x"), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); } [Fact] public void TestGetExpression() { // initializers Assert.Equal("x", Generator.GetExpression(Generator.FieldDeclaration("f", Generator.IdentifierName("t"), initializer: Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.ParameterDeclaration("p", Generator.IdentifierName("t"), initializer: Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.LocalDeclarationStatement("loc", initializer: Generator.IdentifierName("x"))).ToString()); // lambda bodies Assert.Null(Generator.GetExpression(Generator.ValueReturningLambdaExpression("p", new[] { Generator.IdentifierName("x") }))); Assert.Equal(1, Generator.GetStatements(Generator.ValueReturningLambdaExpression("p", new[] { Generator.IdentifierName("x") })).Count); Assert.Equal("x", Generator.GetExpression(Generator.ValueReturningLambdaExpression(Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.VoidReturningLambdaExpression(Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.ValueReturningLambdaExpression("p", Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.VoidReturningLambdaExpression("p", Generator.IdentifierName("x"))).ToString()); // identifier Assert.Null(Generator.GetExpression(Generator.IdentifierName("e"))); // expression bodied methods var method = (MethodDeclarationSyntax)Generator.MethodDeclaration("p"); method = method.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); method = method.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); Assert.Equal("x", Generator.GetExpression(method).ToString()); // expression bodied local functions var local = SyntaxFactory.LocalFunctionStatement(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), "p"); local = local.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); local = local.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); Assert.Equal("x", Generator.GetExpression(local).ToString()); } [Fact] public void TestWithExpression() { // initializers Assert.Equal("x", Generator.GetExpression(Generator.WithExpression(Generator.FieldDeclaration("f", Generator.IdentifierName("t")), Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.WithExpression(Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.WithExpression(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"), Generator.IdentifierName("x"))).ToString()); // lambda bodies Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.ValueReturningLambdaExpression("p", new[] { Generator.IdentifierName("x") }), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.VoidReturningLambdaExpression("p", new[] { Generator.IdentifierName("x") }), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.ValueReturningLambdaExpression(new[] { Generator.IdentifierName("x") }), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.VoidReturningLambdaExpression(new[] { Generator.IdentifierName("x") }), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.ValueReturningLambdaExpression("p", Generator.IdentifierName("x")), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.VoidReturningLambdaExpression("p", Generator.IdentifierName("x")), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.ValueReturningLambdaExpression(Generator.IdentifierName("x")), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.VoidReturningLambdaExpression(Generator.IdentifierName("x")), Generator.IdentifierName("y"))).ToString()); // identifier Assert.Null(Generator.GetExpression(Generator.WithExpression(Generator.IdentifierName("e"), Generator.IdentifierName("x")))); // expression bodied methods var method = (MethodDeclarationSyntax)Generator.MethodDeclaration("p"); method = method.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); method = method.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(method, Generator.IdentifierName("y"))).ToString()); // expression bodied local functions var local = SyntaxFactory.LocalFunctionStatement(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), "p"); local = local.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); local = local.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(local, Generator.IdentifierName("y"))).ToString()); } [Fact] public void TestAccessorDeclarations() { var prop = Generator.PropertyDeclaration("p", Generator.IdentifierName("T")); Assert.Equal(2, Generator.GetAccessors(prop).Count); // get accessors from property var getAccessor = Generator.GetAccessor(prop, DeclarationKind.GetAccessor); Assert.NotNull(getAccessor); VerifySyntax<AccessorDeclarationSyntax>(getAccessor, @"get;"); Assert.NotNull(getAccessor); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(getAccessor)); // get accessors from property var setAccessor = Generator.GetAccessor(prop, DeclarationKind.SetAccessor); Assert.NotNull(setAccessor); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(setAccessor)); // remove accessors Assert.Null(Generator.GetAccessor(Generator.RemoveNode(prop, getAccessor), DeclarationKind.GetAccessor)); Assert.Null(Generator.GetAccessor(Generator.RemoveNode(prop, setAccessor), DeclarationKind.SetAccessor)); // change accessor accessibility Assert.Equal(Accessibility.Public, Generator.GetAccessibility(Generator.WithAccessibility(getAccessor, Accessibility.Public))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(setAccessor, Accessibility.Private))); // change accessor statements Assert.Equal(0, Generator.GetStatements(getAccessor).Count); Assert.Equal(0, Generator.GetStatements(setAccessor).Count); var newGetAccessor = Generator.WithStatements(getAccessor, null); VerifySyntax<AccessorDeclarationSyntax>(newGetAccessor, @"get;"); var newNewGetAccessor = Generator.WithStatements(newGetAccessor, new SyntaxNode[] { }); VerifySyntax<AccessorDeclarationSyntax>(newNewGetAccessor, @"get { }"); // change accessors var newProp = Generator.ReplaceNode(prop, getAccessor, Generator.WithAccessibility(getAccessor, Accessibility.Public)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(Generator.GetAccessor(newProp, DeclarationKind.GetAccessor))); newProp = Generator.ReplaceNode(prop, setAccessor, Generator.WithAccessibility(setAccessor, Accessibility.Public)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(Generator.GetAccessor(newProp, DeclarationKind.SetAccessor))); } [Fact] public void TestAccessorDeclarations2() { VerifySyntax<PropertyDeclarationSyntax>( Generator.WithAccessorDeclarations(Generator.PropertyDeclaration("p", Generator.IdentifierName("x"))), "x p { }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.WithAccessorDeclarations( Generator.PropertyDeclaration("p", Generator.IdentifierName("x")), Generator.GetAccessorDeclaration(Accessibility.NotApplicable, new[] { Generator.ReturnStatement() })), "x p\r\n{\r\n get\r\n {\r\n return;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.WithAccessorDeclarations( Generator.PropertyDeclaration("p", Generator.IdentifierName("x")), Generator.GetAccessorDeclaration(Accessibility.Protected, new[] { Generator.ReturnStatement() })), "x p\r\n{\r\n protected get\r\n {\r\n return;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.WithAccessorDeclarations( Generator.PropertyDeclaration("p", Generator.IdentifierName("x")), Generator.SetAccessorDeclaration(Accessibility.Protected, new[] { Generator.ReturnStatement() })), "x p\r\n{\r\n protected set\r\n {\r\n return;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.WithAccessorDeclarations(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("x"))), "x this[t p] { }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.WithAccessorDeclarations(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("x")), Generator.GetAccessorDeclaration(Accessibility.Protected, new[] { Generator.ReturnStatement() })), "x this[t p]\r\n{\r\n protected get\r\n {\r\n return;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.WithAccessorDeclarations( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("x")), Generator.SetAccessorDeclaration(Accessibility.Protected, new[] { Generator.ReturnStatement() })), "x this[t p]\r\n{\r\n protected set\r\n {\r\n return;\r\n }\r\n}"); } [Fact] public void TestAccessorsOnSpecialProperties() { var root = SyntaxFactory.ParseCompilationUnit( @"class C { public int X { get; set; } = 100; public int Y => 300; }"); var x = Generator.GetMembers(root.Members[0])[0]; var y = Generator.GetMembers(root.Members[0])[1]; Assert.Equal(2, Generator.GetAccessors(x).Count); Assert.Equal(0, Generator.GetAccessors(y).Count); // adding accessors to expression value property will not succeed var y2 = Generator.AddAccessors(y, new[] { Generator.GetAccessor(x, DeclarationKind.GetAccessor) }); Assert.NotNull(y2); Assert.Equal(0, Generator.GetAccessors(y2).Count); } [Fact] public void TestAccessorsOnSpecialIndexers() { var root = SyntaxFactory.ParseCompilationUnit( @"class C { public int this[int p] { get { return p * 10; } set { } }; public int this[int p] => p * 10; }"); var x = Generator.GetMembers(root.Members[0])[0]; var y = Generator.GetMembers(root.Members[0])[1]; Assert.Equal(2, Generator.GetAccessors(x).Count); Assert.Equal(0, Generator.GetAccessors(y).Count); // adding accessors to expression value indexer will not succeed var y2 = Generator.AddAccessors(y, new[] { Generator.GetAccessor(x, DeclarationKind.GetAccessor) }); Assert.NotNull(y2); Assert.Equal(0, Generator.GetAccessors(y2).Count); } [Fact] public void TestExpressionsOnSpecialProperties() { // you can get/set expression from both expression value property and initialized properties var root = SyntaxFactory.ParseCompilationUnit( @"class C { public int X { get; set; } = 100; public int Y => 300; public int Z { get; set; } }"); var x = Generator.GetMembers(root.Members[0])[0]; var y = Generator.GetMembers(root.Members[0])[1]; var z = Generator.GetMembers(root.Members[0])[2]; Assert.NotNull(Generator.GetExpression(x)); Assert.NotNull(Generator.GetExpression(y)); Assert.Null(Generator.GetExpression(z)); Assert.Equal("100", Generator.GetExpression(x).ToString()); Assert.Equal("300", Generator.GetExpression(y).ToString()); Assert.Equal("500", Generator.GetExpression(Generator.WithExpression(x, Generator.LiteralExpression(500))).ToString()); Assert.Equal("500", Generator.GetExpression(Generator.WithExpression(y, Generator.LiteralExpression(500))).ToString()); Assert.Equal("500", Generator.GetExpression(Generator.WithExpression(z, Generator.LiteralExpression(500))).ToString()); } [Fact] public void TestExpressionsOnSpecialIndexers() { // you can get/set expression from both expression value property and initialized properties var root = SyntaxFactory.ParseCompilationUnit( @"class C { public int this[int p] { get { return p * 10; } set { } }; public int this[int p] => p * 10; }"); var x = Generator.GetMembers(root.Members[0])[0]; var y = Generator.GetMembers(root.Members[0])[1]; Assert.Null(Generator.GetExpression(x)); Assert.NotNull(Generator.GetExpression(y)); Assert.Equal("p * 10", Generator.GetExpression(y).ToString()); Assert.Null(Generator.GetExpression(Generator.WithExpression(x, Generator.LiteralExpression(500)))); Assert.Equal("500", Generator.GetExpression(Generator.WithExpression(y, Generator.LiteralExpression(500))).ToString()); } [Fact] public void TestGetStatements() { var stmts = new[] { // x = y; Generator.ExpressionStatement(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), // fn(arg); Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("fn"), Generator.IdentifierName("arg"))) }; Assert.Equal(0, Generator.GetStatements(Generator.MethodDeclaration("m")).Count); Assert.Equal(2, Generator.GetStatements(Generator.MethodDeclaration("m", statements: stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.ConstructorDeclaration()).Count); Assert.Equal(2, Generator.GetStatements(Generator.ConstructorDeclaration(statements: stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.VoidReturningLambdaExpression(new SyntaxNode[] { })).Count); Assert.Equal(2, Generator.GetStatements(Generator.VoidReturningLambdaExpression(stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.ValueReturningLambdaExpression(new SyntaxNode[] { })).Count); Assert.Equal(2, Generator.GetStatements(Generator.ValueReturningLambdaExpression(stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.IdentifierName("x")).Count); } [Fact] public void TestWithStatements() { var stmts = new[] { // x = y; Generator.ExpressionStatement(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), // fn(arg); Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("fn"), Generator.IdentifierName("arg"))) }; Assert.Equal(2, Generator.GetStatements(Generator.WithStatements(Generator.MethodDeclaration("m"), stmts)).Count); Assert.Equal(2, Generator.GetStatements(Generator.WithStatements(Generator.ConstructorDeclaration(), stmts)).Count); Assert.Equal(2, Generator.GetStatements(Generator.WithStatements(Generator.VoidReturningLambdaExpression(new SyntaxNode[] { }), stmts)).Count); Assert.Equal(2, Generator.GetStatements(Generator.WithStatements(Generator.ValueReturningLambdaExpression(new SyntaxNode[] { }), stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.WithStatements(Generator.IdentifierName("x"), stmts)).Count); } [Fact] public void TestGetAccessorStatements() { var stmts = new[] { // x = y; Generator.ExpressionStatement(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), // fn(arg); Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("fn"), Generator.IdentifierName("arg"))) }; var p = Generator.ParameterDeclaration("p", Generator.IdentifierName("t")); // get-accessor Assert.Equal(0, Generator.GetGetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetGetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), getAccessorStatements: stmts)).Count); Assert.Equal(0, Generator.GetGetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetGetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t"), getAccessorStatements: stmts)).Count); Assert.Equal(0, Generator.GetGetAccessorStatements(Generator.IdentifierName("x")).Count); // set-accessor Assert.Equal(0, Generator.GetSetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetSetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), setAccessorStatements: stmts)).Count); Assert.Equal(0, Generator.GetSetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetSetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t"), setAccessorStatements: stmts)).Count); Assert.Equal(0, Generator.GetSetAccessorStatements(Generator.IdentifierName("x")).Count); } [Fact] public void TestWithAccessorStatements() { var stmts = new[] { // x = y; Generator.ExpressionStatement(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), // fn(arg); Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("fn"), Generator.IdentifierName("arg"))) }; var p = Generator.ParameterDeclaration("p", Generator.IdentifierName("t")); // get-accessor Assert.Equal(2, Generator.GetGetAccessorStatements(Generator.WithGetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")), stmts)).Count); Assert.Equal(2, Generator.GetGetAccessorStatements(Generator.WithGetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t")), stmts)).Count); Assert.Equal(0, Generator.GetGetAccessorStatements(Generator.WithGetAccessorStatements(Generator.IdentifierName("x"), stmts)).Count); // set-accessor Assert.Equal(2, Generator.GetSetAccessorStatements(Generator.WithSetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")), stmts)).Count); Assert.Equal(2, Generator.GetSetAccessorStatements(Generator.WithSetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t")), stmts)).Count); Assert.Equal(0, Generator.GetSetAccessorStatements(Generator.WithSetAccessorStatements(Generator.IdentifierName("x"), stmts)).Count); } [Fact] public void TestGetBaseAndInterfaceTypes() { var classBI = SyntaxFactory.ParseCompilationUnit( @"class C : B, I { }").Members[0]; var baseListBI = Generator.GetBaseAndInterfaceTypes(classBI); Assert.NotNull(baseListBI); Assert.Equal(2, baseListBI.Count); Assert.Equal("B", baseListBI[0].ToString()); Assert.Equal("I", baseListBI[1].ToString()); var classB = SyntaxFactory.ParseCompilationUnit( @"class C : B { }").Members[0]; var baseListB = Generator.GetBaseAndInterfaceTypes(classB); Assert.NotNull(baseListB); Assert.Equal(1, baseListB.Count); Assert.Equal("B", baseListB[0].ToString()); var classN = SyntaxFactory.ParseCompilationUnit( @"class C { }").Members[0]; var baseListN = Generator.GetBaseAndInterfaceTypes(classN); Assert.NotNull(baseListN); Assert.Equal(0, baseListN.Count); } [Fact] public void TestRemoveBaseAndInterfaceTypes() { var classBI = SyntaxFactory.ParseCompilationUnit( @"class C : B, I { }").Members[0]; var baseListBI = Generator.GetBaseAndInterfaceTypes(classBI); Assert.NotNull(baseListBI); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNode(classBI, baseListBI[0]), @"class C : I { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNode(classBI, baseListBI[1]), @"class C : B { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(classBI, baseListBI), @"class C { }"); } [Fact] public void TestAddBaseType() { var classC = SyntaxFactory.ParseCompilationUnit( @"class C { }").Members[0]; var classCI = SyntaxFactory.ParseCompilationUnit( @"class C : I { }").Members[0]; var classCB = SyntaxFactory.ParseCompilationUnit( @"class C : B { }").Members[0]; VerifySyntax<ClassDeclarationSyntax>( Generator.AddBaseType(classC, Generator.IdentifierName("T")), @"class C : T { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.AddBaseType(classCI, Generator.IdentifierName("T")), @"class C : T, I { }"); // TODO: find way to avoid this VerifySyntax<ClassDeclarationSyntax>( Generator.AddBaseType(classCB, Generator.IdentifierName("T")), @"class C : T, B { }"); } [Fact] public void TestAddInterfaceTypes() { var classC = SyntaxFactory.ParseCompilationUnit( @"class C { }").Members[0]; var classCI = SyntaxFactory.ParseCompilationUnit( @"class C : I { }").Members[0]; var classCB = SyntaxFactory.ParseCompilationUnit( @"class C : B { }").Members[0]; VerifySyntax<ClassDeclarationSyntax>( Generator.AddInterfaceType(classC, Generator.IdentifierName("T")), @"class C : T { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.AddInterfaceType(classCI, Generator.IdentifierName("T")), @"class C : I, T { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.AddInterfaceType(classCB, Generator.IdentifierName("T")), @"class C : B, T { }"); } [Fact] public void TestMultiFieldDeclarations() { var comp = Compile( @"public class C { public static int X, Y, Z; }"); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var symbolX = (IFieldSymbol)symbolC.GetMembers("X").First(); var symbolY = (IFieldSymbol)symbolC.GetMembers("Y").First(); var symbolZ = (IFieldSymbol)symbolC.GetMembers("Z").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); var declX = Generator.GetDeclaration(symbolX.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); var declY = Generator.GetDeclaration(symbolY.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); var declZ = Generator.GetDeclaration(symbolZ.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(declX)); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(declY)); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(declZ)); Assert.NotNull(Generator.GetType(declX)); Assert.Equal("int", Generator.GetType(declX).ToString()); Assert.Equal("X", Generator.GetName(declX)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(declX)); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(declX)); Assert.NotNull(Generator.GetType(declY)); Assert.Equal("int", Generator.GetType(declY).ToString()); Assert.Equal("Y", Generator.GetName(declY)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(declY)); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(declY)); Assert.NotNull(Generator.GetType(declZ)); Assert.Equal("int", Generator.GetType(declZ).ToString()); Assert.Equal("Z", Generator.GetName(declZ)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(declZ)); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(declZ)); var xTypedT = Generator.WithType(declX, Generator.IdentifierName("T")); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xTypedT)); Assert.Equal(SyntaxKind.FieldDeclaration, xTypedT.Kind()); Assert.Equal("T", Generator.GetType(xTypedT).ToString()); var xNamedQ = Generator.WithName(declX, "Q"); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xNamedQ)); Assert.Equal(SyntaxKind.FieldDeclaration, xNamedQ.Kind()); Assert.Equal("Q", Generator.GetName(xNamedQ).ToString()); var xInitialized = Generator.WithExpression(declX, Generator.IdentifierName("e")); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xInitialized)); Assert.Equal(SyntaxKind.FieldDeclaration, xInitialized.Kind()); Assert.Equal("e", Generator.GetExpression(xInitialized).ToString()); var xPrivate = Generator.WithAccessibility(declX, Accessibility.Private); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xPrivate)); Assert.Equal(SyntaxKind.FieldDeclaration, xPrivate.Kind()); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(xPrivate)); var xReadOnly = Generator.WithModifiers(declX, DeclarationModifiers.ReadOnly); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xReadOnly)); Assert.Equal(SyntaxKind.FieldDeclaration, xReadOnly.Kind()); Assert.Equal(DeclarationModifiers.ReadOnly, Generator.GetModifiers(xReadOnly)); var xAttributed = Generator.AddAttributes(declX, Generator.Attribute("A")); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xAttributed)); Assert.Equal(SyntaxKind.FieldDeclaration, xAttributed.Kind()); Assert.Equal(1, Generator.GetAttributes(xAttributed).Count); Assert.Equal("[A]", Generator.GetAttributes(xAttributed)[0].ToString()); var membersC = Generator.GetMembers(declC); Assert.Equal(3, membersC.Count); Assert.Equal(declX, membersC[0]); Assert.Equal(declY, membersC[1]); Assert.Equal(declZ, membersC[2]); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public class C { T A; public static int X, Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertMembers(declC, 1, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public class C { public static int X; T A; public static int Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertMembers(declC, 2, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public class C { public static int X, Y; T A; public static int Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertMembers(declC, 3, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public class C { public static int X, Y, Z; T A; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("C", members: new[] { declX, declY }), @"class C { public static int X; public static int Y; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, xTypedT), @"public class C { public static T X; public static int Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declY, Generator.WithType(declY, Generator.IdentifierName("T"))), @"public class C { public static int X; public static T Y; public static int Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declZ, Generator.WithType(declZ, Generator.IdentifierName("T"))), @"public class C { public static int X, Y; public static T Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, Generator.WithAccessibility(declX, Accessibility.Private)), @"public class C { private static int X; public static int Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, Generator.WithModifiers(declX, DeclarationModifiers.None)), @"public class C { public int X; public static int Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, Generator.WithName(declX, "Q")), @"public class C { public static int Q, Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX.GetAncestorOrThis<VariableDeclaratorSyntax>(), SyntaxFactory.VariableDeclarator("Q")), @"public class C { public static int Q, Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, Generator.WithExpression(declX, Generator.IdentifierName("e"))), @"public class C { public static int X = e, Y, Z; }"); } [Theory, WorkItem(48789, "https://github.com/dotnet/roslyn/issues/48789")] [InlineData("record")] [InlineData("record class")] public void TestInsertMembersOnRecord_SemiColon(string typeKind) { var comp = Compile( $@"public {typeKind} C; "); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax<RecordDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), $@"public {typeKind} C {{ T A; }}"); } [Fact, WorkItem(48789, "https://github.com/dotnet/roslyn/issues/48789")] public void TestInsertMembersOnRecordStruct_SemiColon() { var src = @"public record struct C; "; var comp = CSharpCompilation.Create("test") .AddReferences(TestMetadata.Net451.mscorlib) .AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(src, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview))); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax<RecordDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public record struct C { T A; }"); } [Fact, WorkItem(48789, "https://github.com/dotnet/roslyn/issues/48789")] public void TestInsertMembersOnRecord_Braces() { var comp = Compile( @"public record C { } "); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax<RecordDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public record C { T A; }"); } [Fact, WorkItem(48789, "https://github.com/dotnet/roslyn/issues/48789")] public void TestInsertMembersOnRecord_BracesAndSemiColon() { var comp = Compile( @"public record C { }; "); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax<RecordDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public record C { T A; }"); } [Fact] public void TestMultiAttributeDeclarations() { var comp = Compile( @"[X, Y, Z] public class C { }"); var symbolC = comp.GlobalNamespace.GetMembers("C").First(); var declC = symbolC.DeclaringSyntaxReferences.First().GetSyntax(); var attrs = Generator.GetAttributes(declC); var attrX = attrs[0]; var attrY = attrs[1]; var attrZ = attrs[2]; Assert.Equal(3, attrs.Count); Assert.Equal("X", Generator.GetName(attrX)); Assert.Equal("Y", Generator.GetName(attrY)); Assert.Equal("Z", Generator.GetName(attrZ)); var xNamedQ = Generator.WithName(attrX, "Q"); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(xNamedQ)); Assert.Equal(SyntaxKind.AttributeList, xNamedQ.Kind()); Assert.Equal("[Q]", xNamedQ.ToString()); var xWithArg = Generator.AddAttributeArguments(attrX, new[] { Generator.AttributeArgument(Generator.IdentifierName("e")) }); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(xWithArg)); Assert.Equal(SyntaxKind.AttributeList, xWithArg.Kind()); Assert.Equal("[X(e)]", xWithArg.ToString()); // Inserting new attributes VerifySyntax<ClassDeclarationSyntax>( Generator.InsertAttributes(declC, 0, Generator.Attribute("A")), @"[A] [X, Y, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertAttributes(declC, 1, Generator.Attribute("A")), @"[X] [A] [Y, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertAttributes(declC, 2, Generator.Attribute("A")), @"[X, Y] [A] [Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertAttributes(declC, 3, Generator.Attribute("A")), @"[X, Y, Z] [A] public class C { }"); // Removing attributes VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrX }), @"[Y, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrY }), @"[X, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrZ }), @"[X, Y] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrX, attrY }), @"[Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrX, attrZ }), @"[Y] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrY, attrZ }), @"[X] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrX, attrY, attrZ }), @"public class C { }"); // Replacing attributes VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, attrX, Generator.Attribute("A")), @"[A, Y, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, attrY, Generator.Attribute("A")), @"[X, A, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, attrZ, Generator.Attribute("A")), @"[X, Y, A] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, attrX, Generator.AddAttributeArguments(attrX, new[] { Generator.AttributeArgument(Generator.IdentifierName("e")) })), @"[X(e), Y, Z] public class C { }"); } [Fact] public void TestMultiReturnAttributeDeclarations() { var comp = Compile( @"public class C { [return: X, Y, Z] public void M() { } }"); var symbolC = comp.GlobalNamespace.GetMembers("C").First(); var declC = symbolC.DeclaringSyntaxReferences.First().GetSyntax(); var declM = Generator.GetMembers(declC).First(); Assert.Equal(0, Generator.GetAttributes(declM).Count); var attrs = Generator.GetReturnAttributes(declM); Assert.Equal(3, attrs.Count); var attrX = attrs[0]; var attrY = attrs[1]; var attrZ = attrs[2]; Assert.Equal("X", Generator.GetName(attrX)); Assert.Equal("Y", Generator.GetName(attrY)); Assert.Equal("Z", Generator.GetName(attrZ)); var xNamedQ = Generator.WithName(attrX, "Q"); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(xNamedQ)); Assert.Equal(SyntaxKind.AttributeList, xNamedQ.Kind()); Assert.Equal("[Q]", xNamedQ.ToString()); var xWithArg = Generator.AddAttributeArguments(attrX, new[] { Generator.AttributeArgument(Generator.IdentifierName("e")) }); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(xWithArg)); Assert.Equal(SyntaxKind.AttributeList, xWithArg.Kind()); Assert.Equal("[X(e)]", xWithArg.ToString()); // Inserting new attributes VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 0, Generator.Attribute("A")), @"[return: A] [return: X, Y, Z] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 1, Generator.Attribute("A")), @"[return: X] [return: A] [return: Y, Z] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 2, Generator.Attribute("A")), @"[return: X, Y] [return: A] [return: Z] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 3, Generator.Attribute("A")), @"[return: X, Y, Z] [return: A] public void M() { }"); // replacing VerifySyntax<MethodDeclarationSyntax>( Generator.ReplaceNode(declM, attrX, Generator.Attribute("Q")), @"[return: Q, Y, Z] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.ReplaceNode(declM, attrX, Generator.AddAttributeArguments(attrX, new[] { Generator.AttributeArgument(Generator.IdentifierName("e")) })), @"[return: X(e), Y, Z] public void M() { }"); } [Fact] public void TestMixedAttributeDeclarations() { var comp = Compile( @"public class C { [X] [return: A] [Y, Z] [return: B, C, D] [P] public void M() { } }"); var symbolC = comp.GlobalNamespace.GetMembers("C").First(); var declC = symbolC.DeclaringSyntaxReferences.First().GetSyntax(); var declM = Generator.GetMembers(declC).First(); var attrs = Generator.GetAttributes(declM); Assert.Equal(4, attrs.Count); var attrX = attrs[0]; Assert.Equal("X", Generator.GetName(attrX)); Assert.Equal(SyntaxKind.AttributeList, attrX.Kind()); var attrY = attrs[1]; Assert.Equal("Y", Generator.GetName(attrY)); Assert.Equal(SyntaxKind.Attribute, attrY.Kind()); var attrZ = attrs[2]; Assert.Equal("Z", Generator.GetName(attrZ)); Assert.Equal(SyntaxKind.Attribute, attrZ.Kind()); var attrP = attrs[3]; Assert.Equal("P", Generator.GetName(attrP)); Assert.Equal(SyntaxKind.AttributeList, attrP.Kind()); var rattrs = Generator.GetReturnAttributes(declM); Assert.Equal(4, rattrs.Count); var attrA = rattrs[0]; Assert.Equal("A", Generator.GetName(attrA)); Assert.Equal(SyntaxKind.AttributeList, attrA.Kind()); var attrB = rattrs[1]; Assert.Equal("B", Generator.GetName(attrB)); Assert.Equal(SyntaxKind.Attribute, attrB.Kind()); var attrC = rattrs[2]; Assert.Equal("C", Generator.GetName(attrC)); Assert.Equal(SyntaxKind.Attribute, attrC.Kind()); var attrD = rattrs[3]; Assert.Equal("D", Generator.GetName(attrD)); Assert.Equal(SyntaxKind.Attribute, attrD.Kind()); // inserting VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 0, Generator.Attribute("Q")), @"[Q] [X] [return: A] [Y, Z] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 1, Generator.Attribute("Q")), @"[X] [return: A] [Q] [Y, Z] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 2, Generator.Attribute("Q")), @"[X] [return: A] [Y] [Q] [Z] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 3, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B, C, D] [Q] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 4, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B, C, D] [P] [Q] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 0, Generator.Attribute("Q")), @"[X] [return: Q] [return: A] [Y, Z] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 1, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: Q] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 2, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B] [return: Q] [return: C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 3, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B, C] [return: Q] [return: D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 4, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B, C, D] [return: Q] [P] public void M() { }"); } [WorkItem(293, "https://github.com/dotnet/roslyn/issues/293")] [Fact] [Trait(Traits.Feature, Traits.Features.Formatting)] public void IntroduceBaseList() { var text = @" public class C { } "; var expected = @" public class C : IDisposable { } "; var root = SyntaxFactory.ParseCompilationUnit(text); var decl = root.DescendantNodes().OfType<ClassDeclarationSyntax>().First(); var newDecl = Generator.AddInterfaceType(decl, Generator.IdentifierName("IDisposable")); var newRoot = root.ReplaceNode(decl, newDecl); var elasticOnlyFormatted = Formatter.Format(newRoot, SyntaxAnnotation.ElasticAnnotation, _workspace).ToFullString(); Assert.Equal(expected, elasticOnlyFormatted); } #endregion #region DeclarationModifiers [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestNamespaceModifiers() { TestModifiersAsync(DeclarationModifiers.None, @" [|namespace N1 { }|]"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestFileScopedNamespaceModifiers() { TestModifiersAsync(DeclarationModifiers.None, @" [|namespace N1;|]"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestClassModifiers1() { TestModifiersAsync(DeclarationModifiers.Static, @" [|static class C { }|]"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestMethodModifiers1() { TestModifiersAsync(DeclarationModifiers.Sealed | DeclarationModifiers.Override, @" class C { [|public sealed override void M() { }|] }"); } [Fact] public void TestAsyncMethodModifier() { TestModifiersAsync(DeclarationModifiers.Async, @" using System.Threading.Tasks; class C { [|public async Task DoAsync() { await Task.CompletedTask; }|] } "); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestPropertyModifiers1() { TestModifiersAsync(DeclarationModifiers.Virtual | DeclarationModifiers.ReadOnly, @" class C { [|public virtual int X => 0;|] }"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestFieldModifiers1() { TestModifiersAsync(DeclarationModifiers.Static, @" class C { public static int [|X|]; }"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestEvent1() { TestModifiersAsync(DeclarationModifiers.Virtual, @" class C { public virtual event System.Action [|X|]; }"); } private static void TestModifiersAsync(DeclarationModifiers modifiers, string markup) { MarkupTestFile.GetSpan(markup, out var code, out var span); var compilation = Compile(code); var tree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(tree); var root = tree.GetRoot(); var node = root.FindNode(span, getInnermostNodeForTie: true); var declaration = semanticModel.GetDeclaredSymbol(node); Assert.NotNull(declaration); Assert.Equal(modifiers, DeclarationModifiers.From(declaration)); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Editing { [UseExportProvider] public class SyntaxGeneratorTests { private readonly CSharpCompilation _emptyCompilation = CSharpCompilation.Create("empty", references: new[] { TestMetadata.Net451.mscorlib, TestMetadata.Net451.System }); private Workspace _workspace; private SyntaxGenerator _generator; public SyntaxGeneratorTests() { } private Workspace Workspace => _workspace ??= new AdhocWorkspace(); private SyntaxGenerator Generator => _generator ??= SyntaxGenerator.GetGenerator(Workspace, LanguageNames.CSharp); public static Compilation Compile(string code) { return CSharpCompilation.Create("test") .AddReferences(TestMetadata.Net451.mscorlib) .AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(code)); } private static void VerifySyntax<TSyntax>(SyntaxNode node, string expectedText) where TSyntax : SyntaxNode { Assert.IsAssignableFrom<TSyntax>(node); var normalized = node.NormalizeWhitespace().ToFullString(); Assert.Equal(expectedText, normalized); } private static void VerifySyntaxRaw<TSyntax>(SyntaxNode node, string expectedText) where TSyntax : SyntaxNode { Assert.IsAssignableFrom<TSyntax>(node); var normalized = node.ToFullString(); Assert.Equal(expectedText, normalized); } #region Expressions and Statements [Fact] public void TestLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1), "1"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1), "-1"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(int.MinValue), "global::System.Int32.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(int.MaxValue), "global::System.Int32.MaxValue"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0L), "0L"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1L), "1L"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1L), "-1L"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(long.MinValue), "global::System.Int64.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(long.MaxValue), "global::System.Int64.MaxValue"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0UL), "0UL"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1UL), "1UL"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(ulong.MinValue), "0UL"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(ulong.MaxValue), "global::System.UInt64.MaxValue"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.0f), "0F"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1.0f), "1F"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1.0f), "-1F"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.MinValue), "global::System.Single.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.MaxValue), "global::System.Single.MaxValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.Epsilon), "global::System.Single.Epsilon"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.NaN), "global::System.Single.NaN"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.NegativeInfinity), "global::System.Single.NegativeInfinity"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(float.PositiveInfinity), "global::System.Single.PositiveInfinity"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.0), "0D"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1.0), "1D"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1.0), "-1D"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.MinValue), "global::System.Double.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.MaxValue), "global::System.Double.MaxValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.Epsilon), "global::System.Double.Epsilon"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.NaN), "global::System.Double.NaN"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.NegativeInfinity), "global::System.Double.NegativeInfinity"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(double.PositiveInfinity), "global::System.Double.PositiveInfinity"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0m), "0M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.00m), "0.00M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1.00m), "1.00M"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression(-1.00m), "-1.00M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1.0000000000m), "1.0000000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.000000m), "0.000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0.0000000m), "0.0000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1000000000m), "1000000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(123456789.123456789m), "123456789.123456789M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1E-28m), "0.0000000000000000000000000001M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(0E-28m), "0.0000000000000000000000000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(1E-29m), "0.0000000000000000000000000000M"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(-1E-29m), "0.0000000000000000000000000000M"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(decimal.MinValue), "global::System.Decimal.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(decimal.MaxValue), "global::System.Decimal.MaxValue"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression('c'), "'c'"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression("str"), "\"str\""); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression("s\"t\"r"), "\"s\\\"t\\\"r\""); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(true), "true"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(false), "false"); } [Fact] public void TestShortLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((short)0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((short)1), "1"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression((short)-1), "-1"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(short.MinValue), "global::System.Int16.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(short.MaxValue), "global::System.Int16.MaxValue"); } [Fact] public void TestUshortLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((ushort)0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((ushort)1), "1"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(ushort.MinValue), "0"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(ushort.MaxValue), "global::System.UInt16.MaxValue"); } [Fact] public void TestSbyteLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((sbyte)0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((sbyte)1), "1"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LiteralExpression((sbyte)-1), "-1"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(sbyte.MinValue), "global::System.SByte.MinValue"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.LiteralExpression(sbyte.MaxValue), "global::System.SByte.MaxValue"); } [Fact] public void TestByteLiteralExpressions() { VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((byte)0), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression((byte)1), "1"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(byte.MinValue), "0"); VerifySyntax<LiteralExpressionSyntax>(Generator.LiteralExpression(byte.MaxValue), "255"); } [Fact] public void TestAttributeData() { VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { }", @"[MyAttribute]")), @"[global::MyAttribute]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(object value) { } }", @"[MyAttribute(null)]")), @"[global::MyAttribute(null)]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(int value) { } }", @"[MyAttribute(123)]")), @"[global::MyAttribute(123)]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(double value) { } }", @"[MyAttribute(12.3)]")), @"[global::MyAttribute(12.3)]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(string value) { } }", @"[MyAttribute(""value"")]")), @"[global::MyAttribute(""value"")]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public enum E { A, B, C } public class MyAttribute : Attribute { public MyAttribute(E value) { } }", @"[MyAttribute(E.A)]")), @"[global::MyAttribute(global::E.A)]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(Type value) { } }", @"[MyAttribute(typeof (MyAttribute))]")), @"[global::MyAttribute(typeof(global::MyAttribute))]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public MyAttribute(int[] values) { } }", @"[MyAttribute(new [] {1, 2, 3})]")), @"[global::MyAttribute(new[]{1, 2, 3})]"); VerifySyntax<AttributeListSyntax>(Generator.Attribute(GetAttributeData( @"using System; public class MyAttribute : Attribute { public int Value {get; set;} }", @"[MyAttribute(Value = 123)]")), @"[global::MyAttribute(Value = 123)]"); var attributes = Generator.GetAttributes(Generator.AddAttributes( Generator.NamespaceDeclaration("n"), Generator.Attribute("Attr"))); Assert.True(attributes.Count == 1); } private static AttributeData GetAttributeData(string decl, string use) { var compilation = Compile(decl + "\r\n" + use + "\r\nclass C { }"); var typeC = compilation.GlobalNamespace.GetMembers("C").First() as INamedTypeSymbol; return typeC.GetAttributes().First(); } [Fact] public void TestNameExpressions() { VerifySyntax<IdentifierNameSyntax>(Generator.IdentifierName("x"), "x"); VerifySyntax<QualifiedNameSyntax>(Generator.QualifiedName(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x.y"); VerifySyntax<QualifiedNameSyntax>(Generator.DottedName("x.y"), "x.y"); VerifySyntax<GenericNameSyntax>(Generator.GenericName("x", Generator.IdentifierName("y")), "x<y>"); VerifySyntax<GenericNameSyntax>(Generator.GenericName("x", Generator.IdentifierName("y"), Generator.IdentifierName("z")), "x<y, z>"); // convert identifier name into generic name VerifySyntax<GenericNameSyntax>(Generator.WithTypeArguments(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x<y>"); // convert qualified name into qualified generic name VerifySyntax<QualifiedNameSyntax>(Generator.WithTypeArguments(Generator.DottedName("x.y"), Generator.IdentifierName("z")), "x.y<z>"); // convert member access expression into generic member access expression VerifySyntax<MemberAccessExpressionSyntax>(Generator.WithTypeArguments(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x.y<z>"); // convert existing generic name into a different generic name var gname = Generator.WithTypeArguments(Generator.IdentifierName("x"), Generator.IdentifierName("y")); VerifySyntax<GenericNameSyntax>(gname, "x<y>"); VerifySyntax<GenericNameSyntax>(Generator.WithTypeArguments(gname, Generator.IdentifierName("z")), "x<z>"); } [Fact] public void TestTypeExpressions() { // these are all type syntax too VerifySyntax<TypeSyntax>(Generator.IdentifierName("x"), "x"); VerifySyntax<TypeSyntax>(Generator.QualifiedName(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x.y"); VerifySyntax<TypeSyntax>(Generator.DottedName("x.y"), "x.y"); VerifySyntax<TypeSyntax>(Generator.GenericName("x", Generator.IdentifierName("y")), "x<y>"); VerifySyntax<TypeSyntax>(Generator.GenericName("x", Generator.IdentifierName("y"), Generator.IdentifierName("z")), "x<y, z>"); VerifySyntax<TypeSyntax>(Generator.ArrayTypeExpression(Generator.IdentifierName("x")), "x[]"); VerifySyntax<TypeSyntax>(Generator.ArrayTypeExpression(Generator.ArrayTypeExpression(Generator.IdentifierName("x"))), "x[][]"); VerifySyntax<TypeSyntax>(Generator.NullableTypeExpression(Generator.IdentifierName("x")), "x?"); VerifySyntax<TypeSyntax>(Generator.NullableTypeExpression(Generator.NullableTypeExpression(Generator.IdentifierName("x"))), "x?"); var intType = _emptyCompilation.GetSpecialType(SpecialType.System_Int32); VerifySyntax<TupleElementSyntax>(Generator.TupleElementExpression(Generator.IdentifierName("x")), "x"); VerifySyntax<TupleElementSyntax>(Generator.TupleElementExpression(Generator.IdentifierName("x"), "y"), "x y"); VerifySyntax<TupleElementSyntax>(Generator.TupleElementExpression(intType), "global::System.Int32"); VerifySyntax<TupleElementSyntax>(Generator.TupleElementExpression(intType, "y"), "global::System.Int32 y"); VerifySyntax<TypeSyntax>(Generator.TupleTypeExpression(Generator.TupleElementExpression(Generator.IdentifierName("x")), Generator.TupleElementExpression(Generator.IdentifierName("y"))), "(x, y)"); VerifySyntax<TypeSyntax>(Generator.TupleTypeExpression(new[] { intType, intType }), "(global::System.Int32, global::System.Int32)"); VerifySyntax<TypeSyntax>(Generator.TupleTypeExpression(new[] { intType, intType }, new[] { "x", "y" }), "(global::System.Int32 x, global::System.Int32 y)"); } [Fact] public void TestSpecialTypeExpression() { VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Byte), "byte"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_SByte), "sbyte"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Int16), "short"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_UInt16), "ushort"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Int32), "int"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_UInt32), "uint"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Int64), "long"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_UInt64), "ulong"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Single), "float"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Double), "double"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Char), "char"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_String), "string"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Object), "object"); VerifySyntax<TypeSyntax>(Generator.TypeExpression(SpecialType.System_Decimal), "decimal"); } [Fact] public void TestSymbolTypeExpressions() { var genericType = _emptyCompilation.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T); VerifySyntax<QualifiedNameSyntax>(Generator.TypeExpression(genericType), "global::System.Collections.Generic.IEnumerable<T>"); var arrayType = _emptyCompilation.CreateArrayTypeSymbol(_emptyCompilation.GetSpecialType(SpecialType.System_Int32)); VerifySyntax<ArrayTypeSyntax>(Generator.TypeExpression(arrayType), "global::System.Int32[]"); } [Fact] public void TestMathAndLogicExpressions() { VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.NegateExpression(Generator.IdentifierName("x")), "-(x)"); VerifySyntax<BinaryExpressionSyntax>(Generator.AddExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) + (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.SubtractExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) - (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.MultiplyExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) * (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.DivideExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) / (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.ModuloExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) % (y)"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.BitwiseNotExpression(Generator.IdentifierName("x")), "~(x)"); VerifySyntax<BinaryExpressionSyntax>(Generator.BitwiseAndExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) & (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.BitwiseOrExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) | (y)"); VerifySyntax<PrefixUnaryExpressionSyntax>(Generator.LogicalNotExpression(Generator.IdentifierName("x")), "!(x)"); VerifySyntax<BinaryExpressionSyntax>(Generator.LogicalAndExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) && (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.LogicalOrExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) || (y)"); } [Fact] public void TestEqualityAndInequalityExpressions() { VerifySyntax<BinaryExpressionSyntax>(Generator.ReferenceEqualsExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) == (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.ValueEqualsExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) == (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.ReferenceNotEqualsExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) != (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.ValueNotEqualsExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) != (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.LessThanExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) < (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.LessThanOrEqualExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) <= (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.GreaterThanExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) > (y)"); VerifySyntax<BinaryExpressionSyntax>(Generator.GreaterThanOrEqualExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) >= (y)"); } [Fact] public void TestConditionalExpressions() { VerifySyntax<BinaryExpressionSyntax>(Generator.CoalesceExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) ?? (y)"); VerifySyntax<ConditionalExpressionSyntax>(Generator.ConditionalExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"), Generator.IdentifierName("z")), "(x) ? (y) : (z)"); } [Fact] public void TestMemberAccessExpressions() { VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x.y"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.IdentifierName("x"), "y"), "x.y"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x.y.z"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x(y).z"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x[y].z"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.AddExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "((x) + (y)).z"); VerifySyntax<MemberAccessExpressionSyntax>(Generator.MemberAccessExpression(Generator.NegateExpression(Generator.IdentifierName("x")), Generator.IdentifierName("y")), "(-(x)).y"); } [Fact] public void TestArrayCreationExpressions() { VerifySyntax<ArrayCreationExpressionSyntax>( Generator.ArrayCreationExpression(Generator.IdentifierName("x"), Generator.LiteralExpression(10)), "new x[10]"); VerifySyntax<ArrayCreationExpressionSyntax>( Generator.ArrayCreationExpression(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y"), Generator.IdentifierName("z") }), "new x[]{y, z}"); } [Fact] public void TestObjectCreationExpressions() { VerifySyntax<ObjectCreationExpressionSyntax>( Generator.ObjectCreationExpression(Generator.IdentifierName("x")), "new x()"); VerifySyntax<ObjectCreationExpressionSyntax>( Generator.ObjectCreationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "new x(y)"); var intType = _emptyCompilation.GetSpecialType(SpecialType.System_Int32); var listType = _emptyCompilation.GetTypeByMetadataName("System.Collections.Generic.List`1"); var listOfIntType = listType.Construct(intType); VerifySyntax<ObjectCreationExpressionSyntax>( Generator.ObjectCreationExpression(listOfIntType, Generator.IdentifierName("y")), "new global::System.Collections.Generic.List<global::System.Int32>(y)"); // should this be 'int' or if not shouldn't it have global::? } [Fact] public void TestElementAccessExpressions() { VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x[y]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"), Generator.IdentifierName("z")), "x[y, z]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x.y[z]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x[y][z]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "x(y)[z]"); VerifySyntax<ElementAccessExpressionSyntax>( Generator.ElementAccessExpression(Generator.AddExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), Generator.IdentifierName("z")), "((x) + (y))[z]"); } [Fact] public void TestCastAndConvertExpressions() { VerifySyntax<CastExpressionSyntax>(Generator.CastExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x)(y)"); VerifySyntax<CastExpressionSyntax>(Generator.ConvertExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x)(y)"); } [Fact] public void TestIsAndAsExpressions() { VerifySyntax<BinaryExpressionSyntax>(Generator.IsTypeExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) is y"); VerifySyntax<BinaryExpressionSyntax>(Generator.TryCastExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "(x) as y"); VerifySyntax<TypeOfExpressionSyntax>(Generator.TypeOfExpression(Generator.IdentifierName("x")), "typeof(x)"); } [Fact] public void TestInvocationExpressions() { // without explicit arguments VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x")), "x()"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x(y)"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"), Generator.IdentifierName("z")), "x(y, z)"); // using explicit arguments VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.Argument(Generator.IdentifierName("y"))), "x(y)"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.Argument(RefKind.Ref, Generator.IdentifierName("y"))), "x(ref y)"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.Argument(RefKind.Out, Generator.IdentifierName("y"))), "x(out y)"); // auto parenthesizing VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.MemberAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), "x.y()"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.ElementAccessExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), "x[y]()"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.InvocationExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), "x(y)()"); VerifySyntax<InvocationExpressionSyntax>(Generator.InvocationExpression(Generator.AddExpression(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), "((x) + (y))()"); } [Fact] public void TestAssignmentStatement() => VerifySyntax<AssignmentExpressionSyntax>(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y")), "x = (y)"); [Fact] public void TestExpressionStatement() { VerifySyntax<ExpressionStatementSyntax>(Generator.ExpressionStatement(Generator.IdentifierName("x")), "x;"); VerifySyntax<ExpressionStatementSyntax>(Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("x"))), "x();"); } [Fact] public void TestLocalDeclarationStatements() { VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "y"), "x y;"); VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "y", Generator.IdentifierName("z")), "x y = z;"); VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "y", isConst: true), "const x y;"); VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "y", Generator.IdentifierName("z"), isConst: true), "const x y = z;"); VerifySyntax<LocalDeclarationStatementSyntax>(Generator.LocalDeclarationStatement("y", Generator.IdentifierName("z")), "var y = z;"); } [Fact] public void TestAddHandlerExpressions() { VerifySyntax<AssignmentExpressionSyntax>( Generator.AddEventHandler(Generator.IdentifierName("@event"), Generator.IdentifierName("handler")), "@event += (handler)"); } [Fact] public void TestSubtractHandlerExpressions() { VerifySyntax<AssignmentExpressionSyntax>( Generator.RemoveEventHandler(Generator.IdentifierName("@event"), Generator.IdentifierName("handler")), "@event -= (handler)"); } [Fact] public void TestAwaitExpressions() => VerifySyntax<AwaitExpressionSyntax>(Generator.AwaitExpression(Generator.IdentifierName("x")), "await x"); [Fact] public void TestNameOfExpressions() => VerifySyntax<InvocationExpressionSyntax>(Generator.NameOfExpression(Generator.IdentifierName("x")), "nameof(x)"); [Fact] public void TestTupleExpression() { VerifySyntax<TupleExpressionSyntax>(Generator.TupleExpression( new[] { Generator.IdentifierName("x"), Generator.IdentifierName("y") }), "(x, y)"); VerifySyntax<TupleExpressionSyntax>(Generator.TupleExpression( new[] { Generator.Argument("goo", RefKind.None, Generator.IdentifierName("x")), Generator.Argument("bar", RefKind.None, Generator.IdentifierName("y")) }), "(goo: x, bar: y)"); } [Fact] public void TestReturnStatements() { VerifySyntax<ReturnStatementSyntax>(Generator.ReturnStatement(), "return;"); VerifySyntax<ReturnStatementSyntax>(Generator.ReturnStatement(Generator.IdentifierName("x")), "return x;"); } [Fact] public void TestYieldReturnStatements() { VerifySyntax<YieldStatementSyntax>(Generator.YieldReturnStatement(Generator.LiteralExpression(1)), "yield return 1;"); VerifySyntax<YieldStatementSyntax>(Generator.YieldReturnStatement(Generator.IdentifierName("x")), "yield return x;"); } [Fact] public void TestThrowStatements() { VerifySyntax<ThrowStatementSyntax>(Generator.ThrowStatement(), "throw;"); VerifySyntax<ThrowStatementSyntax>(Generator.ThrowStatement(Generator.IdentifierName("x")), "throw x;"); } [Fact] public void TestIfStatements() { VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { }), "if (x)\r\n{\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { }, new SyntaxNode[] { }), "if (x)\r\n{\r\n}\r\nelse\r\n{\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y") }), "if (x)\r\n{\r\n y;\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y") }, new SyntaxNode[] { Generator.IdentifierName("z") }), "if (x)\r\n{\r\n y;\r\n}\r\nelse\r\n{\r\n z;\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y") }, Generator.IfStatement(Generator.IdentifierName("p"), new SyntaxNode[] { Generator.IdentifierName("q") })), "if (x)\r\n{\r\n y;\r\n}\r\nelse if (p)\r\n{\r\n q;\r\n}"); VerifySyntax<IfStatementSyntax>( Generator.IfStatement(Generator.IdentifierName("x"), new SyntaxNode[] { Generator.IdentifierName("y") }, Generator.IfStatement(Generator.IdentifierName("p"), new SyntaxNode[] { Generator.IdentifierName("q") }, Generator.IdentifierName("z"))), "if (x)\r\n{\r\n y;\r\n}\r\nelse if (p)\r\n{\r\n q;\r\n}\r\nelse\r\n{\r\n z;\r\n}"); } [Fact] public void TestSwitchStatements() { VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") })), "switch (x)\r\n{\r\n case y:\r\n z;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection( new[] { Generator.IdentifierName("y"), Generator.IdentifierName("p"), Generator.IdentifierName("q") }, new[] { Generator.IdentifierName("z") })), "switch (x)\r\n{\r\n case y:\r\n case p:\r\n case q:\r\n z;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") }), Generator.SwitchSection(Generator.IdentifierName("a"), new[] { Generator.IdentifierName("b") })), "switch (x)\r\n{\r\n case y:\r\n z;\r\n case a:\r\n b;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") }), Generator.DefaultSwitchSection( new[] { Generator.IdentifierName("b") })), "switch (x)\r\n{\r\n case y:\r\n z;\r\n default:\r\n b;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.IdentifierName("x"), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.ExitSwitchStatement() })), "switch (x)\r\n{\r\n case y:\r\n break;\r\n}"); VerifySyntax<SwitchStatementSyntax>( Generator.SwitchStatement(Generator.TupleExpression(new[] { Generator.IdentifierName("x1"), Generator.IdentifierName("x2") }), Generator.SwitchSection(Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") })), "switch (x1, x2)\r\n{\r\n case y:\r\n z;\r\n}"); } [Fact] public void TestUsingStatements() { VerifySyntax<UsingStatementSyntax>( Generator.UsingStatement(Generator.IdentifierName("x"), new[] { Generator.IdentifierName("y") }), "using (x)\r\n{\r\n y;\r\n}"); VerifySyntax<UsingStatementSyntax>( Generator.UsingStatement("x", Generator.IdentifierName("y"), new[] { Generator.IdentifierName("z") }), "using (var x = y)\r\n{\r\n z;\r\n}"); VerifySyntax<UsingStatementSyntax>( Generator.UsingStatement(Generator.IdentifierName("x"), "y", Generator.IdentifierName("z"), new[] { Generator.IdentifierName("q") }), "using (x y = z)\r\n{\r\n q;\r\n}"); } [Fact] public void TestLockStatements() { VerifySyntax<LockStatementSyntax>( Generator.LockStatement(Generator.IdentifierName("x"), new[] { Generator.IdentifierName("y") }), "lock (x)\r\n{\r\n y;\r\n}"); } [Fact] public void TestTryCatchStatements() { VerifySyntax<TryStatementSyntax>( Generator.TryCatchStatement( new[] { Generator.IdentifierName("x") }, Generator.CatchClause(Generator.IdentifierName("y"), "z", new[] { Generator.IdentifierName("a") })), "try\r\n{\r\n x;\r\n}\r\ncatch (y z)\r\n{\r\n a;\r\n}"); VerifySyntax<TryStatementSyntax>( Generator.TryCatchStatement( new[] { Generator.IdentifierName("s") }, Generator.CatchClause(Generator.IdentifierName("x"), "y", new[] { Generator.IdentifierName("z") }), Generator.CatchClause(Generator.IdentifierName("a"), "b", new[] { Generator.IdentifierName("c") })), "try\r\n{\r\n s;\r\n}\r\ncatch (x y)\r\n{\r\n z;\r\n}\r\ncatch (a b)\r\n{\r\n c;\r\n}"); VerifySyntax<TryStatementSyntax>( Generator.TryCatchStatement( new[] { Generator.IdentifierName("s") }, new[] { Generator.CatchClause(Generator.IdentifierName("x"), "y", new[] { Generator.IdentifierName("z") }) }, new[] { Generator.IdentifierName("a") }), "try\r\n{\r\n s;\r\n}\r\ncatch (x y)\r\n{\r\n z;\r\n}\r\nfinally\r\n{\r\n a;\r\n}"); VerifySyntax<TryStatementSyntax>( Generator.TryFinallyStatement( new[] { Generator.IdentifierName("x") }, new[] { Generator.IdentifierName("a") }), "try\r\n{\r\n x;\r\n}\r\nfinally\r\n{\r\n a;\r\n}"); } [Fact] public void TestWhileStatements() { VerifySyntax<WhileStatementSyntax>( Generator.WhileStatement(Generator.IdentifierName("x"), new[] { Generator.IdentifierName("y") }), "while (x)\r\n{\r\n y;\r\n}"); VerifySyntax<WhileStatementSyntax>( Generator.WhileStatement(Generator.IdentifierName("x"), null), "while (x)\r\n{\r\n}"); } [Fact] public void TestLambdaExpressions() { VerifySyntax<SimpleLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression("x", Generator.IdentifierName("y")), "x => y"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new[] { Generator.LambdaParameter("x"), Generator.LambdaParameter("y") }, Generator.IdentifierName("z")), "(x, y) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new SyntaxNode[] { }, Generator.IdentifierName("y")), "() => y"); VerifySyntax<SimpleLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression("x", Generator.IdentifierName("y")), "x => y"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new[] { Generator.LambdaParameter("x"), Generator.LambdaParameter("y") }, Generator.IdentifierName("z")), "(x, y) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new SyntaxNode[] { }, Generator.IdentifierName("y")), "() => y"); VerifySyntax<SimpleLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression("x", new[] { Generator.ReturnStatement(Generator.IdentifierName("y")) }), "x =>\r\n{\r\n return y;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new[] { Generator.LambdaParameter("x"), Generator.LambdaParameter("y") }, new[] { Generator.ReturnStatement(Generator.IdentifierName("z")) }), "(x, y) =>\r\n{\r\n return z;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new SyntaxNode[] { }, new[] { Generator.ReturnStatement(Generator.IdentifierName("y")) }), "() =>\r\n{\r\n return y;\r\n}"); VerifySyntax<SimpleLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression("x", new[] { Generator.IdentifierName("y") }), "x =>\r\n{\r\n y;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new[] { Generator.LambdaParameter("x"), Generator.LambdaParameter("y") }, new[] { Generator.IdentifierName("z") }), "(x, y) =>\r\n{\r\n z;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new SyntaxNode[] { }, new[] { Generator.IdentifierName("y") }), "() =>\r\n{\r\n y;\r\n}"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new[] { Generator.LambdaParameter("x", Generator.IdentifierName("y")) }, Generator.IdentifierName("z")), "(y x) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.ValueReturningLambdaExpression(new[] { Generator.LambdaParameter("x", Generator.IdentifierName("y")), Generator.LambdaParameter("a", Generator.IdentifierName("b")) }, Generator.IdentifierName("z")), "(y x, b a) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new[] { Generator.LambdaParameter("x", Generator.IdentifierName("y")) }, Generator.IdentifierName("z")), "(y x) => z"); VerifySyntax<ParenthesizedLambdaExpressionSyntax>( Generator.VoidReturningLambdaExpression(new[] { Generator.LambdaParameter("x", Generator.IdentifierName("y")), Generator.LambdaParameter("a", Generator.IdentifierName("b")) }, Generator.IdentifierName("z")), "(y x, b a) => z"); } #endregion #region Declarations [Fact] public void TestFieldDeclarations() { VerifySyntax<FieldDeclarationSyntax>( Generator.FieldDeclaration("fld", Generator.TypeExpression(SpecialType.System_Int32)), "int fld;"); VerifySyntax<FieldDeclarationSyntax>( Generator.FieldDeclaration("fld", Generator.TypeExpression(SpecialType.System_Int32), initializer: Generator.LiteralExpression(0)), "int fld = 0;"); VerifySyntax<FieldDeclarationSyntax>( Generator.FieldDeclaration("fld", Generator.TypeExpression(SpecialType.System_Int32), accessibility: Accessibility.Public), "public int fld;"); VerifySyntax<FieldDeclarationSyntax>( Generator.FieldDeclaration("fld", Generator.TypeExpression(SpecialType.System_Int32), accessibility: Accessibility.NotApplicable, modifiers: DeclarationModifiers.Static | DeclarationModifiers.ReadOnly), "static readonly int fld;"); } [Fact] public void TestMethodDeclarations() { VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m"), "void m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", typeParameters: new[] { "x", "y" }), "void m<x, y>()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x")), "x m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x"), statements: new[] { Generator.IdentifierName("y") }), "x m()\r\n{\r\n y;\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", parameters: new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, returnType: Generator.IdentifierName("x")), "x m(y z)\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", parameters: new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y"), Generator.IdentifierName("a")) }, returnType: Generator.IdentifierName("x")), "x m(y z = a)\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x"), accessibility: Accessibility.Public), "public x m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Abstract), "public abstract x m();"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Partial), "partial void m();"); VerifySyntax<MethodDeclarationSyntax>( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Partial, statements: new[] { Generator.IdentifierName("y") }), "partial void m()\r\n{\r\n y;\r\n}"); } [Fact] public void TestOperatorDeclaration() { var parameterTypes = new[] { _emptyCompilation.GetSpecialType(SpecialType.System_Int32), _emptyCompilation.GetSpecialType(SpecialType.System_String) }; var parameters = parameterTypes.Select((t, i) => Generator.ParameterDeclaration("p" + i, Generator.TypeExpression(t))).ToList(); var returnType = Generator.TypeExpression(SpecialType.System_Boolean); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Addition, parameters, returnType), "bool operator +(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.BitwiseAnd, parameters, returnType), "bool operator &(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.BitwiseOr, parameters, returnType), "bool operator |(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Decrement, parameters, returnType), "bool operator --(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Division, parameters, returnType), "bool operator /(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Equality, parameters, returnType), "bool operator ==(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.ExclusiveOr, parameters, returnType), "bool operator ^(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.False, parameters, returnType), "bool operator false (global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.GreaterThan, parameters, returnType), "bool operator>(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.GreaterThanOrEqual, parameters, returnType), "bool operator >=(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Increment, parameters, returnType), "bool operator ++(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Inequality, parameters, returnType), "bool operator !=(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.LeftShift, parameters, returnType), "bool operator <<(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.LessThan, parameters, returnType), "bool operator <(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.LessThanOrEqual, parameters, returnType), "bool operator <=(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.LogicalNot, parameters, returnType), "bool operator !(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Modulus, parameters, returnType), "bool operator %(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Multiply, parameters, returnType), "bool operator *(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.OnesComplement, parameters, returnType), "bool operator ~(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.RightShift, parameters, returnType), "bool operator >>(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.Subtraction, parameters, returnType), "bool operator -(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.True, parameters, returnType), "bool operator true (global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.UnaryNegation, parameters, returnType), "bool operator -(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<OperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.UnaryPlus, parameters, returnType), "bool operator +(global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); // Conversion operators VerifySyntax<ConversionOperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.ImplicitConversion, parameters, returnType), "implicit operator bool (global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); VerifySyntax<ConversionOperatorDeclarationSyntax>( Generator.OperatorDeclaration(OperatorKind.ExplicitConversion, parameters, returnType), "explicit operator bool (global::System.Int32 p0, global::System.String p1)\r\n{\r\n}"); } [Fact] public void TestConstructorDeclaration() { VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration(), "ctor()\r\n{\r\n}"); VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration("c"), "c()\r\n{\r\n}"); VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration("c", accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Static), "public static c()\r\n{\r\n}"); VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration("c", new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }), "c(t p)\r\n{\r\n}"); VerifySyntax<ConstructorDeclarationSyntax>( Generator.ConstructorDeclaration("c", parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, baseConstructorArguments: new[] { Generator.IdentifierName("p") }), "c(t p) : base(p)\r\n{\r\n}"); } [Fact] public void TestPropertyDeclarations() { VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract | DeclarationModifiers.ReadOnly), "abstract x p { get; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract | DeclarationModifiers.WriteOnly), "abstract x p { set; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly), "x p { get; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly, getAccessorStatements: Array.Empty<SyntaxNode>()), "x p\r\n{\r\n get\r\n {\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly), "x p { set; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly, setAccessorStatements: Array.Empty<SyntaxNode>()), "x p\r\n{\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract), "abstract x p { get; set; }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly, getAccessorStatements: new[] { Generator.IdentifierName("y") }), "x p\r\n{\r\n get\r\n {\r\n y;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly, setAccessorStatements: new[] { Generator.IdentifierName("y") }), "x p\r\n{\r\n set\r\n {\r\n y;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), setAccessorStatements: new[] { Generator.IdentifierName("y") }), "x p\r\n{\r\n get;\r\n set\r\n {\r\n y;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), getAccessorStatements: Array.Empty<SyntaxNode>(), setAccessorStatements: new[] { Generator.IdentifierName("y") }), "x p\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n y;\r\n }\r\n}"); } [Fact] public void TestIndexerDeclarations() { VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract | DeclarationModifiers.ReadOnly), "abstract x this[y z] { get; }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract | DeclarationModifiers.WriteOnly), "abstract x this[y z] { set; }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract), "abstract x this[y z] { get; set; }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly), "x this[y z]\r\n{\r\n get\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly), "x this[y z]\r\n{\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.ReadOnly, getAccessorStatements: new[] { Generator.IdentifierName("a") }), "x this[y z]\r\n{\r\n get\r\n {\r\n a;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.WriteOnly, setAccessorStatements: new[] { Generator.IdentifierName("a") }), "x this[y z]\r\n{\r\n set\r\n {\r\n a;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x")), "x this[y z]\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), setAccessorStatements: new[] { Generator.IdentifierName("a") }), "x this[y z]\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n a;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), getAccessorStatements: new[] { Generator.IdentifierName("a") }, setAccessorStatements: new[] { Generator.IdentifierName("b") }), "x this[y z]\r\n{\r\n get\r\n {\r\n a;\r\n }\r\n\r\n set\r\n {\r\n b;\r\n }\r\n}"); } [Fact] public void TestEventFieldDeclarations() { VerifySyntax<EventFieldDeclarationSyntax>( Generator.EventDeclaration("ef", Generator.IdentifierName("t")), "event t ef;"); VerifySyntax<EventFieldDeclarationSyntax>( Generator.EventDeclaration("ef", Generator.IdentifierName("t"), accessibility: Accessibility.Public), "public event t ef;"); VerifySyntax<EventFieldDeclarationSyntax>( Generator.EventDeclaration("ef", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Static), "static event t ef;"); } [Fact] public void TestEventPropertyDeclarations() { VerifySyntax<EventDeclarationSyntax>( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), "abstract event t ep { add; remove; }"); VerifySyntax<EventDeclarationSyntax>( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Abstract), "public abstract event t ep { add; remove; }"); VerifySyntax<EventDeclarationSyntax>( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t")), "event t ep\r\n{\r\n add\r\n {\r\n }\r\n\r\n remove\r\n {\r\n }\r\n}"); VerifySyntax<EventDeclarationSyntax>( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), addAccessorStatements: new[] { Generator.IdentifierName("s") }, removeAccessorStatements: new[] { Generator.IdentifierName("s2") }), "event t ep\r\n{\r\n add\r\n {\r\n s;\r\n }\r\n\r\n remove\r\n {\r\n s2;\r\n }\r\n}"); } [Fact] public void TestAsPublicInterfaceImplementation() { VerifySyntax<MethodDeclarationSyntax>( Generator.AsPublicInterfaceImplementation( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "public t m()\r\n{\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.AsPublicInterfaceImplementation( Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Private, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "public t p\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.AsPublicInterfaceImplementation( Generator.IndexerDeclaration(parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("a")) }, type: Generator.IdentifierName("t"), accessibility: Accessibility.Internal, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "public t this[a p]\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); // convert private to public var pim = Generator.AsPrivateInterfaceImplementation( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), accessibility: Accessibility.Private, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")); VerifySyntax<MethodDeclarationSyntax>( Generator.AsPublicInterfaceImplementation(pim, Generator.IdentifierName("i2")), "public t m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.AsPublicInterfaceImplementation(pim, Generator.IdentifierName("i2"), "m2"), "public t m2()\r\n{\r\n}"); } [Fact] public void TestAsPrivateInterfaceImplementation() { VerifySyntax<MethodDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), accessibility: Accessibility.Private, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "t i.m()\r\n{\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation( Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Internal, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "t i.p\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation( Generator.IndexerDeclaration(parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("a")) }, type: Generator.IdentifierName("t"), accessibility: Accessibility.Protected, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "t i.this[a p]\r\n{\r\n get\r\n {\r\n }\r\n\r\n set\r\n {\r\n }\r\n}"); VerifySyntax<EventDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")), "event t i.ep\r\n{\r\n add\r\n {\r\n }\r\n\r\n remove\r\n {\r\n }\r\n}"); // convert public to private var pim = Generator.AsPublicInterfaceImplementation( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), accessibility: Accessibility.Private, modifiers: DeclarationModifiers.Abstract), Generator.IdentifierName("i")); VerifySyntax<MethodDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation(pim, Generator.IdentifierName("i2")), "t i2.m()\r\n{\r\n}"); VerifySyntax<MethodDeclarationSyntax>( Generator.AsPrivateInterfaceImplementation(pim, Generator.IdentifierName("i2"), "m2"), "t i2.m2()\r\n{\r\n}"); } [WorkItem(3928, "https://github.com/dotnet/roslyn/issues/3928")] [Fact] public void TestAsPrivateInterfaceImplementationRemovesConstraints() { var code = @" public interface IFace { void Method<T>() where T : class; }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var iface = cu.Members[0]; var method = Generator.GetMembers(iface)[0]; var privateMethod = Generator.AsPrivateInterfaceImplementation(method, Generator.IdentifierName("IFace")); VerifySyntax<MethodDeclarationSyntax>( privateMethod, "void IFace.Method<T>()\r\n{\r\n}"); } [Fact] public void TestClassDeclarations() { VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c"), "class c\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", typeParameters: new[] { "x", "y" }), "class c<x, y>\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", baseType: Generator.IdentifierName("x")), "class c : x\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", interfaceTypes: new[] { Generator.IdentifierName("x") }), "class c : x\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", baseType: Generator.IdentifierName("x"), interfaceTypes: new[] { Generator.IdentifierName("y") }), "class c : x, y\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", interfaceTypes: new SyntaxNode[] { }), "class c\r\n{\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", members: new[] { Generator.FieldDeclaration("y", type: Generator.IdentifierName("x")) }), "class c\r\n{\r\n x y;\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", members: new[] { Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t")) }), "class c\r\n{\r\n t m()\r\n {\r\n }\r\n}"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("c", members: new[] { Generator.ConstructorDeclaration() }), "class c\r\n{\r\n c()\r\n {\r\n }\r\n}"); } [Fact] public void TestStructDeclarations() { VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s"), "struct s\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", typeParameters: new[] { "x", "y" }), "struct s<x, y>\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", interfaceTypes: new[] { Generator.IdentifierName("x") }), "struct s : x\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", interfaceTypes: new[] { Generator.IdentifierName("x"), Generator.IdentifierName("y") }), "struct s : x, y\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", interfaceTypes: new SyntaxNode[] { }), "struct s\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", members: new[] { Generator.FieldDeclaration("y", Generator.IdentifierName("x")) }), "struct s\r\n{\r\n x y;\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t")) }), "struct s\r\n{\r\n t m()\r\n {\r\n }\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.StructDeclaration("s", members: new[] { Generator.ConstructorDeclaration("xxx") }), "struct s\r\n{\r\n s()\r\n {\r\n }\r\n}"); } [Fact] public void TestInterfaceDeclarations() { VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i"), "interface i\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", typeParameters: new[] { "x", "y" }), "interface i<x, y>\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", interfaceTypes: new[] { Generator.IdentifierName("a") }), "interface i : a\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", interfaceTypes: new[] { Generator.IdentifierName("a"), Generator.IdentifierName("b") }), "interface i : a, b\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", interfaceTypes: new SyntaxNode[] { }), "interface i\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Sealed) }), "interface i\r\n{\r\n t m();\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Sealed) }), "interface i\r\n{\r\n t p { get; set; }\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.ReadOnly) }), "interface i\r\n{\r\n t p { get; }\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("y", Generator.IdentifierName("x")) }, Generator.IdentifierName("t"), Accessibility.Public, DeclarationModifiers.Sealed) }), "interface i\r\n{\r\n t this[x y] { get; set; }\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("y", Generator.IdentifierName("x")) }, Generator.IdentifierName("t"), Accessibility.Public, DeclarationModifiers.ReadOnly) }), "interface i\r\n{\r\n t this[x y] { get; }\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Static) }), "interface i\r\n{\r\n event t ep;\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.EventDeclaration("ef", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Static) }), "interface i\r\n{\r\n event t ef;\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.InterfaceDeclaration("i", members: new[] { Generator.FieldDeclaration("f", Generator.IdentifierName("t"), accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Sealed) }), "interface i\r\n{\r\n t f { get; set; }\r\n}"); } [Fact] public void TestEnumDeclarations() { VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e"), "enum e\r\n{\r\n}"); VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e", members: new[] { Generator.EnumMember("a"), Generator.EnumMember("b"), Generator.EnumMember("c") }), "enum e\r\n{\r\n a,\r\n b,\r\n c\r\n}"); VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e", members: new[] { Generator.IdentifierName("a"), Generator.EnumMember("b"), Generator.IdentifierName("c") }), "enum e\r\n{\r\n a,\r\n b,\r\n c\r\n}"); VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e", members: new[] { Generator.EnumMember("a", Generator.LiteralExpression(0)), Generator.EnumMember("b"), Generator.EnumMember("c", Generator.LiteralExpression(5)) }), "enum e\r\n{\r\n a = 0,\r\n b,\r\n c = 5\r\n}"); VerifySyntax<EnumDeclarationSyntax>( Generator.EnumDeclaration("e", members: new[] { Generator.FieldDeclaration("a", Generator.IdentifierName("e"), initializer: Generator.LiteralExpression(1)) }), "enum e\r\n{\r\n a = 1\r\n}"); } [Fact] public void TestDelegateDeclarations() { VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d"), "delegate void d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", returnType: Generator.IdentifierName("t")), "delegate t d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", returnType: Generator.IdentifierName("t"), parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("pt")) }), "delegate t d(pt p);"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", accessibility: Accessibility.Public), "public delegate void d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", accessibility: Accessibility.Public), "public delegate void d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", modifiers: DeclarationModifiers.New), "new delegate void d();"); VerifySyntax<DelegateDeclarationSyntax>( Generator.DelegateDeclaration("d", typeParameters: new[] { "T", "S" }), "delegate void d<T, S>();"); } [Fact] public void TestNamespaceImportDeclarations() { VerifySyntax<UsingDirectiveSyntax>( Generator.NamespaceImportDeclaration(Generator.IdentifierName("n")), "using n;"); VerifySyntax<UsingDirectiveSyntax>( Generator.NamespaceImportDeclaration("n"), "using n;"); VerifySyntax<UsingDirectiveSyntax>( Generator.NamespaceImportDeclaration("n.m"), "using n.m;"); } [Fact] public void TestNamespaceDeclarations() { VerifySyntax<NamespaceDeclarationSyntax>( Generator.NamespaceDeclaration("n"), "namespace n\r\n{\r\n}"); VerifySyntax<NamespaceDeclarationSyntax>( Generator.NamespaceDeclaration("n.m"), "namespace n.m\r\n{\r\n}"); VerifySyntax<NamespaceDeclarationSyntax>( Generator.NamespaceDeclaration("n", Generator.NamespaceImportDeclaration("m")), "namespace n\r\n{\r\n using m;\r\n}"); VerifySyntax<NamespaceDeclarationSyntax>( Generator.NamespaceDeclaration("n", Generator.ClassDeclaration("c"), Generator.NamespaceImportDeclaration("m")), "namespace n\r\n{\r\n using m;\r\n\r\n class c\r\n {\r\n }\r\n}"); } [Fact] public void TestCompilationUnits() { VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit(), ""); VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit( Generator.NamespaceDeclaration("n")), "namespace n\r\n{\r\n}"); VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit( Generator.NamespaceImportDeclaration("n")), "using n;"); VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit( Generator.ClassDeclaration("c"), Generator.NamespaceImportDeclaration("m")), "using m;\r\n\r\nclass c\r\n{\r\n}"); VerifySyntax<CompilationUnitSyntax>( Generator.CompilationUnit( Generator.NamespaceImportDeclaration("n"), Generator.NamespaceDeclaration("n", Generator.NamespaceImportDeclaration("m"), Generator.ClassDeclaration("c"))), "using n;\r\n\r\nnamespace n\r\n{\r\n using m;\r\n\r\n class c\r\n {\r\n }\r\n}"); } [Fact] public void TestAttributeDeclarations() { VerifySyntax<AttributeListSyntax>( Generator.Attribute(Generator.IdentifierName("a")), "[a]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a"), "[a]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a.b"), "[a.b]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new SyntaxNode[] { }), "[a()]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new[] { Generator.IdentifierName("x") }), "[a(x)]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new[] { Generator.AttributeArgument(Generator.IdentifierName("x")) }), "[a(x)]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new[] { Generator.AttributeArgument("x", Generator.IdentifierName("y")) }), "[a(x = y)]"); VerifySyntax<AttributeListSyntax>( Generator.Attribute("a", new[] { Generator.IdentifierName("x"), Generator.IdentifierName("y") }), "[a(x, y)]"); } [Fact] public void TestAddAttributes() { VerifySyntax<FieldDeclarationSyntax>( Generator.AddAttributes( Generator.FieldDeclaration("y", Generator.IdentifierName("x")), Generator.Attribute("a")), "[a]\r\nx y;"); VerifySyntax<FieldDeclarationSyntax>( Generator.AddAttributes( Generator.AddAttributes( Generator.FieldDeclaration("y", Generator.IdentifierName("x")), Generator.Attribute("a")), Generator.Attribute("b")), "[a]\r\n[b]\r\nx y;"); VerifySyntax<MethodDeclarationSyntax>( Generator.AddAttributes( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[a]\r\nabstract t m();"); VerifySyntax<MethodDeclarationSyntax>( Generator.AddReturnAttributes( Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[return: a]\r\nabstract t m();"); VerifySyntax<PropertyDeclarationSyntax>( Generator.AddAttributes( Generator.PropertyDeclaration("p", Generator.IdentifierName("x"), accessibility: Accessibility.NotApplicable, modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[a]\r\nabstract x p { get; set; }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.AddAttributes( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("z", Generator.IdentifierName("y")) }, Generator.IdentifierName("x"), modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[a]\r\nabstract x this[y z] { get; set; }"); VerifySyntax<EventDeclarationSyntax>( Generator.AddAttributes( Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract), Generator.Attribute("a")), "[a]\r\nabstract event t ep { add; remove; }"); VerifySyntax<EventFieldDeclarationSyntax>( Generator.AddAttributes( Generator.EventDeclaration("ef", Generator.IdentifierName("t")), Generator.Attribute("a")), "[a]\r\nevent t ef;"); VerifySyntax<ClassDeclarationSyntax>( Generator.AddAttributes( Generator.ClassDeclaration("c"), Generator.Attribute("a")), "[a]\r\nclass c\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.AddAttributes( Generator.StructDeclaration("s"), Generator.Attribute("a")), "[a]\r\nstruct s\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.AddAttributes( Generator.InterfaceDeclaration("i"), Generator.Attribute("a")), "[a]\r\ninterface i\r\n{\r\n}"); VerifySyntax<DelegateDeclarationSyntax>( Generator.AddAttributes( Generator.DelegateDeclaration("d"), Generator.Attribute("a")), "[a]\r\ndelegate void d();"); VerifySyntax<ParameterSyntax>( Generator.AddAttributes( Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.Attribute("a")), "[a] t p"); VerifySyntax<CompilationUnitSyntax>( Generator.AddAttributes( Generator.CompilationUnit(Generator.NamespaceDeclaration("n")), Generator.Attribute("a")), "[assembly: a]\r\nnamespace n\r\n{\r\n}"); } [Fact] [WorkItem(5066, "https://github.com/dotnet/roslyn/issues/5066")] public void TestAddAttributesToAccessors() { var prop = Generator.PropertyDeclaration("P", Generator.IdentifierName("T")); var evnt = Generator.CustomEventDeclaration("E", Generator.IdentifierName("T")); CheckAddRemoveAttribute(Generator.GetAccessor(prop, DeclarationKind.GetAccessor)); CheckAddRemoveAttribute(Generator.GetAccessor(prop, DeclarationKind.SetAccessor)); CheckAddRemoveAttribute(Generator.GetAccessor(evnt, DeclarationKind.AddAccessor)); CheckAddRemoveAttribute(Generator.GetAccessor(evnt, DeclarationKind.RemoveAccessor)); } private void CheckAddRemoveAttribute(SyntaxNode declaration) { var initialAttributes = Generator.GetAttributes(declaration); Assert.Equal(0, initialAttributes.Count); var withAttribute = Generator.AddAttributes(declaration, Generator.Attribute("a")); var attrsAdded = Generator.GetAttributes(withAttribute); Assert.Equal(1, attrsAdded.Count); var withoutAttribute = Generator.RemoveNode(withAttribute, attrsAdded[0]); var attrsRemoved = Generator.GetAttributes(withoutAttribute); Assert.Equal(0, attrsRemoved.Count); } [Fact] public void TestAddRemoveAttributesPerservesTrivia() { var cls = SyntaxFactory.ParseCompilationUnit(@"// comment public class C { } // end").Members[0]; var added = Generator.AddAttributes(cls, Generator.Attribute("a")); VerifySyntax<ClassDeclarationSyntax>(added, "// comment\r\n[a]\r\npublic class C\r\n{\r\n} // end\r\n"); var removed = Generator.RemoveAllAttributes(added); VerifySyntax<ClassDeclarationSyntax>(removed, "// comment\r\npublic class C\r\n{\r\n} // end\r\n"); var attrWithComment = Generator.GetAttributes(added).First(); VerifySyntax<AttributeListSyntax>(attrWithComment, "// comment\r\n[a]"); } [Fact] public void TestWithTypeParameters() { VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeParameters( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "abstract void m<a>();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeParameters( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract)), "abstract void m();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeParameters( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a", "b"), "abstract void m<a, b>();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeParameters(Generator.WithTypeParameters( Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a", "b")), "abstract void m();"); VerifySyntax<ClassDeclarationSyntax>( Generator.WithTypeParameters( Generator.ClassDeclaration("c"), "a", "b"), "class c<a, b>\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.WithTypeParameters( Generator.StructDeclaration("s"), "a", "b"), "struct s<a, b>\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.WithTypeParameters( Generator.InterfaceDeclaration("i"), "a", "b"), "interface i<a, b>\r\n{\r\n}"); VerifySyntax<DelegateDeclarationSyntax>( Generator.WithTypeParameters( Generator.DelegateDeclaration("d"), "a", "b"), "delegate void d<a, b>();"); } [Fact] public void TestWithTypeConstraint() { VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", Generator.IdentifierName("b")), "abstract void m<a>()\r\n where a : b;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", Generator.IdentifierName("b"), Generator.IdentifierName("c")), "abstract void m<a>()\r\n where a : b, c;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a"), "abstract void m<a>();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint(Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", Generator.IdentifierName("b"), Generator.IdentifierName("c")), "a"), "abstract void m<a>();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a", "x"), "a", Generator.IdentifierName("b"), Generator.IdentifierName("c")), "x", Generator.IdentifierName("y")), "abstract void m<a, x>()\r\n where a : b, c where x : y;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.Constructor), "abstract void m<a>()\r\n where a : new();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ReferenceType), "abstract void m<a>()\r\n where a : class;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ValueType), "abstract void m<a>()\r\n where a : struct;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ReferenceType | SpecialTypeConstraintKind.Constructor), "abstract void m<a>()\r\n where a : class, new();"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ReferenceType | SpecialTypeConstraintKind.ValueType), "abstract void m<a>()\r\n where a : class;"); VerifySyntax<MethodDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Abstract), "a"), "a", SpecialTypeConstraintKind.ReferenceType, Generator.IdentifierName("b"), Generator.IdentifierName("c")), "abstract void m<a>()\r\n where a : class, b, c;"); // type declarations VerifySyntax<ClassDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters( Generator.ClassDeclaration("c"), "a", "b"), "a", Generator.IdentifierName("x")), "class c<a, b>\r\n where a : x\r\n{\r\n}"); VerifySyntax<StructDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters( Generator.StructDeclaration("s"), "a", "b"), "a", Generator.IdentifierName("x")), "struct s<a, b>\r\n where a : x\r\n{\r\n}"); VerifySyntax<InterfaceDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters( Generator.InterfaceDeclaration("i"), "a", "b"), "a", Generator.IdentifierName("x")), "interface i<a, b>\r\n where a : x\r\n{\r\n}"); VerifySyntax<DelegateDeclarationSyntax>( Generator.WithTypeConstraint( Generator.WithTypeParameters( Generator.DelegateDeclaration("d"), "a", "b"), "a", Generator.IdentifierName("x")), "delegate void d<a, b>()\r\n where a : x;"); } [Fact] public void TestInterfaceDeclarationWithEventFromSymbol() { VerifySyntax<InterfaceDeclarationSyntax>( Generator.Declaration(_emptyCompilation.GetTypeByMetadataName("System.ComponentModel.INotifyPropertyChanged")), @"public interface INotifyPropertyChanged { event global::System.ComponentModel.PropertyChangedEventHandler PropertyChanged; }"); } [WorkItem(38379, "https://github.com/dotnet/roslyn/issues/38379")] [Fact] public void TestUnsafeFieldDeclarationFromSymbol() { VerifySyntax<MethodDeclarationSyntax>( Generator.Declaration( _emptyCompilation.GetTypeByMetadataName("System.IntPtr").GetMembers("ToPointer").Single()), @"public unsafe void* ToPointer() { }"); } [Fact] public void TestEnumDeclarationFromSymbol() { VerifySyntax<EnumDeclarationSyntax>( Generator.Declaration( _emptyCompilation.GetTypeByMetadataName("System.DateTimeKind")), @"public enum DateTimeKind { Unspecified = 0, Utc = 1, Local = 2 }"); } [Fact] public void TestEnumWithUnderlyingTypeFromSymbol() { VerifySyntax<EnumDeclarationSyntax>( Generator.Declaration( _emptyCompilation.GetTypeByMetadataName("System.Security.SecurityRuleSet")), @"public enum SecurityRuleSet : byte { None = 0, Level1 = 1, Level2 = 2 }"); } #endregion #region Add/Insert/Remove/Get declarations & members/elements private void AssertNamesEqual(string[] expectedNames, IEnumerable<SyntaxNode> actualNodes) { var actualNames = actualNodes.Select(n => Generator.GetName(n)).ToArray(); var expected = string.Join(", ", expectedNames); var actual = string.Join(", ", actualNames); Assert.Equal(expected, actual); } private void AssertNamesEqual(string name, IEnumerable<SyntaxNode> actualNodes) => AssertNamesEqual(new[] { name }, actualNodes); private void AssertMemberNamesEqual(string[] expectedNames, SyntaxNode declaration) => AssertNamesEqual(expectedNames, Generator.GetMembers(declaration)); private void AssertMemberNamesEqual(string expectedName, SyntaxNode declaration) => AssertNamesEqual(new[] { expectedName }, Generator.GetMembers(declaration)); [Fact] public void TestAddNamespaceImports() { AssertNamesEqual("x.y", Generator.GetNamespaceImports(Generator.AddNamespaceImports(Generator.CompilationUnit(), Generator.NamespaceImportDeclaration("x.y")))); AssertNamesEqual(new[] { "x.y", "z" }, Generator.GetNamespaceImports(Generator.AddNamespaceImports(Generator.CompilationUnit(), Generator.NamespaceImportDeclaration("x.y"), Generator.IdentifierName("z")))); AssertNamesEqual("", Generator.GetNamespaceImports(Generator.AddNamespaceImports(Generator.CompilationUnit(), Generator.MethodDeclaration("m")))); AssertNamesEqual(new[] { "x", "y.z" }, Generator.GetNamespaceImports(Generator.AddNamespaceImports(Generator.CompilationUnit(Generator.IdentifierName("x")), Generator.DottedName("y.z")))); } [Fact] public void TestRemoveNamespaceImports() { TestRemoveAllNamespaceImports(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x"))); TestRemoveAllNamespaceImports(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x"), Generator.IdentifierName("y"))); TestRemoveNamespaceImport(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x")), "x", new string[] { }); TestRemoveNamespaceImport(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x"), Generator.IdentifierName("y")), "x", new[] { "y" }); TestRemoveNamespaceImport(Generator.CompilationUnit(Generator.NamespaceImportDeclaration("x"), Generator.IdentifierName("y")), "y", new[] { "x" }); } private void TestRemoveAllNamespaceImports(SyntaxNode declaration) => Assert.Equal(0, Generator.GetNamespaceImports(Generator.RemoveNodes(declaration, Generator.GetNamespaceImports(declaration))).Count); private void TestRemoveNamespaceImport(SyntaxNode declaration, string name, string[] remainingNames) { var newDecl = Generator.RemoveNode(declaration, Generator.GetNamespaceImports(declaration).First(m => Generator.GetName(m) == name)); AssertNamesEqual(remainingNames, Generator.GetNamespaceImports(newDecl)); } [Fact] public void TestRemoveNodeInTrivia() { var code = @" ///<summary> ... </summary> public class C { }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var summary = cls.DescendantNodes(descendIntoTrivia: true).OfType<XmlElementSyntax>().First(); var newCu = Generator.RemoveNode(cu, summary); VerifySyntaxRaw<CompilationUnitSyntax>( newCu, @" public class C { }"); } [Fact] public void TestReplaceNodeInTrivia() { var code = @" ///<summary> ... </summary> public class C { }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var summary = cls.DescendantNodes(descendIntoTrivia: true).OfType<XmlElementSyntax>().First(); var summary2 = summary.WithContent(default); var newCu = Generator.ReplaceNode(cu, summary, summary2); VerifySyntaxRaw<CompilationUnitSyntax>( newCu, @" ///<summary></summary> public class C { }"); } [Fact] public void TestInsertAfterNodeInTrivia() { var code = @" ///<summary> ... </summary> public class C { }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var text = cls.DescendantNodes(descendIntoTrivia: true).OfType<XmlTextSyntax>().First(); var newCu = Generator.InsertNodesAfter(cu, text, new SyntaxNode[] { text }); VerifySyntaxRaw<CompilationUnitSyntax>( newCu, @" ///<summary> ... ... </summary> public class C { }"); } [Fact] public void TestInsertBeforeNodeInTrivia() { var code = @" ///<summary> ... </summary> public class C { }"; var cu = SyntaxFactory.ParseCompilationUnit(code); var cls = cu.Members[0]; var text = cls.DescendantNodes(descendIntoTrivia: true).OfType<XmlTextSyntax>().First(); var newCu = Generator.InsertNodesBefore(cu, text, new SyntaxNode[] { text }); VerifySyntaxRaw<CompilationUnitSyntax>( newCu, @" ///<summary> ... ... </summary> public class C { }"); } [Fact] public void TestAddMembers() { AssertMemberNamesEqual("m", Generator.AddMembers(Generator.ClassDeclaration("d"), new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("m", Generator.AddMembers(Generator.StructDeclaration("s"), new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("m", Generator.AddMembers(Generator.InterfaceDeclaration("i"), new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("v", Generator.AddMembers(Generator.EnumDeclaration("e"), new[] { Generator.EnumMember("v") })); AssertMemberNamesEqual("n2", Generator.AddMembers(Generator.NamespaceDeclaration("n"), new[] { Generator.NamespaceDeclaration("n2") })); AssertMemberNamesEqual("n", Generator.AddMembers(Generator.CompilationUnit(), new[] { Generator.NamespaceDeclaration("n") })); AssertMemberNamesEqual(new[] { "m", "m2" }, Generator.AddMembers(Generator.ClassDeclaration("d", members: new[] { Generator.MethodDeclaration("m") }), new[] { Generator.MethodDeclaration("m2") })); AssertMemberNamesEqual(new[] { "m", "m2" }, Generator.AddMembers(Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m") }), new[] { Generator.MethodDeclaration("m2") })); AssertMemberNamesEqual(new[] { "m", "m2" }, Generator.AddMembers(Generator.InterfaceDeclaration("i", members: new[] { Generator.MethodDeclaration("m") }), new[] { Generator.MethodDeclaration("m2") })); AssertMemberNamesEqual(new[] { "v", "v2" }, Generator.AddMembers(Generator.EnumDeclaration("i", members: new[] { Generator.EnumMember("v") }), new[] { Generator.EnumMember("v2") })); AssertMemberNamesEqual(new[] { "n1", "n2" }, Generator.AddMembers(Generator.NamespaceDeclaration("n", new[] { Generator.NamespaceDeclaration("n1") }), new[] { Generator.NamespaceDeclaration("n2") })); AssertMemberNamesEqual(new[] { "n1", "n2" }, Generator.AddMembers(Generator.CompilationUnit(declarations: new[] { Generator.NamespaceDeclaration("n1") }), new[] { Generator.NamespaceDeclaration("n2") })); } [Fact] public void TestRemoveMembers() { // remove all members TestRemoveAllMembers(Generator.ClassDeclaration("c", members: new[] { Generator.MethodDeclaration("m") })); TestRemoveAllMembers(Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m") })); TestRemoveAllMembers(Generator.InterfaceDeclaration("i", members: new[] { Generator.MethodDeclaration("m") })); TestRemoveAllMembers(Generator.EnumDeclaration("i", members: new[] { Generator.EnumMember("v") })); TestRemoveAllMembers(Generator.NamespaceDeclaration("n", new[] { Generator.NamespaceDeclaration("n") })); TestRemoveAllMembers(Generator.CompilationUnit(declarations: new[] { Generator.NamespaceDeclaration("n") })); TestRemoveMember(Generator.ClassDeclaration("c", members: new[] { Generator.MethodDeclaration("m1"), Generator.MethodDeclaration("m2") }), "m1", new[] { "m2" }); TestRemoveMember(Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m1"), Generator.MethodDeclaration("m2") }), "m1", new[] { "m2" }); } private void TestRemoveAllMembers(SyntaxNode declaration) => Assert.Equal(0, Generator.GetMembers(Generator.RemoveNodes(declaration, Generator.GetMembers(declaration))).Count); private void TestRemoveMember(SyntaxNode declaration, string name, string[] remainingNames) { var newDecl = Generator.RemoveNode(declaration, Generator.GetMembers(declaration).First(m => Generator.GetName(m) == name)); AssertMemberNamesEqual(remainingNames, newDecl); } [Fact] public void TestGetMembers() { AssertMemberNamesEqual("m", Generator.ClassDeclaration("c", members: new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("m", Generator.StructDeclaration("s", members: new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("m", Generator.InterfaceDeclaration("i", members: new[] { Generator.MethodDeclaration("m") })); AssertMemberNamesEqual("v", Generator.EnumDeclaration("e", members: new[] { Generator.EnumMember("v") })); AssertMemberNamesEqual("c", Generator.NamespaceDeclaration("n", declarations: new[] { Generator.ClassDeclaration("c") })); AssertMemberNamesEqual("c", Generator.CompilationUnit(declarations: new[] { Generator.ClassDeclaration("c") })); } [Fact] public void TestGetDeclarationKind() { Assert.Equal(DeclarationKind.CompilationUnit, Generator.GetDeclarationKind(Generator.CompilationUnit())); Assert.Equal(DeclarationKind.Class, Generator.GetDeclarationKind(Generator.ClassDeclaration("c"))); Assert.Equal(DeclarationKind.Struct, Generator.GetDeclarationKind(Generator.StructDeclaration("s"))); Assert.Equal(DeclarationKind.Interface, Generator.GetDeclarationKind(Generator.InterfaceDeclaration("i"))); Assert.Equal(DeclarationKind.Enum, Generator.GetDeclarationKind(Generator.EnumDeclaration("e"))); Assert.Equal(DeclarationKind.Delegate, Generator.GetDeclarationKind(Generator.DelegateDeclaration("d"))); Assert.Equal(DeclarationKind.Method, Generator.GetDeclarationKind(Generator.MethodDeclaration("m"))); Assert.Equal(DeclarationKind.Constructor, Generator.GetDeclarationKind(Generator.ConstructorDeclaration())); Assert.Equal(DeclarationKind.Parameter, Generator.GetDeclarationKind(Generator.ParameterDeclaration("p"))); Assert.Equal(DeclarationKind.Property, Generator.GetDeclarationKind(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.Indexer, Generator.GetDeclarationKind(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(Generator.FieldDeclaration("f", Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.EnumMember, Generator.GetDeclarationKind(Generator.EnumMember("v"))); Assert.Equal(DeclarationKind.Event, Generator.GetDeclarationKind(Generator.EventDeclaration("ef", Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.CustomEvent, Generator.GetDeclarationKind(Generator.CustomEventDeclaration("e", Generator.IdentifierName("t")))); Assert.Equal(DeclarationKind.Namespace, Generator.GetDeclarationKind(Generator.NamespaceDeclaration("n"))); Assert.Equal(DeclarationKind.NamespaceImport, Generator.GetDeclarationKind(Generator.NamespaceImportDeclaration("u"))); Assert.Equal(DeclarationKind.Variable, Generator.GetDeclarationKind(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"))); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(Generator.Attribute("a"))); } [Fact] public void TestGetName() { Assert.Equal("c", Generator.GetName(Generator.ClassDeclaration("c"))); Assert.Equal("s", Generator.GetName(Generator.StructDeclaration("s"))); Assert.Equal("i", Generator.GetName(Generator.EnumDeclaration("i"))); Assert.Equal("e", Generator.GetName(Generator.EnumDeclaration("e"))); Assert.Equal("d", Generator.GetName(Generator.DelegateDeclaration("d"))); Assert.Equal("m", Generator.GetName(Generator.MethodDeclaration("m"))); Assert.Equal("", Generator.GetName(Generator.ConstructorDeclaration())); Assert.Equal("p", Generator.GetName(Generator.ParameterDeclaration("p"))); Assert.Equal("p", Generator.GetName(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")))); Assert.Equal("", Generator.GetName(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")))); Assert.Equal("f", Generator.GetName(Generator.FieldDeclaration("f", Generator.IdentifierName("t")))); Assert.Equal("v", Generator.GetName(Generator.EnumMember("v"))); Assert.Equal("ef", Generator.GetName(Generator.EventDeclaration("ef", Generator.IdentifierName("t")))); Assert.Equal("ep", Generator.GetName(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t")))); Assert.Equal("n", Generator.GetName(Generator.NamespaceDeclaration("n"))); Assert.Equal("u", Generator.GetName(Generator.NamespaceImportDeclaration("u"))); Assert.Equal("loc", Generator.GetName(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"))); Assert.Equal("a", Generator.GetName(Generator.Attribute("a"))); } [Fact] public void TestWithName() { Assert.Equal("c", Generator.GetName(Generator.WithName(Generator.ClassDeclaration("x"), "c"))); Assert.Equal("s", Generator.GetName(Generator.WithName(Generator.StructDeclaration("x"), "s"))); Assert.Equal("i", Generator.GetName(Generator.WithName(Generator.EnumDeclaration("x"), "i"))); Assert.Equal("e", Generator.GetName(Generator.WithName(Generator.EnumDeclaration("x"), "e"))); Assert.Equal("d", Generator.GetName(Generator.WithName(Generator.DelegateDeclaration("x"), "d"))); Assert.Equal("m", Generator.GetName(Generator.WithName(Generator.MethodDeclaration("x"), "m"))); Assert.Equal("", Generator.GetName(Generator.WithName(Generator.ConstructorDeclaration(), ".ctor"))); Assert.Equal("p", Generator.GetName(Generator.WithName(Generator.ParameterDeclaration("x"), "p"))); Assert.Equal("p", Generator.GetName(Generator.WithName(Generator.PropertyDeclaration("x", Generator.IdentifierName("t")), "p"))); Assert.Equal("", Generator.GetName(Generator.WithName(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")), "this"))); Assert.Equal("f", Generator.GetName(Generator.WithName(Generator.FieldDeclaration("x", Generator.IdentifierName("t")), "f"))); Assert.Equal("v", Generator.GetName(Generator.WithName(Generator.EnumMember("x"), "v"))); Assert.Equal("ef", Generator.GetName(Generator.WithName(Generator.EventDeclaration("x", Generator.IdentifierName("t")), "ef"))); Assert.Equal("ep", Generator.GetName(Generator.WithName(Generator.CustomEventDeclaration("x", Generator.IdentifierName("t")), "ep"))); Assert.Equal("n", Generator.GetName(Generator.WithName(Generator.NamespaceDeclaration("x"), "n"))); Assert.Equal("u", Generator.GetName(Generator.WithName(Generator.NamespaceImportDeclaration("x"), "u"))); Assert.Equal("loc", Generator.GetName(Generator.WithName(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "x"), "loc"))); Assert.Equal("a", Generator.GetName(Generator.WithName(Generator.Attribute("x"), "a"))); } [Fact] public void TestGetAccessibility() { Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.ClassDeclaration("c", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.StructDeclaration("s", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.EnumDeclaration("i", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.EnumDeclaration("e", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.DelegateDeclaration("d", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.MethodDeclaration("m", accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.ConstructorDeclaration(accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.ParameterDeclaration("p"))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.FieldDeclaration("f", Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.EnumMember("v"))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.EventDeclaration("ef", Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.Internal, Generator.GetAccessibility(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), accessibility: Accessibility.Internal))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.NamespaceDeclaration("n"))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.NamespaceImportDeclaration("u"))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.Attribute("a"))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(SyntaxFactory.TypeParameter("tp"))); } [Fact] public void TestWithAccessibility() { Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.ClassDeclaration("c", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.StructDeclaration("s", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.EnumDeclaration("i", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.EnumDeclaration("e", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.DelegateDeclaration("d", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.MethodDeclaration("m", accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.ConstructorDeclaration(accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.ParameterDeclaration("p"), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.FieldDeclaration("f", Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.EnumMember("v"), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.EventDeclaration("ef", Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), accessibility: Accessibility.Internal), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.NamespaceDeclaration("n"), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.NamespaceImportDeclaration("u"), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(Generator.Attribute("a"), Accessibility.Private))); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(Generator.WithAccessibility(SyntaxFactory.TypeParameter("tp"), Accessibility.Private))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(SyntaxFactory.AccessorDeclaration(SyntaxKind.InitAccessorDeclaration), Accessibility.Private))); } [Fact] public void TestGetModifiers() { Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.ClassDeclaration("c", modifiers: DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Partial, Generator.GetModifiers(Generator.StructDeclaration("s", modifiers: DeclarationModifiers.Partial))); Assert.Equal(DeclarationModifiers.New, Generator.GetModifiers(Generator.EnumDeclaration("e", modifiers: DeclarationModifiers.New))); Assert.Equal(DeclarationModifiers.New, Generator.GetModifiers(Generator.DelegateDeclaration("d", modifiers: DeclarationModifiers.New))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.MethodDeclaration("m", modifiers: DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.ConstructorDeclaration(modifiers: DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.ParameterDeclaration("p"))); Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Const, Generator.GetModifiers(Generator.FieldDeclaration("f", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Const))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.EventDeclaration("ef", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"), modifiers: DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.EnumMember("v"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.NamespaceDeclaration("n"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.NamespaceImportDeclaration("u"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.Attribute("a"))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(SyntaxFactory.TypeParameter("tp"))); } [Fact] public void TestWithModifiers() { Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.WithModifiers(Generator.ClassDeclaration("c"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Partial, Generator.GetModifiers(Generator.WithModifiers(Generator.StructDeclaration("s"), DeclarationModifiers.Partial))); Assert.Equal(DeclarationModifiers.New, Generator.GetModifiers(Generator.WithModifiers(Generator.EnumDeclaration("e"), DeclarationModifiers.New))); Assert.Equal(DeclarationModifiers.New, Generator.GetModifiers(Generator.WithModifiers(Generator.DelegateDeclaration("d"), DeclarationModifiers.New))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.WithModifiers(Generator.MethodDeclaration("m"), DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.WithModifiers(Generator.ConstructorDeclaration(), DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.ParameterDeclaration("p"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.WithModifiers(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Abstract, Generator.GetModifiers(Generator.WithModifiers(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.Const, Generator.GetModifiers(Generator.WithModifiers(Generator.FieldDeclaration("f", Generator.IdentifierName("t")), DeclarationModifiers.Const))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.WithModifiers(Generator.EventDeclaration("ef", Generator.IdentifierName("t")), DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(Generator.WithModifiers(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t")), DeclarationModifiers.Static))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.EnumMember("v"), DeclarationModifiers.Partial))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.NamespaceDeclaration("n"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.NamespaceImportDeclaration("u"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(Generator.Attribute("a"), DeclarationModifiers.Abstract))); Assert.Equal(DeclarationModifiers.None, Generator.GetModifiers(Generator.WithModifiers(SyntaxFactory.TypeParameter("tp"), DeclarationModifiers.Abstract))); } [Fact] public void TestWithModifiers_AllowedModifiers() { var allModifiers = new DeclarationModifiers(true, true, true, true, true, true, true, true, true, true, true, true, true); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.ClassDeclaration("c"), allModifiers))); Assert.Equal( DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Unsafe | DeclarationModifiers.ReadOnly, Generator.GetModifiers(Generator.WithModifiers(Generator.StructDeclaration("s"), allModifiers))); Assert.Equal( DeclarationModifiers.New | DeclarationModifiers.Partial | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.InterfaceDeclaration("i"), allModifiers))); Assert.Equal( DeclarationModifiers.New | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.DelegateDeclaration("d"), allModifiers))); Assert.Equal( DeclarationModifiers.New, Generator.GetModifiers(Generator.WithModifiers(Generator.EnumDeclaration("e"), allModifiers))); Assert.Equal( DeclarationModifiers.Const | DeclarationModifiers.New | DeclarationModifiers.ReadOnly | DeclarationModifiers.Static | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.FieldDeclaration("f", Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.Static | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.ConstructorDeclaration("c"), allModifiers))); Assert.Equal( DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(SyntaxFactory.DestructorDeclaration("c"), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.Async | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe | DeclarationModifiers.ReadOnly, Generator.GetModifiers(Generator.WithModifiers(Generator.MethodDeclaration("m"), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.ReadOnly | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe, Generator.GetModifiers(Generator.WithModifiers(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("i") }, Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.New | DeclarationModifiers.Static | DeclarationModifiers.Unsafe | DeclarationModifiers.ReadOnly, Generator.GetModifiers(Generator.WithModifiers(Generator.EventDeclaration("ef", Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Sealed | DeclarationModifiers.Static | DeclarationModifiers.Virtual | DeclarationModifiers.Unsafe | DeclarationModifiers.ReadOnly, Generator.GetModifiers(Generator.WithModifiers(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t")), allModifiers))); Assert.Equal( DeclarationModifiers.Abstract | DeclarationModifiers.New | DeclarationModifiers.Override | DeclarationModifiers.Virtual, Generator.GetModifiers(Generator.WithModifiers(SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration), allModifiers))); } [Fact] public void TestGetType() { Assert.Equal("t", Generator.GetType(Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("t"))).ToString()); Assert.Null(Generator.GetType(Generator.MethodDeclaration("m"))); Assert.Equal("t", Generator.GetType(Generator.FieldDeclaration("f", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("pt")) }, Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.ParameterDeclaration("p", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.EventDeclaration("ef", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.DelegateDeclaration("t", returnType: Generator.IdentifierName("t"))).ToString()); Assert.Null(Generator.GetType(Generator.DelegateDeclaration("d"))); Assert.Equal("t", Generator.GetType(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "v")).ToString()); Assert.Null(Generator.GetType(Generator.ClassDeclaration("c"))); Assert.Null(Generator.GetType(Generator.IdentifierName("x"))); } [Fact] public void TestWithType() { Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.MethodDeclaration("m", returnType: Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.FieldDeclaration("f", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.PropertyDeclaration("p", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("pt")) }, Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.ParameterDeclaration("p", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.DelegateDeclaration("t"), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.EventDeclaration("ef", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.CustomEventDeclaration("ep", Generator.IdentifierName("x")), Generator.IdentifierName("t"))).ToString()); Assert.Equal("t", Generator.GetType(Generator.WithType(Generator.LocalDeclarationStatement(Generator.IdentifierName("x"), "v"), Generator.IdentifierName("t"))).ToString()); Assert.Null(Generator.GetType(Generator.WithType(Generator.ClassDeclaration("c"), Generator.IdentifierName("t")))); Assert.Null(Generator.GetType(Generator.WithType(Generator.IdentifierName("x"), Generator.IdentifierName("t")))); } [Fact] public void TestGetParameters() { Assert.Equal(0, Generator.GetParameters(Generator.MethodDeclaration("m")).Count); Assert.Equal(1, Generator.GetParameters(Generator.MethodDeclaration("m", parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(2, Generator.GetParameters(Generator.MethodDeclaration("m", parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.ParameterDeclaration("p2", Generator.IdentifierName("t2")) })).Count); Assert.Equal(0, Generator.GetParameters(Generator.ConstructorDeclaration()).Count); Assert.Equal(1, Generator.GetParameters(Generator.ConstructorDeclaration(parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(2, Generator.GetParameters(Generator.ConstructorDeclaration(parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.ParameterDeclaration("p2", Generator.IdentifierName("t2")) })).Count); Assert.Equal(1, Generator.GetParameters(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetParameters(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.ParameterDeclaration("p2", Generator.IdentifierName("t2")) }, Generator.IdentifierName("t"))).Count); Assert.Equal(0, Generator.GetParameters(Generator.ValueReturningLambdaExpression(Generator.IdentifierName("expr"))).Count); Assert.Equal(1, Generator.GetParameters(Generator.ValueReturningLambdaExpression("p1", Generator.IdentifierName("expr"))).Count); Assert.Equal(0, Generator.GetParameters(Generator.VoidReturningLambdaExpression(Generator.IdentifierName("expr"))).Count); Assert.Equal(1, Generator.GetParameters(Generator.VoidReturningLambdaExpression("p1", Generator.IdentifierName("expr"))).Count); Assert.Equal(0, Generator.GetParameters(Generator.DelegateDeclaration("d")).Count); Assert.Equal(1, Generator.GetParameters(Generator.DelegateDeclaration("d", parameters: new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(0, Generator.GetParameters(Generator.ClassDeclaration("c")).Count); Assert.Equal(0, Generator.GetParameters(Generator.IdentifierName("x")).Count); } [Fact] public void TestAddParameters() { Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.MethodDeclaration("m"), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.ConstructorDeclaration(), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(3, Generator.GetParameters(Generator.AddParameters(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("t")), new[] { Generator.ParameterDeclaration("p2", Generator.IdentifierName("t2")), Generator.ParameterDeclaration("p3", Generator.IdentifierName("t3")) })).Count); Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.ValueReturningLambdaExpression(Generator.IdentifierName("expr")), new[] { Generator.LambdaParameter("p") })).Count); Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.VoidReturningLambdaExpression(Generator.IdentifierName("expr")), new[] { Generator.LambdaParameter("p") })).Count); Assert.Equal(1, Generator.GetParameters(Generator.AddParameters(Generator.DelegateDeclaration("d"), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(0, Generator.GetParameters(Generator.AddParameters(Generator.ClassDeclaration("c"), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); Assert.Equal(0, Generator.GetParameters(Generator.AddParameters(Generator.IdentifierName("x"), new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) })).Count); } [Fact] public void TestGetExpression() { // initializers Assert.Equal("x", Generator.GetExpression(Generator.FieldDeclaration("f", Generator.IdentifierName("t"), initializer: Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.ParameterDeclaration("p", Generator.IdentifierName("t"), initializer: Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.LocalDeclarationStatement("loc", initializer: Generator.IdentifierName("x"))).ToString()); // lambda bodies Assert.Null(Generator.GetExpression(Generator.ValueReturningLambdaExpression("p", new[] { Generator.IdentifierName("x") }))); Assert.Equal(1, Generator.GetStatements(Generator.ValueReturningLambdaExpression("p", new[] { Generator.IdentifierName("x") })).Count); Assert.Equal("x", Generator.GetExpression(Generator.ValueReturningLambdaExpression(Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.VoidReturningLambdaExpression(Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.ValueReturningLambdaExpression("p", Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.VoidReturningLambdaExpression("p", Generator.IdentifierName("x"))).ToString()); // identifier Assert.Null(Generator.GetExpression(Generator.IdentifierName("e"))); // expression bodied methods var method = (MethodDeclarationSyntax)Generator.MethodDeclaration("p"); method = method.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); method = method.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); Assert.Equal("x", Generator.GetExpression(method).ToString()); // expression bodied local functions var local = SyntaxFactory.LocalFunctionStatement(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), "p"); local = local.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); local = local.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); Assert.Equal("x", Generator.GetExpression(local).ToString()); } [Fact] public void TestWithExpression() { // initializers Assert.Equal("x", Generator.GetExpression(Generator.WithExpression(Generator.FieldDeclaration("f", Generator.IdentifierName("t")), Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.WithExpression(Generator.ParameterDeclaration("p", Generator.IdentifierName("t")), Generator.IdentifierName("x"))).ToString()); Assert.Equal("x", Generator.GetExpression(Generator.WithExpression(Generator.LocalDeclarationStatement(Generator.IdentifierName("t"), "loc"), Generator.IdentifierName("x"))).ToString()); // lambda bodies Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.ValueReturningLambdaExpression("p", new[] { Generator.IdentifierName("x") }), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.VoidReturningLambdaExpression("p", new[] { Generator.IdentifierName("x") }), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.ValueReturningLambdaExpression(new[] { Generator.IdentifierName("x") }), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.VoidReturningLambdaExpression(new[] { Generator.IdentifierName("x") }), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.ValueReturningLambdaExpression("p", Generator.IdentifierName("x")), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.VoidReturningLambdaExpression("p", Generator.IdentifierName("x")), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.ValueReturningLambdaExpression(Generator.IdentifierName("x")), Generator.IdentifierName("y"))).ToString()); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(Generator.VoidReturningLambdaExpression(Generator.IdentifierName("x")), Generator.IdentifierName("y"))).ToString()); // identifier Assert.Null(Generator.GetExpression(Generator.WithExpression(Generator.IdentifierName("e"), Generator.IdentifierName("x")))); // expression bodied methods var method = (MethodDeclarationSyntax)Generator.MethodDeclaration("p"); method = method.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); method = method.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(method, Generator.IdentifierName("y"))).ToString()); // expression bodied local functions var local = SyntaxFactory.LocalFunctionStatement(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), "p"); local = local.WithBody(null).WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); local = local.WithExpressionBody(SyntaxFactory.ArrowExpressionClause((ExpressionSyntax)Generator.IdentifierName("x"))); Assert.Equal("y", Generator.GetExpression(Generator.WithExpression(local, Generator.IdentifierName("y"))).ToString()); } [Fact] public void TestAccessorDeclarations() { var prop = Generator.PropertyDeclaration("p", Generator.IdentifierName("T")); Assert.Equal(2, Generator.GetAccessors(prop).Count); // get accessors from property var getAccessor = Generator.GetAccessor(prop, DeclarationKind.GetAccessor); Assert.NotNull(getAccessor); VerifySyntax<AccessorDeclarationSyntax>(getAccessor, @"get;"); Assert.NotNull(getAccessor); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(getAccessor)); // get accessors from property var setAccessor = Generator.GetAccessor(prop, DeclarationKind.SetAccessor); Assert.NotNull(setAccessor); Assert.Equal(Accessibility.NotApplicable, Generator.GetAccessibility(setAccessor)); // remove accessors Assert.Null(Generator.GetAccessor(Generator.RemoveNode(prop, getAccessor), DeclarationKind.GetAccessor)); Assert.Null(Generator.GetAccessor(Generator.RemoveNode(prop, setAccessor), DeclarationKind.SetAccessor)); // change accessor accessibility Assert.Equal(Accessibility.Public, Generator.GetAccessibility(Generator.WithAccessibility(getAccessor, Accessibility.Public))); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(Generator.WithAccessibility(setAccessor, Accessibility.Private))); // change accessor statements Assert.Equal(0, Generator.GetStatements(getAccessor).Count); Assert.Equal(0, Generator.GetStatements(setAccessor).Count); var newGetAccessor = Generator.WithStatements(getAccessor, null); VerifySyntax<AccessorDeclarationSyntax>(newGetAccessor, @"get;"); var newNewGetAccessor = Generator.WithStatements(newGetAccessor, new SyntaxNode[] { }); VerifySyntax<AccessorDeclarationSyntax>(newNewGetAccessor, @"get { }"); // change accessors var newProp = Generator.ReplaceNode(prop, getAccessor, Generator.WithAccessibility(getAccessor, Accessibility.Public)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(Generator.GetAccessor(newProp, DeclarationKind.GetAccessor))); newProp = Generator.ReplaceNode(prop, setAccessor, Generator.WithAccessibility(setAccessor, Accessibility.Public)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(Generator.GetAccessor(newProp, DeclarationKind.SetAccessor))); } [Fact] public void TestAccessorDeclarations2() { VerifySyntax<PropertyDeclarationSyntax>( Generator.WithAccessorDeclarations(Generator.PropertyDeclaration("p", Generator.IdentifierName("x"))), "x p { }"); VerifySyntax<PropertyDeclarationSyntax>( Generator.WithAccessorDeclarations( Generator.PropertyDeclaration("p", Generator.IdentifierName("x")), Generator.GetAccessorDeclaration(Accessibility.NotApplicable, new[] { Generator.ReturnStatement() })), "x p\r\n{\r\n get\r\n {\r\n return;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.WithAccessorDeclarations( Generator.PropertyDeclaration("p", Generator.IdentifierName("x")), Generator.GetAccessorDeclaration(Accessibility.Protected, new[] { Generator.ReturnStatement() })), "x p\r\n{\r\n protected get\r\n {\r\n return;\r\n }\r\n}"); VerifySyntax<PropertyDeclarationSyntax>( Generator.WithAccessorDeclarations( Generator.PropertyDeclaration("p", Generator.IdentifierName("x")), Generator.SetAccessorDeclaration(Accessibility.Protected, new[] { Generator.ReturnStatement() })), "x p\r\n{\r\n protected set\r\n {\r\n return;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.WithAccessorDeclarations(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("x"))), "x this[t p] { }"); VerifySyntax<IndexerDeclarationSyntax>( Generator.WithAccessorDeclarations(Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("x")), Generator.GetAccessorDeclaration(Accessibility.Protected, new[] { Generator.ReturnStatement() })), "x this[t p]\r\n{\r\n protected get\r\n {\r\n return;\r\n }\r\n}"); VerifySyntax<IndexerDeclarationSyntax>( Generator.WithAccessorDeclarations( Generator.IndexerDeclaration(new[] { Generator.ParameterDeclaration("p", Generator.IdentifierName("t")) }, Generator.IdentifierName("x")), Generator.SetAccessorDeclaration(Accessibility.Protected, new[] { Generator.ReturnStatement() })), "x this[t p]\r\n{\r\n protected set\r\n {\r\n return;\r\n }\r\n}"); } [Fact] public void TestAccessorsOnSpecialProperties() { var root = SyntaxFactory.ParseCompilationUnit( @"class C { public int X { get; set; } = 100; public int Y => 300; }"); var x = Generator.GetMembers(root.Members[0])[0]; var y = Generator.GetMembers(root.Members[0])[1]; Assert.Equal(2, Generator.GetAccessors(x).Count); Assert.Equal(0, Generator.GetAccessors(y).Count); // adding accessors to expression value property will not succeed var y2 = Generator.AddAccessors(y, new[] { Generator.GetAccessor(x, DeclarationKind.GetAccessor) }); Assert.NotNull(y2); Assert.Equal(0, Generator.GetAccessors(y2).Count); } [Fact] public void TestAccessorsOnSpecialIndexers() { var root = SyntaxFactory.ParseCompilationUnit( @"class C { public int this[int p] { get { return p * 10; } set { } }; public int this[int p] => p * 10; }"); var x = Generator.GetMembers(root.Members[0])[0]; var y = Generator.GetMembers(root.Members[0])[1]; Assert.Equal(2, Generator.GetAccessors(x).Count); Assert.Equal(0, Generator.GetAccessors(y).Count); // adding accessors to expression value indexer will not succeed var y2 = Generator.AddAccessors(y, new[] { Generator.GetAccessor(x, DeclarationKind.GetAccessor) }); Assert.NotNull(y2); Assert.Equal(0, Generator.GetAccessors(y2).Count); } [Fact] public void TestExpressionsOnSpecialProperties() { // you can get/set expression from both expression value property and initialized properties var root = SyntaxFactory.ParseCompilationUnit( @"class C { public int X { get; set; } = 100; public int Y => 300; public int Z { get; set; } }"); var x = Generator.GetMembers(root.Members[0])[0]; var y = Generator.GetMembers(root.Members[0])[1]; var z = Generator.GetMembers(root.Members[0])[2]; Assert.NotNull(Generator.GetExpression(x)); Assert.NotNull(Generator.GetExpression(y)); Assert.Null(Generator.GetExpression(z)); Assert.Equal("100", Generator.GetExpression(x).ToString()); Assert.Equal("300", Generator.GetExpression(y).ToString()); Assert.Equal("500", Generator.GetExpression(Generator.WithExpression(x, Generator.LiteralExpression(500))).ToString()); Assert.Equal("500", Generator.GetExpression(Generator.WithExpression(y, Generator.LiteralExpression(500))).ToString()); Assert.Equal("500", Generator.GetExpression(Generator.WithExpression(z, Generator.LiteralExpression(500))).ToString()); } [Fact] public void TestExpressionsOnSpecialIndexers() { // you can get/set expression from both expression value property and initialized properties var root = SyntaxFactory.ParseCompilationUnit( @"class C { public int this[int p] { get { return p * 10; } set { } }; public int this[int p] => p * 10; }"); var x = Generator.GetMembers(root.Members[0])[0]; var y = Generator.GetMembers(root.Members[0])[1]; Assert.Null(Generator.GetExpression(x)); Assert.NotNull(Generator.GetExpression(y)); Assert.Equal("p * 10", Generator.GetExpression(y).ToString()); Assert.Null(Generator.GetExpression(Generator.WithExpression(x, Generator.LiteralExpression(500)))); Assert.Equal("500", Generator.GetExpression(Generator.WithExpression(y, Generator.LiteralExpression(500))).ToString()); } [Fact] public void TestGetStatements() { var stmts = new[] { // x = y; Generator.ExpressionStatement(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), // fn(arg); Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("fn"), Generator.IdentifierName("arg"))) }; Assert.Equal(0, Generator.GetStatements(Generator.MethodDeclaration("m")).Count); Assert.Equal(2, Generator.GetStatements(Generator.MethodDeclaration("m", statements: stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.ConstructorDeclaration()).Count); Assert.Equal(2, Generator.GetStatements(Generator.ConstructorDeclaration(statements: stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.VoidReturningLambdaExpression(new SyntaxNode[] { })).Count); Assert.Equal(2, Generator.GetStatements(Generator.VoidReturningLambdaExpression(stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.ValueReturningLambdaExpression(new SyntaxNode[] { })).Count); Assert.Equal(2, Generator.GetStatements(Generator.ValueReturningLambdaExpression(stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.IdentifierName("x")).Count); } [Fact] public void TestWithStatements() { var stmts = new[] { // x = y; Generator.ExpressionStatement(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), // fn(arg); Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("fn"), Generator.IdentifierName("arg"))) }; Assert.Equal(2, Generator.GetStatements(Generator.WithStatements(Generator.MethodDeclaration("m"), stmts)).Count); Assert.Equal(2, Generator.GetStatements(Generator.WithStatements(Generator.ConstructorDeclaration(), stmts)).Count); Assert.Equal(2, Generator.GetStatements(Generator.WithStatements(Generator.VoidReturningLambdaExpression(new SyntaxNode[] { }), stmts)).Count); Assert.Equal(2, Generator.GetStatements(Generator.WithStatements(Generator.ValueReturningLambdaExpression(new SyntaxNode[] { }), stmts)).Count); Assert.Equal(0, Generator.GetStatements(Generator.WithStatements(Generator.IdentifierName("x"), stmts)).Count); } [Fact] public void TestGetAccessorStatements() { var stmts = new[] { // x = y; Generator.ExpressionStatement(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), // fn(arg); Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("fn"), Generator.IdentifierName("arg"))) }; var p = Generator.ParameterDeclaration("p", Generator.IdentifierName("t")); // get-accessor Assert.Equal(0, Generator.GetGetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetGetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), getAccessorStatements: stmts)).Count); Assert.Equal(0, Generator.GetGetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetGetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t"), getAccessorStatements: stmts)).Count); Assert.Equal(0, Generator.GetGetAccessorStatements(Generator.IdentifierName("x")).Count); // set-accessor Assert.Equal(0, Generator.GetSetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetSetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t"), setAccessorStatements: stmts)).Count); Assert.Equal(0, Generator.GetSetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t"))).Count); Assert.Equal(2, Generator.GetSetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t"), setAccessorStatements: stmts)).Count); Assert.Equal(0, Generator.GetSetAccessorStatements(Generator.IdentifierName("x")).Count); } [Fact] public void TestWithAccessorStatements() { var stmts = new[] { // x = y; Generator.ExpressionStatement(Generator.AssignmentStatement(Generator.IdentifierName("x"), Generator.IdentifierName("y"))), // fn(arg); Generator.ExpressionStatement(Generator.InvocationExpression(Generator.IdentifierName("fn"), Generator.IdentifierName("arg"))) }; var p = Generator.ParameterDeclaration("p", Generator.IdentifierName("t")); // get-accessor Assert.Equal(2, Generator.GetGetAccessorStatements(Generator.WithGetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")), stmts)).Count); Assert.Equal(2, Generator.GetGetAccessorStatements(Generator.WithGetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t")), stmts)).Count); Assert.Equal(0, Generator.GetGetAccessorStatements(Generator.WithGetAccessorStatements(Generator.IdentifierName("x"), stmts)).Count); // set-accessor Assert.Equal(2, Generator.GetSetAccessorStatements(Generator.WithSetAccessorStatements(Generator.PropertyDeclaration("p", Generator.IdentifierName("t")), stmts)).Count); Assert.Equal(2, Generator.GetSetAccessorStatements(Generator.WithSetAccessorStatements(Generator.IndexerDeclaration(new[] { p }, Generator.IdentifierName("t")), stmts)).Count); Assert.Equal(0, Generator.GetSetAccessorStatements(Generator.WithSetAccessorStatements(Generator.IdentifierName("x"), stmts)).Count); } [Fact] public void TestGetBaseAndInterfaceTypes() { var classBI = SyntaxFactory.ParseCompilationUnit( @"class C : B, I { }").Members[0]; var baseListBI = Generator.GetBaseAndInterfaceTypes(classBI); Assert.NotNull(baseListBI); Assert.Equal(2, baseListBI.Count); Assert.Equal("B", baseListBI[0].ToString()); Assert.Equal("I", baseListBI[1].ToString()); var classB = SyntaxFactory.ParseCompilationUnit( @"class C : B { }").Members[0]; var baseListB = Generator.GetBaseAndInterfaceTypes(classB); Assert.NotNull(baseListB); Assert.Equal(1, baseListB.Count); Assert.Equal("B", baseListB[0].ToString()); var classN = SyntaxFactory.ParseCompilationUnit( @"class C { }").Members[0]; var baseListN = Generator.GetBaseAndInterfaceTypes(classN); Assert.NotNull(baseListN); Assert.Equal(0, baseListN.Count); } [Fact] public void TestRemoveBaseAndInterfaceTypes() { var classBI = SyntaxFactory.ParseCompilationUnit( @"class C : B, I { }").Members[0]; var baseListBI = Generator.GetBaseAndInterfaceTypes(classBI); Assert.NotNull(baseListBI); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNode(classBI, baseListBI[0]), @"class C : I { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNode(classBI, baseListBI[1]), @"class C : B { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(classBI, baseListBI), @"class C { }"); } [Fact] public void TestAddBaseType() { var classC = SyntaxFactory.ParseCompilationUnit( @"class C { }").Members[0]; var classCI = SyntaxFactory.ParseCompilationUnit( @"class C : I { }").Members[0]; var classCB = SyntaxFactory.ParseCompilationUnit( @"class C : B { }").Members[0]; VerifySyntax<ClassDeclarationSyntax>( Generator.AddBaseType(classC, Generator.IdentifierName("T")), @"class C : T { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.AddBaseType(classCI, Generator.IdentifierName("T")), @"class C : T, I { }"); // TODO: find way to avoid this VerifySyntax<ClassDeclarationSyntax>( Generator.AddBaseType(classCB, Generator.IdentifierName("T")), @"class C : T, B { }"); } [Fact] public void TestAddInterfaceTypes() { var classC = SyntaxFactory.ParseCompilationUnit( @"class C { }").Members[0]; var classCI = SyntaxFactory.ParseCompilationUnit( @"class C : I { }").Members[0]; var classCB = SyntaxFactory.ParseCompilationUnit( @"class C : B { }").Members[0]; VerifySyntax<ClassDeclarationSyntax>( Generator.AddInterfaceType(classC, Generator.IdentifierName("T")), @"class C : T { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.AddInterfaceType(classCI, Generator.IdentifierName("T")), @"class C : I, T { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.AddInterfaceType(classCB, Generator.IdentifierName("T")), @"class C : B, T { }"); } [Fact] public void TestMultiFieldDeclarations() { var comp = Compile( @"public class C { public static int X, Y, Z; }"); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var symbolX = (IFieldSymbol)symbolC.GetMembers("X").First(); var symbolY = (IFieldSymbol)symbolC.GetMembers("Y").First(); var symbolZ = (IFieldSymbol)symbolC.GetMembers("Z").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); var declX = Generator.GetDeclaration(symbolX.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); var declY = Generator.GetDeclaration(symbolY.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); var declZ = Generator.GetDeclaration(symbolZ.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(declX)); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(declY)); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(declZ)); Assert.NotNull(Generator.GetType(declX)); Assert.Equal("int", Generator.GetType(declX).ToString()); Assert.Equal("X", Generator.GetName(declX)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(declX)); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(declX)); Assert.NotNull(Generator.GetType(declY)); Assert.Equal("int", Generator.GetType(declY).ToString()); Assert.Equal("Y", Generator.GetName(declY)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(declY)); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(declY)); Assert.NotNull(Generator.GetType(declZ)); Assert.Equal("int", Generator.GetType(declZ).ToString()); Assert.Equal("Z", Generator.GetName(declZ)); Assert.Equal(Accessibility.Public, Generator.GetAccessibility(declZ)); Assert.Equal(DeclarationModifiers.Static, Generator.GetModifiers(declZ)); var xTypedT = Generator.WithType(declX, Generator.IdentifierName("T")); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xTypedT)); Assert.Equal(SyntaxKind.FieldDeclaration, xTypedT.Kind()); Assert.Equal("T", Generator.GetType(xTypedT).ToString()); var xNamedQ = Generator.WithName(declX, "Q"); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xNamedQ)); Assert.Equal(SyntaxKind.FieldDeclaration, xNamedQ.Kind()); Assert.Equal("Q", Generator.GetName(xNamedQ).ToString()); var xInitialized = Generator.WithExpression(declX, Generator.IdentifierName("e")); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xInitialized)); Assert.Equal(SyntaxKind.FieldDeclaration, xInitialized.Kind()); Assert.Equal("e", Generator.GetExpression(xInitialized).ToString()); var xPrivate = Generator.WithAccessibility(declX, Accessibility.Private); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xPrivate)); Assert.Equal(SyntaxKind.FieldDeclaration, xPrivate.Kind()); Assert.Equal(Accessibility.Private, Generator.GetAccessibility(xPrivate)); var xReadOnly = Generator.WithModifiers(declX, DeclarationModifiers.ReadOnly); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xReadOnly)); Assert.Equal(SyntaxKind.FieldDeclaration, xReadOnly.Kind()); Assert.Equal(DeclarationModifiers.ReadOnly, Generator.GetModifiers(xReadOnly)); var xAttributed = Generator.AddAttributes(declX, Generator.Attribute("A")); Assert.Equal(DeclarationKind.Field, Generator.GetDeclarationKind(xAttributed)); Assert.Equal(SyntaxKind.FieldDeclaration, xAttributed.Kind()); Assert.Equal(1, Generator.GetAttributes(xAttributed).Count); Assert.Equal("[A]", Generator.GetAttributes(xAttributed)[0].ToString()); var membersC = Generator.GetMembers(declC); Assert.Equal(3, membersC.Count); Assert.Equal(declX, membersC[0]); Assert.Equal(declY, membersC[1]); Assert.Equal(declZ, membersC[2]); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public class C { T A; public static int X, Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertMembers(declC, 1, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public class C { public static int X; T A; public static int Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertMembers(declC, 2, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public class C { public static int X, Y; T A; public static int Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertMembers(declC, 3, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public class C { public static int X, Y, Z; T A; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ClassDeclaration("C", members: new[] { declX, declY }), @"class C { public static int X; public static int Y; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, xTypedT), @"public class C { public static T X; public static int Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declY, Generator.WithType(declY, Generator.IdentifierName("T"))), @"public class C { public static int X; public static T Y; public static int Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declZ, Generator.WithType(declZ, Generator.IdentifierName("T"))), @"public class C { public static int X, Y; public static T Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, Generator.WithAccessibility(declX, Accessibility.Private)), @"public class C { private static int X; public static int Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, Generator.WithModifiers(declX, DeclarationModifiers.None)), @"public class C { public int X; public static int Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, Generator.WithName(declX, "Q")), @"public class C { public static int Q, Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX.GetAncestorOrThis<VariableDeclaratorSyntax>(), SyntaxFactory.VariableDeclarator("Q")), @"public class C { public static int Q, Y, Z; }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, declX, Generator.WithExpression(declX, Generator.IdentifierName("e"))), @"public class C { public static int X = e, Y, Z; }"); } [Theory, WorkItem(48789, "https://github.com/dotnet/roslyn/issues/48789")] [InlineData("record")] [InlineData("record class")] public void TestInsertMembersOnRecord_SemiColon(string typeKind) { var comp = Compile( $@"public {typeKind} C; "); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax<RecordDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), $@"public {typeKind} C {{ T A; }}"); } [Fact, WorkItem(48789, "https://github.com/dotnet/roslyn/issues/48789")] public void TestInsertMembersOnRecordStruct_SemiColon() { var src = @"public record struct C; "; var comp = CSharpCompilation.Create("test") .AddReferences(TestMetadata.Net451.mscorlib) .AddSyntaxTrees(SyntaxFactory.ParseSyntaxTree(src, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview))); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax<RecordDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public record struct C { T A; }"); } [Fact, WorkItem(48789, "https://github.com/dotnet/roslyn/issues/48789")] public void TestInsertMembersOnRecord_Braces() { var comp = Compile( @"public record C { } "); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax<RecordDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public record C { T A; }"); } [Fact, WorkItem(48789, "https://github.com/dotnet/roslyn/issues/48789")] public void TestInsertMembersOnRecord_BracesAndSemiColon() { var comp = Compile( @"public record C { }; "); var symbolC = (INamedTypeSymbol)comp.GlobalNamespace.GetMembers("C").First(); var declC = Generator.GetDeclaration(symbolC.DeclaringSyntaxReferences.Select(x => x.GetSyntax()).First()); VerifySyntax<RecordDeclarationSyntax>( Generator.InsertMembers(declC, 0, Generator.FieldDeclaration("A", Generator.IdentifierName("T"))), @"public record C { T A; }"); } [Fact] public void TestMultiAttributeDeclarations() { var comp = Compile( @"[X, Y, Z] public class C { }"); var symbolC = comp.GlobalNamespace.GetMembers("C").First(); var declC = symbolC.DeclaringSyntaxReferences.First().GetSyntax(); var attrs = Generator.GetAttributes(declC); var attrX = attrs[0]; var attrY = attrs[1]; var attrZ = attrs[2]; Assert.Equal(3, attrs.Count); Assert.Equal("X", Generator.GetName(attrX)); Assert.Equal("Y", Generator.GetName(attrY)); Assert.Equal("Z", Generator.GetName(attrZ)); var xNamedQ = Generator.WithName(attrX, "Q"); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(xNamedQ)); Assert.Equal(SyntaxKind.AttributeList, xNamedQ.Kind()); Assert.Equal("[Q]", xNamedQ.ToString()); var xWithArg = Generator.AddAttributeArguments(attrX, new[] { Generator.AttributeArgument(Generator.IdentifierName("e")) }); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(xWithArg)); Assert.Equal(SyntaxKind.AttributeList, xWithArg.Kind()); Assert.Equal("[X(e)]", xWithArg.ToString()); // Inserting new attributes VerifySyntax<ClassDeclarationSyntax>( Generator.InsertAttributes(declC, 0, Generator.Attribute("A")), @"[A] [X, Y, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertAttributes(declC, 1, Generator.Attribute("A")), @"[X] [A] [Y, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertAttributes(declC, 2, Generator.Attribute("A")), @"[X, Y] [A] [Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.InsertAttributes(declC, 3, Generator.Attribute("A")), @"[X, Y, Z] [A] public class C { }"); // Removing attributes VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrX }), @"[Y, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrY }), @"[X, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrZ }), @"[X, Y] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrX, attrY }), @"[Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrX, attrZ }), @"[Y] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrY, attrZ }), @"[X] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.RemoveNodes(declC, new[] { attrX, attrY, attrZ }), @"public class C { }"); // Replacing attributes VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, attrX, Generator.Attribute("A")), @"[A, Y, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, attrY, Generator.Attribute("A")), @"[X, A, Z] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, attrZ, Generator.Attribute("A")), @"[X, Y, A] public class C { }"); VerifySyntax<ClassDeclarationSyntax>( Generator.ReplaceNode(declC, attrX, Generator.AddAttributeArguments(attrX, new[] { Generator.AttributeArgument(Generator.IdentifierName("e")) })), @"[X(e), Y, Z] public class C { }"); } [Fact] public void TestMultiReturnAttributeDeclarations() { var comp = Compile( @"public class C { [return: X, Y, Z] public void M() { } }"); var symbolC = comp.GlobalNamespace.GetMembers("C").First(); var declC = symbolC.DeclaringSyntaxReferences.First().GetSyntax(); var declM = Generator.GetMembers(declC).First(); Assert.Equal(0, Generator.GetAttributes(declM).Count); var attrs = Generator.GetReturnAttributes(declM); Assert.Equal(3, attrs.Count); var attrX = attrs[0]; var attrY = attrs[1]; var attrZ = attrs[2]; Assert.Equal("X", Generator.GetName(attrX)); Assert.Equal("Y", Generator.GetName(attrY)); Assert.Equal("Z", Generator.GetName(attrZ)); var xNamedQ = Generator.WithName(attrX, "Q"); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(xNamedQ)); Assert.Equal(SyntaxKind.AttributeList, xNamedQ.Kind()); Assert.Equal("[Q]", xNamedQ.ToString()); var xWithArg = Generator.AddAttributeArguments(attrX, new[] { Generator.AttributeArgument(Generator.IdentifierName("e")) }); Assert.Equal(DeclarationKind.Attribute, Generator.GetDeclarationKind(xWithArg)); Assert.Equal(SyntaxKind.AttributeList, xWithArg.Kind()); Assert.Equal("[X(e)]", xWithArg.ToString()); // Inserting new attributes VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 0, Generator.Attribute("A")), @"[return: A] [return: X, Y, Z] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 1, Generator.Attribute("A")), @"[return: X] [return: A] [return: Y, Z] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 2, Generator.Attribute("A")), @"[return: X, Y] [return: A] [return: Z] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 3, Generator.Attribute("A")), @"[return: X, Y, Z] [return: A] public void M() { }"); // replacing VerifySyntax<MethodDeclarationSyntax>( Generator.ReplaceNode(declM, attrX, Generator.Attribute("Q")), @"[return: Q, Y, Z] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.ReplaceNode(declM, attrX, Generator.AddAttributeArguments(attrX, new[] { Generator.AttributeArgument(Generator.IdentifierName("e")) })), @"[return: X(e), Y, Z] public void M() { }"); } [Fact] public void TestMixedAttributeDeclarations() { var comp = Compile( @"public class C { [X] [return: A] [Y, Z] [return: B, C, D] [P] public void M() { } }"); var symbolC = comp.GlobalNamespace.GetMembers("C").First(); var declC = symbolC.DeclaringSyntaxReferences.First().GetSyntax(); var declM = Generator.GetMembers(declC).First(); var attrs = Generator.GetAttributes(declM); Assert.Equal(4, attrs.Count); var attrX = attrs[0]; Assert.Equal("X", Generator.GetName(attrX)); Assert.Equal(SyntaxKind.AttributeList, attrX.Kind()); var attrY = attrs[1]; Assert.Equal("Y", Generator.GetName(attrY)); Assert.Equal(SyntaxKind.Attribute, attrY.Kind()); var attrZ = attrs[2]; Assert.Equal("Z", Generator.GetName(attrZ)); Assert.Equal(SyntaxKind.Attribute, attrZ.Kind()); var attrP = attrs[3]; Assert.Equal("P", Generator.GetName(attrP)); Assert.Equal(SyntaxKind.AttributeList, attrP.Kind()); var rattrs = Generator.GetReturnAttributes(declM); Assert.Equal(4, rattrs.Count); var attrA = rattrs[0]; Assert.Equal("A", Generator.GetName(attrA)); Assert.Equal(SyntaxKind.AttributeList, attrA.Kind()); var attrB = rattrs[1]; Assert.Equal("B", Generator.GetName(attrB)); Assert.Equal(SyntaxKind.Attribute, attrB.Kind()); var attrC = rattrs[2]; Assert.Equal("C", Generator.GetName(attrC)); Assert.Equal(SyntaxKind.Attribute, attrC.Kind()); var attrD = rattrs[3]; Assert.Equal("D", Generator.GetName(attrD)); Assert.Equal(SyntaxKind.Attribute, attrD.Kind()); // inserting VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 0, Generator.Attribute("Q")), @"[Q] [X] [return: A] [Y, Z] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 1, Generator.Attribute("Q")), @"[X] [return: A] [Q] [Y, Z] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 2, Generator.Attribute("Q")), @"[X] [return: A] [Y] [Q] [Z] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 3, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B, C, D] [Q] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertAttributes(declM, 4, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B, C, D] [P] [Q] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 0, Generator.Attribute("Q")), @"[X] [return: Q] [return: A] [Y, Z] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 1, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: Q] [return: B, C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 2, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B] [return: Q] [return: C, D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 3, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B, C] [return: Q] [return: D] [P] public void M() { }"); VerifySyntax<MethodDeclarationSyntax>( Generator.InsertReturnAttributes(declM, 4, Generator.Attribute("Q")), @"[X] [return: A] [Y, Z] [return: B, C, D] [return: Q] [P] public void M() { }"); } [WorkItem(293, "https://github.com/dotnet/roslyn/issues/293")] [Fact] [Trait(Traits.Feature, Traits.Features.Formatting)] public void IntroduceBaseList() { var text = @" public class C { } "; var expected = @" public class C : IDisposable { } "; var root = SyntaxFactory.ParseCompilationUnit(text); var decl = root.DescendantNodes().OfType<ClassDeclarationSyntax>().First(); var newDecl = Generator.AddInterfaceType(decl, Generator.IdentifierName("IDisposable")); var newRoot = root.ReplaceNode(decl, newDecl); var elasticOnlyFormatted = Formatter.Format(newRoot, SyntaxAnnotation.ElasticAnnotation, _workspace).ToFullString(); Assert.Equal(expected, elasticOnlyFormatted); } #endregion #region DeclarationModifiers [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestNamespaceModifiers() { TestModifiersAsync(DeclarationModifiers.None, @" [|namespace N1 { }|]"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestFileScopedNamespaceModifiers() { TestModifiersAsync(DeclarationModifiers.None, @" [|namespace N1;|]"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestClassModifiers1() { TestModifiersAsync(DeclarationModifiers.Static, @" [|static class C { }|]"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestMethodModifiers1() { TestModifiersAsync(DeclarationModifiers.Sealed | DeclarationModifiers.Override, @" class C { [|public sealed override void M() { }|] }"); } [Fact] public void TestAsyncMethodModifier() { TestModifiersAsync(DeclarationModifiers.Async, @" using System.Threading.Tasks; class C { [|public async Task DoAsync() { await Task.CompletedTask; }|] } "); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestPropertyModifiers1() { TestModifiersAsync(DeclarationModifiers.Virtual | DeclarationModifiers.ReadOnly, @" class C { [|public virtual int X => 0;|] }"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestFieldModifiers1() { TestModifiersAsync(DeclarationModifiers.Static, @" class C { public static int [|X|]; }"); } [Fact, WorkItem(1084965, " https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1084965")] public void TestEvent1() { TestModifiersAsync(DeclarationModifiers.Virtual, @" class C { public virtual event System.Action [|X|]; }"); } private static void TestModifiersAsync(DeclarationModifiers modifiers, string markup) { MarkupTestFile.GetSpan(markup, out var code, out var span); var compilation = Compile(code); var tree = compilation.SyntaxTrees.Single(); var semanticModel = compilation.GetSemanticModel(tree); var root = tree.GetRoot(); var node = root.FindNode(span, getInnermostNodeForTie: true); var declaration = semanticModel.GetDeclaredSymbol(node); Assert.NotNull(declaration); Assert.Equal(modifiers, DeclarationModifiers.From(declaration)); } #endregion } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Analyzers/Core/Analyzers/UseConditionalExpression/ForReturn/UseConditionalExpressionForReturnHelpers.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 Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis.UseConditionalExpression { internal static class UseConditionalExpressionForReturnHelpers { public static bool TryMatchPattern( ISyntaxFacts syntaxFacts, IConditionalOperation ifOperation, ISymbol containingSymbol, [NotNullWhen(true)] out IOperation? trueStatement, [NotNullWhen(true)] out IOperation? falseStatement, out IReturnOperation? trueReturn, out IReturnOperation? falseReturn) { trueReturn = null; falseReturn = null; trueStatement = ifOperation.WhenTrue; falseStatement = ifOperation.WhenFalse; // we support: // // if (expr) // return a; // else // return b; // // and // // if (expr) // return a; // // return b; // // note: either (but not both) of these statements can be throw-statements. if (falseStatement == null) { if (ifOperation.Parent is not IBlockOperation parentBlock) return false; var ifIndex = parentBlock.Operations.IndexOf(ifOperation); if (ifIndex < 0) return false; if (ifIndex + 1 >= parentBlock.Operations.Length) return false; falseStatement = parentBlock.Operations[ifIndex + 1]; if (falseStatement.IsImplicit) return false; } trueStatement = UseConditionalExpressionHelpers.UnwrapSingleStatementBlock(trueStatement); falseStatement = UseConditionalExpressionHelpers.UnwrapSingleStatementBlock(falseStatement); // Both return-statements must be of the form "return value" if (!IsReturnExprOrThrow(trueStatement) || !IsReturnExprOrThrow(falseStatement)) { return false; } trueReturn = trueStatement as IReturnOperation; falseReturn = falseStatement as IReturnOperation; var trueThrow = trueStatement as IThrowOperation; var falseThrow = falseStatement as IThrowOperation; var anyReturn = trueReturn ?? falseReturn; if (UseConditionalExpressionHelpers.HasInconvertibleThrowStatement( syntaxFacts, anyReturn.GetRefKind(containingSymbol) != RefKind.None, trueThrow, falseThrow)) { return false; } if (trueReturn != null && falseReturn != null && trueReturn.Kind != falseReturn.Kind) { // Not allowed if these are different types of returns. i.e. // "yield return ..." and "return ...". return false; } if (trueReturn?.Kind == OperationKind.YieldBreak) { // This check is just paranoia. We likely shouldn't get here since we already // checked if .ReturnedValue was null above. return false; } if (trueReturn?.Kind == OperationKind.YieldReturn && ifOperation.WhenFalse == null) { // we have the following: // // if (...) { // yield return ... // } // // yield return ... // // It is *not* correct to replace this with: // // yield return ... ? ... ? ... // // as both yields need to be hit. return false; } return UseConditionalExpressionHelpers.CanConvert( syntaxFacts, ifOperation, trueStatement, falseStatement); } private static bool IsReturnExprOrThrow(IOperation? statement) { // We can only convert a `throw expr` to a throw expression, not `throw;` if (statement is IThrowOperation throwOperation) return throwOperation.Exception != null; return statement is IReturnOperation returnOp && returnOp.ReturnedValue != null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis.UseConditionalExpression { internal static class UseConditionalExpressionForReturnHelpers { public static bool TryMatchPattern( ISyntaxFacts syntaxFacts, IConditionalOperation ifOperation, ISymbol containingSymbol, [NotNullWhen(true)] out IOperation? trueStatement, [NotNullWhen(true)] out IOperation? falseStatement, out IReturnOperation? trueReturn, out IReturnOperation? falseReturn) { trueReturn = null; falseReturn = null; trueStatement = ifOperation.WhenTrue; falseStatement = ifOperation.WhenFalse; // we support: // // if (expr) // return a; // else // return b; // // and // // if (expr) // return a; // // return b; // // note: either (but not both) of these statements can be throw-statements. if (falseStatement == null) { if (ifOperation.Parent is not IBlockOperation parentBlock) return false; var ifIndex = parentBlock.Operations.IndexOf(ifOperation); if (ifIndex < 0) return false; if (ifIndex + 1 >= parentBlock.Operations.Length) return false; falseStatement = parentBlock.Operations[ifIndex + 1]; if (falseStatement.IsImplicit) return false; } trueStatement = UseConditionalExpressionHelpers.UnwrapSingleStatementBlock(trueStatement); falseStatement = UseConditionalExpressionHelpers.UnwrapSingleStatementBlock(falseStatement); // Both return-statements must be of the form "return value" if (!IsReturnExprOrThrow(trueStatement) || !IsReturnExprOrThrow(falseStatement)) { return false; } trueReturn = trueStatement as IReturnOperation; falseReturn = falseStatement as IReturnOperation; var trueThrow = trueStatement as IThrowOperation; var falseThrow = falseStatement as IThrowOperation; var anyReturn = trueReturn ?? falseReturn; if (UseConditionalExpressionHelpers.HasInconvertibleThrowStatement( syntaxFacts, anyReturn.GetRefKind(containingSymbol) != RefKind.None, trueThrow, falseThrow)) { return false; } if (trueReturn != null && falseReturn != null && trueReturn.Kind != falseReturn.Kind) { // Not allowed if these are different types of returns. i.e. // "yield return ..." and "return ...". return false; } if (trueReturn?.Kind == OperationKind.YieldBreak) { // This check is just paranoia. We likely shouldn't get here since we already // checked if .ReturnedValue was null above. return false; } if (trueReturn?.Kind == OperationKind.YieldReturn && ifOperation.WhenFalse == null) { // we have the following: // // if (...) { // yield return ... // } // // yield return ... // // It is *not* correct to replace this with: // // yield return ... ? ... ? ... // // as both yields need to be hit. return false; } return UseConditionalExpressionHelpers.CanConvert( syntaxFacts, ifOperation, trueStatement, falseStatement); } private static bool IsReturnExprOrThrow(IOperation? statement) { // We can only convert a `throw expr` to a throw expression, not `throw;` if (statement is IThrowOperation throwOperation) return throwOperation.Exception != null; return statement is IReturnOperation returnOp && returnOp.ReturnedValue != null; } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Analyzers/CSharp/Analyzers/UseExpressionBody/Helpers/UseExpressionBodyForAccessorsHelper.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 Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody { internal class UseExpressionBodyForAccessorsHelper : UseExpressionBodyHelper<AccessorDeclarationSyntax> { public static readonly UseExpressionBodyForAccessorsHelper Instance = new(); private UseExpressionBodyForAccessorsHelper() : base(IDEDiagnosticIds.UseExpressionBodyForAccessorsDiagnosticId, EnforceOnBuildValues.UseExpressionBodyForAccessors, new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_expression_body_for_accessors), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)), new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_block_body_for_accessors), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)), CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ImmutableArray.Create(SyntaxKind.GetAccessorDeclaration, SyntaxKind.SetAccessorDeclaration, SyntaxKind.InitAccessorDeclaration)) { } protected override BlockSyntax GetBody(AccessorDeclarationSyntax declaration) => declaration.Body; protected override ArrowExpressionClauseSyntax GetExpressionBody(AccessorDeclarationSyntax declaration) => declaration.ExpressionBody; protected override SyntaxToken GetSemicolonToken(AccessorDeclarationSyntax declaration) => declaration.SemicolonToken; protected override AccessorDeclarationSyntax WithSemicolonToken(AccessorDeclarationSyntax declaration, SyntaxToken token) => declaration.WithSemicolonToken(token); protected override AccessorDeclarationSyntax WithExpressionBody(AccessorDeclarationSyntax declaration, ArrowExpressionClauseSyntax expressionBody) => declaration.WithExpressionBody(expressionBody); protected override AccessorDeclarationSyntax WithBody(AccessorDeclarationSyntax declaration, BlockSyntax body) => declaration.WithBody(body); protected override bool CreateReturnStatementForExpression(SemanticModel semanticModel, AccessorDeclarationSyntax declaration) => declaration.IsKind(SyntaxKind.GetAccessorDeclaration); } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.UseExpressionBody { internal class UseExpressionBodyForAccessorsHelper : UseExpressionBodyHelper<AccessorDeclarationSyntax> { public static readonly UseExpressionBodyForAccessorsHelper Instance = new(); private UseExpressionBodyForAccessorsHelper() : base(IDEDiagnosticIds.UseExpressionBodyForAccessorsDiagnosticId, EnforceOnBuildValues.UseExpressionBodyForAccessors, new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_expression_body_for_accessors), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)), new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_block_body_for_accessors), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources)), CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ImmutableArray.Create(SyntaxKind.GetAccessorDeclaration, SyntaxKind.SetAccessorDeclaration, SyntaxKind.InitAccessorDeclaration)) { } protected override BlockSyntax GetBody(AccessorDeclarationSyntax declaration) => declaration.Body; protected override ArrowExpressionClauseSyntax GetExpressionBody(AccessorDeclarationSyntax declaration) => declaration.ExpressionBody; protected override SyntaxToken GetSemicolonToken(AccessorDeclarationSyntax declaration) => declaration.SemicolonToken; protected override AccessorDeclarationSyntax WithSemicolonToken(AccessorDeclarationSyntax declaration, SyntaxToken token) => declaration.WithSemicolonToken(token); protected override AccessorDeclarationSyntax WithExpressionBody(AccessorDeclarationSyntax declaration, ArrowExpressionClauseSyntax expressionBody) => declaration.WithExpressionBody(expressionBody); protected override AccessorDeclarationSyntax WithBody(AccessorDeclarationSyntax declaration, BlockSyntax body) => declaration.WithBody(body); protected override bool CreateReturnStatementForExpression(SemanticModel semanticModel, AccessorDeclarationSyntax declaration) => declaration.IsKind(SyntaxKind.GetAccessorDeclaration); } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/DefaultKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class DefaultKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public DefaultKeywordRecommender() : base(SyntaxKind.DefaultKeyword, isValidInPreprocessorContext: true) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return IsValidPreProcessorContext(context) || context.IsStatementContext || context.IsGlobalStatementContext || context.IsAnyExpressionContext || context.TargetToken.IsSwitchLabelContext() || context.SyntaxTree.IsTypeParameterConstraintStartContext(position, context.LeftToken); } private static bool IsValidPreProcessorContext(CSharpSyntaxContext context) { // cases: // #line | // #line d| // # line | // # line d| var previousToken1 = context.TargetToken; var previousToken2 = previousToken1.GetPreviousToken(includeSkipped: true); return previousToken1.Kind() == SyntaxKind.LineKeyword && previousToken2.Kind() == SyntaxKind.HashToken; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class DefaultKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public DefaultKeywordRecommender() : base(SyntaxKind.DefaultKeyword, isValidInPreprocessorContext: true) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { return IsValidPreProcessorContext(context) || context.IsStatementContext || context.IsGlobalStatementContext || context.IsAnyExpressionContext || context.TargetToken.IsSwitchLabelContext() || context.SyntaxTree.IsTypeParameterConstraintStartContext(position, context.LeftToken); } private static bool IsValidPreProcessorContext(CSharpSyntaxContext context) { // cases: // #line | // #line d| // # line | // # line d| var previousToken1 = context.TargetToken; var previousToken2 = previousToken1.GetPreviousToken(includeSkipped: true); return previousToken1.Kind() == SyntaxKind.LineKeyword && previousToken2.Kind() == SyntaxKind.HashToken; } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/Core/CodeAnalysisTest/ObjectSerializationTests.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.IO; using System.Linq; using System.Text; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public sealed class ObjectSerializationTests { static ObjectSerializationTests() { // Register appropriate deserialization methods. new PrimitiveArrayMemberTest(); new PrimitiveMemberTest(); new PrimitiveValueTest(); } [Fact] public void TestInvalidStreamVersion() { var stream = new MemoryStream(); stream.WriteByte(0); stream.WriteByte(0); stream.Position = 0; var reader = ObjectReader.TryGetReader(stream); Assert.Null(reader); } private void RoundTrip(Action<ObjectWriter> writeAction, Action<ObjectReader> readAction, bool recursive) { using var stream = new MemoryStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true)) { writeAction(writer); } stream.Position = 0; using var reader = ObjectReader.TryGetReader(stream); readAction(reader); } private void TestRoundTrip(Action<ObjectWriter> writeAction, Action<ObjectReader> readAction) { RoundTrip(writeAction, readAction, recursive: true); RoundTrip(writeAction, readAction, recursive: false); } private T RoundTrip<T>(T value, Action<ObjectWriter, T> writeAction, Func<ObjectReader, T> readAction, bool recursive) { using var stream = new MemoryStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true)) { writeAction(writer, value); } stream.Position = 0; using var reader = ObjectReader.TryGetReader(stream); return readAction(reader); } private void TestRoundTrip<T>(T value, Action<ObjectWriter, T> writeAction, Func<ObjectReader, T> readAction, bool recursive) { var newValue = RoundTrip(value, writeAction, readAction, recursive); Assert.True(Equalish(value, newValue)); } private void TestRoundTrip<T>(T value, Action<ObjectWriter, T> writeAction, Func<ObjectReader, T> readAction) { TestRoundTrip(value, writeAction, readAction, recursive: true); TestRoundTrip(value, writeAction, readAction, recursive: false); } private T RoundTripValue<T>(T value, bool recursive) { return RoundTrip(value, (w, v) => { if (v != null && v.GetType().IsEnum) { w.WriteInt64(Convert.ToInt64((object)v)); } else { w.WriteValue(v); } }, r => value != null && value.GetType().IsEnum ? (T)Enum.ToObject(typeof(T), r.ReadInt64()) : (T)r.ReadValue(), recursive); } private void TestRoundTripValue<T>(T value, bool recursive) { var newValue = RoundTripValue(value, recursive); Assert.True(Equalish(value, newValue)); } private void TestRoundTripValue<T>(T value) { TestRoundTripValue(value, recursive: true); TestRoundTripValue(value, recursive: false); } private static bool Equalish<T>(T value1, T value2) { return object.Equals(value1, value2) || (value1 is Array && value2 is Array && ArrayEquals((Array)(object)value1, (Array)(object)value2)); } private static bool ArrayEquals(Array seq1, Array seq2) { if (seq1 == null && seq2 == null) { return true; } else if (seq1 == null || seq2 == null) { return false; } if (seq1.Length != seq2.Length) { return false; } for (int i = 0; i < seq1.Length; i++) { if (!Equalish(seq1.GetValue(i), seq2.GetValue(i))) { return false; } } return true; } private class TypeWithOneMember<T> : IObjectWritable, IEquatable<TypeWithOneMember<T>> { private readonly T _member; public TypeWithOneMember(T value) { _member = value; } private TypeWithOneMember(ObjectReader reader) { _member = typeof(T).IsEnum ? (T)Enum.ToObject(typeof(T), reader.ReadInt64()) : (T)reader.ReadValue(); } bool IObjectWritable.ShouldReuseInSerialization => true; void IObjectWritable.WriteTo(ObjectWriter writer) { if (typeof(T).IsEnum) { writer.WriteInt64(Convert.ToInt64(_member)); } else { writer.WriteValue(_member); } } static TypeWithOneMember() { ObjectBinder.RegisterTypeReader(typeof(TypeWithOneMember<T>), r => new TypeWithOneMember<T>(r)); } public override Int32 GetHashCode() { if (_member == null) { return 0; } else { return _member.GetHashCode(); } } public override Boolean Equals(Object obj) { return Equals(obj as TypeWithOneMember<T>); } public bool Equals(TypeWithOneMember<T> other) { return other != null && Equalish(_member, other._member); } } private class TypeWithTwoMembers<T, S> : IObjectWritable, IEquatable<TypeWithTwoMembers<T, S>> { private readonly T _member1; private readonly S _member2; public TypeWithTwoMembers(T value1, S value2) { _member1 = value1; _member2 = value2; } private TypeWithTwoMembers(ObjectReader reader) { _member1 = (T)reader.ReadValue(); _member2 = (S)reader.ReadValue(); } bool IObjectWritable.ShouldReuseInSerialization => true; void IObjectWritable.WriteTo(ObjectWriter writer) { writer.WriteValue(_member1); writer.WriteValue(_member2); } static TypeWithTwoMembers() { ObjectBinder.RegisterTypeReader(typeof(TypeWithTwoMembers<T, S>), r => new TypeWithTwoMembers<T, S>(r)); } public override int GetHashCode() { if (_member1 == null) { return 0; } else { return _member1.GetHashCode(); } } public override Boolean Equals(Object obj) { return Equals(obj as TypeWithTwoMembers<T, S>); } public bool Equals(TypeWithTwoMembers<T, S> other) { return other != null && Equalish(_member1, other._member1) && Equalish(_member2, other._member2); } } // this type simulates a class with many members.. // it serializes each member individually, not as an array. private class TypeWithManyMembers<T> : IObjectWritable, IEquatable<TypeWithManyMembers<T>> { private readonly T[] _members; public TypeWithManyMembers(T[] values) { _members = values; } private TypeWithManyMembers(ObjectReader reader) { var count = reader.ReadInt32(); _members = new T[count]; for (int i = 0; i < count; i++) { _members[i] = (T)reader.ReadValue(); } } bool IObjectWritable.ShouldReuseInSerialization => true; void IObjectWritable.WriteTo(ObjectWriter writer) { writer.WriteInt32(_members.Length); for (int i = 0; i < _members.Length; i++) { writer.WriteValue(_members[i]); } } static TypeWithManyMembers() { ObjectBinder.RegisterTypeReader(typeof(TypeWithManyMembers<T>), r => new TypeWithManyMembers<T>(r)); } public override int GetHashCode() { return _members.Length; } public override Boolean Equals(Object obj) { return Equals(obj as TypeWithManyMembers<T>); } public bool Equals(TypeWithManyMembers<T> other) { if (other == null) { return false; } if (_members.Length != other._members.Length) { return false; } return Equalish(_members, other._members); } } private void TestRoundTripMember<T>(T value) { TestRoundTripValue(new TypeWithOneMember<T>(value)); } private void TestRoundTripMembers<T, S>(T value1, S value2) { TestRoundTripValue(new TypeWithTwoMembers<T, S>(value1, value2)); } private void TestRoundTripMembers<T>(params T[] values) { TestRoundTripValue(new TypeWithManyMembers<T>(values)); } [Fact] public void TestValueInt32() { TestRoundTripValue(123); } [Fact] public void TestMemberInt32() { TestRoundTripMember(123); } [Fact] public void TestMemberIntString() { TestRoundTripMembers(123, "Hello"); } [Fact] public void TestManyMembersInt32() { TestRoundTripMembers(Enumerable.Range(0, 1000).ToArray()); } [Fact] public void TestSmallArrayMember() { TestRoundTripMember(Enumerable.Range(0, 3).ToArray()); } [Fact] public void TestEmptyArrayMember() { TestRoundTripMember(new int[] { }); } [Fact] public void TestNullArrayMember() { TestRoundTripMember<int[]>(null); } [Fact] public void TestLargeArrayMember() { TestRoundTripMember(Enumerable.Range(0, 1000).ToArray()); } [Fact] public void TestEnumMember() { TestRoundTripMember(EByte.Value); } [Fact] public void TestInt32EncodingKinds() { Assert.Equal(ObjectWriter.EncodingKind.Int32_1, ObjectWriter.EncodingKind.Int32_0 + 1); Assert.Equal(ObjectWriter.EncodingKind.Int32_2, ObjectWriter.EncodingKind.Int32_0 + 2); Assert.Equal(ObjectWriter.EncodingKind.Int32_3, ObjectWriter.EncodingKind.Int32_0 + 3); Assert.Equal(ObjectWriter.EncodingKind.Int32_4, ObjectWriter.EncodingKind.Int32_0 + 4); Assert.Equal(ObjectWriter.EncodingKind.Int32_5, ObjectWriter.EncodingKind.Int32_0 + 5); Assert.Equal(ObjectWriter.EncodingKind.Int32_6, ObjectWriter.EncodingKind.Int32_0 + 6); Assert.Equal(ObjectWriter.EncodingKind.Int32_7, ObjectWriter.EncodingKind.Int32_0 + 7); Assert.Equal(ObjectWriter.EncodingKind.Int32_8, ObjectWriter.EncodingKind.Int32_0 + 8); Assert.Equal(ObjectWriter.EncodingKind.Int32_9, ObjectWriter.EncodingKind.Int32_0 + 9); Assert.Equal(ObjectWriter.EncodingKind.Int32_10, ObjectWriter.EncodingKind.Int32_0 + 10); } [Fact] public void TestUInt32EncodingKinds() { Assert.Equal(ObjectWriter.EncodingKind.UInt32_1, ObjectWriter.EncodingKind.UInt32_0 + 1); Assert.Equal(ObjectWriter.EncodingKind.UInt32_2, ObjectWriter.EncodingKind.UInt32_0 + 2); Assert.Equal(ObjectWriter.EncodingKind.UInt32_3, ObjectWriter.EncodingKind.UInt32_0 + 3); Assert.Equal(ObjectWriter.EncodingKind.UInt32_4, ObjectWriter.EncodingKind.UInt32_0 + 4); Assert.Equal(ObjectWriter.EncodingKind.UInt32_5, ObjectWriter.EncodingKind.UInt32_0 + 5); Assert.Equal(ObjectWriter.EncodingKind.UInt32_6, ObjectWriter.EncodingKind.UInt32_0 + 6); Assert.Equal(ObjectWriter.EncodingKind.UInt32_7, ObjectWriter.EncodingKind.UInt32_0 + 7); Assert.Equal(ObjectWriter.EncodingKind.UInt32_8, ObjectWriter.EncodingKind.UInt32_0 + 8); Assert.Equal(ObjectWriter.EncodingKind.UInt32_9, ObjectWriter.EncodingKind.UInt32_0 + 9); Assert.Equal(ObjectWriter.EncodingKind.UInt32_10, ObjectWriter.EncodingKind.UInt32_0 + 10); } private void TestRoundTripType(Type type) { TestRoundTrip(type, (w, v) => w.WriteType(v), r => r.ReadType()); } [Fact] public void TestTypes() { TestRoundTripType(typeof(int)); TestRoundTripType(typeof(string)); TestRoundTripType(typeof(ObjectSerializationTests)); } private void TestRoundTripCompressedUint(uint value) { TestRoundTrip(value, (w, v) => ((ObjectWriter)w).WriteCompressedUInt(v), r => ((ObjectReader)r).ReadCompressedUInt()); } [Fact] public void TestCompressedUInt() { TestRoundTripCompressedUint(0); TestRoundTripCompressedUint(0x01u); TestRoundTripCompressedUint(0x0123u); // unique bytes tests order TestRoundTripCompressedUint(0x012345u); // unique bytes tests order TestRoundTripCompressedUint(0x01234567u); // unique bytes tests order TestRoundTripCompressedUint(0x3Fu); // largest value packed in one byte TestRoundTripCompressedUint(0x3FFFu); // largest value packed into two bytes TestRoundTripCompressedUint(0x3FFFFFu); // no three byte option yet, but test anyway TestRoundTripCompressedUint(0x3FFFFFFFu); // largest unit allowed in four bytes Assert.Throws<ArgumentException>(() => TestRoundTripCompressedUint(uint.MaxValue)); // max uint not allowed Assert.Throws<ArgumentException>(() => TestRoundTripCompressedUint(0x80000000u)); // highest bit set not allowed Assert.Throws<ArgumentException>(() => TestRoundTripCompressedUint(0x40000000u)); // second highest bit set not allowed Assert.Throws<ArgumentException>(() => TestRoundTripCompressedUint(0xC0000000u)); // both high bits set not allowed } [Fact] public void TestArraySizes() { TestArrayValues<byte>(1, 2, 3, 4, 5); TestArrayValues<sbyte>(1, 2, 3, 4, 5); TestArrayValues<short>(1, 2, 3, 4, 5); TestArrayValues<ushort>(1, 2, 3, 4, 5); TestArrayValues<int>(1, 2, 3, 4, 5); TestArrayValues<uint>(1, 2, 3, 4, 5); TestArrayValues<long>(1, 2, 3, 4, 5); TestArrayValues<ulong>(1, 2, 3, 4, 5); TestArrayValues<decimal>(1m, 2m, 3m, 4m, 5m); TestArrayValues<float>(1.0f, 2.0f, 3.0f, 4.0f, 5.0f); TestArrayValues<double>(1.0, 2.0, 3.0, 4.0, 5.0); TestArrayValues<char>('1', '2', '3', '4', '5'); TestArrayValues<string>("1", "2", "3", "4", "5"); TestArrayValues( new TypeWithOneMember<int>(1), new TypeWithOneMember<int>(2), new TypeWithOneMember<int>(3), new TypeWithOneMember<int>(4), new TypeWithOneMember<int>(5)); } private void TestArrayValues<T>(T v1, T v2, T v3, T v4, T v5) { TestRoundTripValue((T[])null); TestRoundTripValue(new T[] { }); TestRoundTripValue(new T[] { v1 }); TestRoundTripValue(new T[] { v1, v2 }); TestRoundTripValue(new T[] { v1, v2, v3 }); TestRoundTripValue(new T[] { v1, v2, v3, v4 }); TestRoundTripValue(new T[] { v1, v2, v3, v4, v5 }); } [Fact] public void TestPrimitiveArrayValues() { TestRoundTrip(w => TestWritingPrimitiveArrays(w), r => TestReadingPrimitiveArrays(r)); } [Theory] [CombinatorialData] public void TestByteSpan([CombinatorialValues(0, 1, 2, 3, 1000, 1000000)] int size) { var data = new byte[size]; for (int i = 0; i < data.Length; i++) { data[i] = (byte)i; } TestRoundTrip(w => TestWritingByteSpan(data, w), r => TestReadingByteSpan(data, r)); } [Fact] public void TestPrimitiveArrayMembers() { TestRoundTrip(w => w.WriteValue(new PrimitiveArrayMemberTest()), r => r.ReadValue()); } public class PrimitiveArrayMemberTest : IObjectWritable { public PrimitiveArrayMemberTest() { } private PrimitiveArrayMemberTest(ObjectReader reader) { TestReadingPrimitiveArrays(reader); } bool IObjectWritable.ShouldReuseInSerialization => true; void IObjectWritable.WriteTo(ObjectWriter writer) { TestWritingPrimitiveArrays(writer); } static PrimitiveArrayMemberTest() { ObjectBinder.RegisterTypeReader(typeof(PrimitiveArrayMemberTest), r => new PrimitiveArrayMemberTest(r)); } } private static void TestWritingPrimitiveArrays(ObjectWriter writer) { var inputBool = new bool[] { true, false }; var inputByte = new byte[] { 1, 2, 3, 4, 5 }; var inputChar = new char[] { 'h', 'e', 'l', 'l', 'o' }; var inputDecimal = new decimal[] { 1.0M, 2.0M, 3.0M, 4.0M, 5.0M }; var inputDouble = new double[] { 1.0, 2.0, 3.0, 4.0, 5.0 }; var inputFloat = new float[] { 1.0F, 2.0F, 3.0F, 4.0F, 5.0F }; var inputInt = new int[] { -1, -2, -3, -4, -5 }; var inputLong = new long[] { 1, 2, 3, 4, 5 }; var inputSByte = new sbyte[] { -1, -2, -3, -4, -5 }; var inputShort = new short[] { -1, -2, -3, -4, -5 }; var inputUInt = new uint[] { 1, 2, 3, 4, 5 }; var inputULong = new ulong[] { 1, 2, 3, 4, 5 }; var inputUShort = new ushort[] { 1, 2, 3, 4, 5 }; var inputString = new string[] { "h", "e", "l", "l", "o" }; writer.WriteValue(inputBool); writer.WriteValue((object)inputByte); writer.WriteValue(inputChar); writer.WriteValue(inputDecimal); writer.WriteValue(inputDouble); writer.WriteValue(inputFloat); writer.WriteValue(inputInt); writer.WriteValue(inputLong); writer.WriteValue(inputSByte); writer.WriteValue(inputShort); writer.WriteValue(inputUInt); writer.WriteValue(inputULong); writer.WriteValue(inputUShort); writer.WriteValue(inputString); } private static void TestReadingPrimitiveArrays(ObjectReader reader) { var inputBool = new bool[] { true, false }; var inputByte = new byte[] { 1, 2, 3, 4, 5 }; var inputChar = new char[] { 'h', 'e', 'l', 'l', 'o' }; var inputDecimal = new decimal[] { 1.0M, 2.0M, 3.0M, 4.0M, 5.0M }; var inputDouble = new double[] { 1.0, 2.0, 3.0, 4.0, 5.0 }; var inputFloat = new float[] { 1.0F, 2.0F, 3.0F, 4.0F, 5.0F }; var inputInt = new int[] { -1, -2, -3, -4, -5 }; var inputLong = new long[] { 1, 2, 3, 4, 5 }; var inputSByte = new sbyte[] { -1, -2, -3, -4, -5 }; var inputShort = new short[] { -1, -2, -3, -4, -5 }; var inputUInt = new uint[] { 1, 2, 3, 4, 5 }; var inputULong = new ulong[] { 1, 2, 3, 4, 5 }; var inputUShort = new ushort[] { 1, 2, 3, 4, 5 }; var inputString = new string[] { "h", "e", "l", "l", "o" }; Assert.True(Enumerable.SequenceEqual(inputBool, (bool[])reader.ReadValue())); Assert.True(Enumerable.SequenceEqual(inputByte, (byte[])reader.ReadValue())); Assert.True(Enumerable.SequenceEqual(inputChar, (char[])reader.ReadValue())); Assert.True(Enumerable.SequenceEqual(inputDecimal, (decimal[])reader.ReadValue())); Assert.True(Enumerable.SequenceEqual(inputDouble, (double[])reader.ReadValue())); Assert.True(Enumerable.SequenceEqual(inputFloat, (float[])reader.ReadValue())); Assert.True(Enumerable.SequenceEqual(inputInt, (int[])reader.ReadValue())); Assert.True(Enumerable.SequenceEqual(inputLong, (long[])reader.ReadValue())); Assert.True(Enumerable.SequenceEqual(inputSByte, (sbyte[])reader.ReadValue())); Assert.True(Enumerable.SequenceEqual(inputShort, (short[])reader.ReadValue())); Assert.True(Enumerable.SequenceEqual(inputUInt, (uint[])reader.ReadValue())); Assert.True(Enumerable.SequenceEqual(inputULong, (ulong[])reader.ReadValue())); Assert.True(Enumerable.SequenceEqual(inputUShort, (ushort[])reader.ReadValue())); Assert.True(Enumerable.SequenceEqual(inputString, (string[])reader.ReadValue())); } private static void TestWritingByteSpan(byte[] data, ObjectWriter writer) { writer.WriteValue(data.AsSpan()); } private static void TestReadingByteSpan(byte[] expected, ObjectReader reader) { Assert.True(Enumerable.SequenceEqual(expected, (byte[])reader.ReadValue())); } [Fact] public void TestBooleanArrays() { for (var i = 0; i < 1000; i++) { var inputBool = new bool[i]; for (var j = 0; j < i; j++) { inputBool[j] = j % 2 == 0; } TestRoundTripValue(inputBool); TestRoundTripMember(inputBool); } } [Fact] public void TestFalseBooleanArray() { var inputBool = Enumerable.Repeat<bool>(false, 1000).ToArray(); TestRoundTripValue(inputBool); TestRoundTripMember(inputBool); } private static readonly DateTime _testNow = DateTime.Now; [Fact] public void TestPrimitiveValues() { TestRoundTripValue(true); TestRoundTripValue(false); TestRoundTripValue(Byte.MaxValue); TestRoundTripValue(SByte.MaxValue); TestRoundTripValue(Int16.MaxValue); TestRoundTripValue(Int32.MaxValue); TestRoundTripValue(Byte.MaxValue); TestRoundTripValue(Int16.MaxValue); TestRoundTripValue(Int64.MaxValue); TestRoundTripValue(UInt16.MaxValue); TestRoundTripValue(UInt32.MaxValue); TestRoundTripValue(UInt64.MaxValue); TestRoundTripValue(Decimal.MaxValue); TestRoundTripValue(Double.MaxValue); TestRoundTripValue(Single.MaxValue); TestRoundTripValue('X'); TestRoundTripValue("YYY"); TestRoundTripValue("\uD800\uDC00"); // valid surrogate pair TestRoundTripValue("\uDC00\uD800"); // invalid surrogate pair TestRoundTripValue("\uD800"); // incomplete surrogate pair TestRoundTripValue<object>(null); TestRoundTripValue(ConsoleColor.Cyan); TestRoundTripValue(EByte.Value); TestRoundTripValue(ESByte.Value); TestRoundTripValue(EShort.Value); TestRoundTripValue(EUShort.Value); TestRoundTripValue(EInt.Value); TestRoundTripValue(EUInt.Value); TestRoundTripValue(ELong.Value); TestRoundTripValue(EULong.Value); TestRoundTripValue(_testNow); } [Fact] public void TestInt32Values() { TestRoundTripValue<Int32>(0); TestRoundTripValue<Int32>(1); TestRoundTripValue<Int32>(2); TestRoundTripValue<Int32>(3); TestRoundTripValue<Int32>(4); TestRoundTripValue<Int32>(5); TestRoundTripValue<Int32>(6); TestRoundTripValue<Int32>(7); TestRoundTripValue<Int32>(8); TestRoundTripValue<Int32>(9); TestRoundTripValue<Int32>(10); TestRoundTripValue<Int32>(-1); TestRoundTripValue<Int32>(Int32.MinValue); TestRoundTripValue<Int32>(Byte.MaxValue); TestRoundTripValue<Int32>(UInt16.MaxValue); TestRoundTripValue<Int32>(Int32.MaxValue); } [Fact] public void TestUInt32Values() { TestRoundTripValue<UInt32>(0); TestRoundTripValue<UInt32>(1); TestRoundTripValue<UInt32>(2); TestRoundTripValue<UInt32>(3); TestRoundTripValue<UInt32>(4); TestRoundTripValue<UInt32>(5); TestRoundTripValue<UInt32>(6); TestRoundTripValue<UInt32>(7); TestRoundTripValue<UInt32>(8); TestRoundTripValue<UInt32>(9); TestRoundTripValue<UInt32>(10); TestRoundTripValue<Int32>(Byte.MaxValue); TestRoundTripValue<Int32>(UInt16.MaxValue); TestRoundTripValue<Int32>(Int32.MaxValue); } [Fact] public void TestInt64Values() { TestRoundTripValue<Int64>(0); TestRoundTripValue<Int64>(1); TestRoundTripValue<Int64>(2); TestRoundTripValue<Int64>(3); TestRoundTripValue<Int64>(4); TestRoundTripValue<Int64>(5); TestRoundTripValue<Int64>(6); TestRoundTripValue<Int64>(7); TestRoundTripValue<Int64>(8); TestRoundTripValue<Int64>(9); TestRoundTripValue<Int64>(10); TestRoundTripValue<Int64>(-1); TestRoundTripValue<Int64>(Byte.MinValue); TestRoundTripValue<Int64>(Byte.MaxValue); TestRoundTripValue<Int64>(Int16.MinValue); TestRoundTripValue<Int64>(Int16.MaxValue); TestRoundTripValue<Int64>(UInt16.MinValue); TestRoundTripValue<Int64>(UInt16.MaxValue); TestRoundTripValue<Int64>(Int32.MinValue); TestRoundTripValue<Int64>(Int32.MaxValue); TestRoundTripValue<Int64>(UInt32.MinValue); TestRoundTripValue<Int64>(UInt32.MaxValue); TestRoundTripValue<Int64>(Int64.MinValue); TestRoundTripValue<Int64>(Int64.MaxValue); } [Fact] public void TestUInt64Values() { TestRoundTripValue<UInt64>(0); TestRoundTripValue<UInt64>(1); TestRoundTripValue<UInt64>(2); TestRoundTripValue<UInt64>(3); TestRoundTripValue<UInt64>(4); TestRoundTripValue<UInt64>(5); TestRoundTripValue<UInt64>(6); TestRoundTripValue<UInt64>(7); TestRoundTripValue<UInt64>(8); TestRoundTripValue<UInt64>(9); TestRoundTripValue<UInt64>(10); TestRoundTripValue<UInt64>(Byte.MinValue); TestRoundTripValue<UInt64>(Byte.MaxValue); TestRoundTripValue<UInt64>(UInt16.MinValue); TestRoundTripValue<UInt64>(UInt16.MaxValue); TestRoundTripValue<UInt64>(Int32.MaxValue); TestRoundTripValue<UInt64>(UInt32.MinValue); TestRoundTripValue<UInt64>(UInt32.MaxValue); TestRoundTripValue<UInt64>(UInt64.MinValue); TestRoundTripValue<UInt64>(UInt64.MaxValue); } [Fact] public void TestPrimitiveMemberValues() { TestRoundTripMember(true); TestRoundTripMember(false); TestRoundTripMember(Byte.MaxValue); TestRoundTripMember(SByte.MaxValue); TestRoundTripMember(Int16.MaxValue); TestRoundTripMember(Int32.MaxValue); TestRoundTripMember(Byte.MaxValue); TestRoundTripMember(Int16.MaxValue); TestRoundTripMember(Int64.MaxValue); TestRoundTripMember(UInt16.MaxValue); TestRoundTripMember(UInt32.MaxValue); TestRoundTripMember(UInt64.MaxValue); TestRoundTripMember(Decimal.MaxValue); TestRoundTripMember(Double.MaxValue); TestRoundTripMember(Single.MaxValue); TestRoundTripMember('X'); TestRoundTripMember("YYY"); TestRoundTripMember("\uD800\uDC00"); // valid surrogate pair TestRoundTripMember("\uDC00\uD800"); // invalid surrogate pair TestRoundTripMember("\uD800"); // incomplete surrogate pair TestRoundTripMember<object>(null); TestRoundTripMember(ConsoleColor.Cyan); TestRoundTripMember(EByte.Value); TestRoundTripMember(ESByte.Value); TestRoundTripMember(EShort.Value); TestRoundTripMember(EUShort.Value); TestRoundTripMember(EInt.Value); TestRoundTripMember(EUInt.Value); TestRoundTripMember(ELong.Value); TestRoundTripMember(EULong.Value); TestRoundTripMember(_testNow); } [Fact] public void TestPrimitiveAPIs() { TestRoundTrip(w => TestWritingPrimitiveAPIs(w), r => TestReadingPrimitiveAPIs(r)); } [Fact] public void TestPrimitiveMemberAPIs() { TestRoundTrip(w => w.WriteValue(new PrimitiveMemberTest()), r => r.ReadValue()); } public class PrimitiveMemberTest : IObjectWritable { public PrimitiveMemberTest() { } private PrimitiveMemberTest(ObjectReader reader) { TestReadingPrimitiveAPIs(reader); } bool IObjectWritable.ShouldReuseInSerialization => true; void IObjectWritable.WriteTo(ObjectWriter writer) { TestWritingPrimitiveAPIs(writer); } static PrimitiveMemberTest() { ObjectBinder.RegisterTypeReader(typeof(PrimitiveMemberTest), r => new PrimitiveMemberTest(r)); } } private static void TestWritingPrimitiveAPIs(ObjectWriter writer) { writer.WriteBoolean(true); writer.WriteBoolean(false); writer.WriteByte(Byte.MaxValue); writer.WriteSByte(SByte.MaxValue); writer.WriteInt16(Int16.MaxValue); writer.WriteInt32(Int32.MaxValue); writer.WriteInt32(Byte.MaxValue); writer.WriteInt32(Int16.MaxValue); writer.WriteInt64(Int64.MaxValue); writer.WriteUInt16(UInt16.MaxValue); writer.WriteUInt32(UInt32.MaxValue); writer.WriteUInt64(UInt64.MaxValue); writer.WriteDecimal(Decimal.MaxValue); writer.WriteDouble(Double.MaxValue); writer.WriteSingle(Single.MaxValue); writer.WriteChar('X'); writer.WriteString("YYY"); writer.WriteString("\uD800\uDC00"); // valid surrogate pair writer.WriteString("\uDC00\uD800"); // invalid surrogate pair writer.WriteString("\uD800"); // incomplete surrogate pair } private static void TestReadingPrimitiveAPIs(ObjectReader reader) { Assert.True(reader.ReadBoolean()); Assert.False(reader.ReadBoolean()); Assert.Equal(Byte.MaxValue, reader.ReadByte()); Assert.Equal(SByte.MaxValue, reader.ReadSByte()); Assert.Equal(Int16.MaxValue, reader.ReadInt16()); Assert.Equal(Int32.MaxValue, reader.ReadInt32()); Assert.Equal(Byte.MaxValue, reader.ReadInt32()); Assert.Equal(Int16.MaxValue, reader.ReadInt32()); Assert.Equal(Int64.MaxValue, reader.ReadInt64()); Assert.Equal(UInt16.MaxValue, reader.ReadUInt16()); Assert.Equal(UInt32.MaxValue, reader.ReadUInt32()); Assert.Equal(UInt64.MaxValue, reader.ReadUInt64()); Assert.Equal(Decimal.MaxValue, reader.ReadDecimal()); Assert.Equal(Double.MaxValue, reader.ReadDouble()); Assert.Equal(Single.MaxValue, reader.ReadSingle()); Assert.Equal('X', reader.ReadChar()); Assert.Equal("YYY", reader.ReadString()); Assert.Equal("\uD800\uDC00", reader.ReadString()); // valid surrogate pair Assert.Equal("\uDC00\uD800", reader.ReadString()); // invalid surrogate pair Assert.Equal("\uD800", reader.ReadString()); // incomplete surrogate pair } [Fact] public void TestPrimitivesValue() { TestRoundTrip(w => TestWritingPrimitiveValues(w), r => TestReadingPrimitiveValues(r)); } [Fact] public void TestPrimitiveValueAPIs() { TestRoundTrip(w => w.WriteValue(new PrimitiveValueTest()), r => r.ReadValue()); } public class PrimitiveValueTest : IObjectWritable { public PrimitiveValueTest() { } private PrimitiveValueTest(ObjectReader reader) { TestReadingPrimitiveValues(reader); } bool IObjectWritable.ShouldReuseInSerialization => true; void IObjectWritable.WriteTo(ObjectWriter writer) { TestWritingPrimitiveValues(writer); } static PrimitiveValueTest() { ObjectBinder.RegisterTypeReader(typeof(PrimitiveValueTest), r => new PrimitiveValueTest(r)); } } private static void TestWritingPrimitiveValues(ObjectWriter writer) { writer.WriteValue(true); writer.WriteValue(false); writer.WriteValue(Byte.MaxValue); writer.WriteValue(SByte.MaxValue); writer.WriteValue(Int16.MaxValue); writer.WriteValue(Int32.MaxValue); writer.WriteValue((Int32)Byte.MaxValue); writer.WriteValue((Int32)Int16.MaxValue); writer.WriteValue(Int64.MaxValue); writer.WriteValue(UInt16.MaxValue); writer.WriteValue(UInt32.MaxValue); writer.WriteValue(UInt64.MaxValue); writer.WriteValue(Decimal.MaxValue); writer.WriteValue(Double.MaxValue); writer.WriteValue(Single.MaxValue); writer.WriteValue('X'); writer.WriteValue("YYY"); writer.WriteValue("\uD800\uDC00"); // valid surrogate pair writer.WriteValue("\uDC00\uD800"); // invalid surrogate pair writer.WriteValue("\uD800"); // incomplete surrogate pair writer.WriteValue((object)null); writer.WriteValue((IObjectWritable)null); unchecked { writer.WriteInt64((long)ConsoleColor.Cyan); writer.WriteInt64((long)EByte.Value); writer.WriteInt64((long)ESByte.Value); writer.WriteInt64((long)EShort.Value); writer.WriteInt64((long)EUShort.Value); writer.WriteInt64((long)EInt.Value); writer.WriteInt64((long)EUInt.Value); writer.WriteInt64((long)ELong.Value); writer.WriteInt64((long)EULong.Value); } writer.WriteValue(_testNow); } private static void TestReadingPrimitiveValues(ObjectReader reader) { Assert.True((bool)reader.ReadValue()); Assert.False((bool)reader.ReadValue()); Assert.Equal(Byte.MaxValue, (Byte)reader.ReadValue()); Assert.Equal(SByte.MaxValue, (SByte)reader.ReadValue()); Assert.Equal(Int16.MaxValue, (Int16)reader.ReadValue()); Assert.Equal(Int32.MaxValue, (Int32)reader.ReadValue()); Assert.Equal(Byte.MaxValue, (Int32)reader.ReadValue()); Assert.Equal(Int16.MaxValue, (Int32)reader.ReadValue()); Assert.Equal(Int64.MaxValue, (Int64)reader.ReadValue()); Assert.Equal(UInt16.MaxValue, (UInt16)reader.ReadValue()); Assert.Equal(UInt32.MaxValue, (UInt32)reader.ReadValue()); Assert.Equal(UInt64.MaxValue, (UInt64)reader.ReadValue()); Assert.Equal(Decimal.MaxValue, (Decimal)reader.ReadValue()); Assert.Equal(Double.MaxValue, (Double)reader.ReadValue()); Assert.Equal(Single.MaxValue, (Single)reader.ReadValue()); Assert.Equal('X', (Char)reader.ReadValue()); Assert.Equal("YYY", (String)reader.ReadValue()); Assert.Equal("\uD800\uDC00", (String)reader.ReadValue()); // valid surrogate pair Assert.Equal("\uDC00\uD800", (String)reader.ReadValue()); // invalid surrogate pair Assert.Equal("\uD800", (String)reader.ReadValue()); // incomplete surrogate pair Assert.Null(reader.ReadValue()); Assert.Null(reader.ReadValue()); unchecked { Assert.Equal((long)ConsoleColor.Cyan, reader.ReadInt64()); Assert.Equal((long)EByte.Value, reader.ReadInt64()); Assert.Equal((long)ESByte.Value, reader.ReadInt64()); Assert.Equal((long)EShort.Value, reader.ReadInt64()); Assert.Equal((long)EUShort.Value, reader.ReadInt64()); Assert.Equal((long)EInt.Value, reader.ReadInt64()); Assert.Equal((long)EUInt.Value, reader.ReadInt64()); Assert.Equal((long)ELong.Value, reader.ReadInt64()); Assert.Equal((long)EULong.Value, reader.ReadInt64()); } Assert.Equal(_testNow, (DateTime)reader.ReadValue()); } public enum EByte : byte { Value = 1 } public enum ESByte : sbyte { Value = 2 } public enum EShort : short { Value = 3 } public enum EUShort : ushort { Value = 4 } public enum EInt : int { Value = 5 } public enum EUInt : uint { Value = 6 } public enum ELong : long { Value = 7 } public enum EULong : ulong { Value = 8 } [Fact] public void TestRoundTripCharacters() { // round trip all possible characters as a string for (int i = ushort.MinValue; i <= ushort.MaxValue; i++) { TestRoundTripChar((char)i); } } private void TestRoundTripChar(Char ch) { TestRoundTrip(ch, (w, v) => w.WriteChar(v), r => r.ReadChar()); } [Fact] public void TestRoundTripGuid() { void test(Guid guid) { TestRoundTrip(guid, (w, v) => w.WriteGuid(v), r => r.ReadGuid()); } test(Guid.Empty); test(new Guid(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)); test(new Guid(0b10000000000000000000000000000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)); test(new Guid(0b10000000000000000000000000000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)); for (int i = 0; i < 10; i++) { test(Guid.NewGuid()); } } [Fact] public void TestRoundTripStringCharacters() { // round trip all possible characters as a string for (int i = ushort.MinValue; i <= ushort.MaxValue; i++) { TestRoundTripStringCharacter((ushort)i); } // round trip single string with all possible characters var sb = new StringBuilder(); for (int i = ushort.MinValue; i <= ushort.MaxValue; i++) { sb.Append((char)i); } TestRoundTripString(sb.ToString()); } private void TestRoundTripString(string text) { TestRoundTrip(text, (w, v) => w.WriteString(v), r => r.ReadString()); } private void TestRoundTripStringCharacter(ushort code) { TestRoundTripString(new String((char)code, 1)); } [Fact] public void TestRoundTripArrays() { //TestRoundTripArray(new object[] { }); //TestRoundTripArray(new object[] { "hello" }); //TestRoundTripArray(new object[] { "hello", "world" }); //TestRoundTripArray(new object[] { "hello", "world", "good" }); //TestRoundTripArray(new object[] { "hello", "world", "good", "bye" }); //TestRoundTripArray(new object[] { "hello", 123, 45m, 99.9, 'c' }); TestRoundTripArray(new string[] { "hello", null, "world" }); } private void TestRoundTripArray<T>(T[] values) { TestRoundTripValue(values); } [Theory] [CombinatorialData] public void Encoding_UTF8(bool byteOrderMark) { TestRoundtripEncoding(new UTF8Encoding(byteOrderMark)); } [Theory] [CombinatorialData] public void Encoding_UTF32(bool bigEndian, bool byteOrderMark) { TestRoundtripEncoding(new UTF32Encoding(bigEndian, byteOrderMark)); } [Theory] [CombinatorialData] public void Encoding_Unicode(bool bigEndian, bool byteOrderMark) { TestRoundtripEncoding(new UnicodeEncoding(bigEndian, byteOrderMark)); } [Fact] public void Encoding_AllAvailable() { foreach (var info in Encoding.GetEncodings()) { TestRoundtripEncoding(Encoding.GetEncoding(info.Name)); } } private static void TestRoundtripEncoding(Encoding encoding) { using var stream = new MemoryStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true)) { writer.WriteEncoding(encoding); } stream.Position = 0; using var reader = ObjectReader.TryGetReader(stream); Assert.NotNull(reader); var actualEncoding = (Encoding)((Encoding)reader.ReadValue()).Clone(); var expectedEncoding = (Encoding)encoding.Clone(); // set the fallbacks to the same instance so that equality comparison does not take them into account: actualEncoding.EncoderFallback = EncoderFallback.ExceptionFallback; actualEncoding.DecoderFallback = DecoderFallback.ExceptionFallback; expectedEncoding.EncoderFallback = EncoderFallback.ExceptionFallback; expectedEncoding.DecoderFallback = DecoderFallback.ExceptionFallback; Assert.Equal(expectedEncoding.GetPreamble(), actualEncoding.GetPreamble()); Assert.Equal(expectedEncoding.CodePage, actualEncoding.CodePage); Assert.Equal(expectedEncoding.WebName, actualEncoding.WebName); Assert.Equal(expectedEncoding, actualEncoding); } [Fact] public void TestObjectMapLimits() { using var stream = new MemoryStream(); var instances = new List<TypeWithTwoMembers<int, string>>(); // We need enough items to exercise all sizes of ObjectRef for (int i = 0; i < ushort.MaxValue + 1; i++) { instances.Add(new TypeWithTwoMembers<int, string>(i, i.ToString())); } using (var writer = new ObjectWriter(stream, leaveOpen: true)) { // Write each instance twice. The second time around, they'll become ObjectRefs for (int pass = 0; pass < 2; pass++) { foreach (var instance in instances) { writer.WriteValue(instance); } } } stream.Position = 0; using (var reader = ObjectReader.TryGetReader(stream, leaveOpen: true)) { for (int pass = 0; pass < 2; pass++) { foreach (var instance in instances) { var obj = reader.ReadValue(); Assert.NotNull(obj); Assert.True(Equalish(obj, instance)); } } } } [Fact] public void TestObjectGraph() { var oneNode = new Node("one"); TestRoundTripValue(oneNode); TestRoundTripValue(new Node("a", new Node("b"), new Node("c"))); TestRoundTripValue(new Node("x", oneNode, oneNode, oneNode, oneNode)); } [Fact] public void TestReuse() { var oneNode = new Node("one"); var n1 = new Node("x", oneNode, oneNode, oneNode, oneNode); var n2 = RoundTripValue(n1, recursive: true); Assert.Same(n2.Children[0], n2.Children[1]); Assert.Same(n2.Children[1], n2.Children[2]); Assert.Same(n2.Children[2], n2.Children[3]); } [Fact] public void TestReuseNegative() { var oneNode = new Node("one", isReusable: false); var n1 = new Node("x", oneNode, oneNode, oneNode, oneNode); var n2 = RoundTripValue(n1, recursive: true); Assert.NotSame(n2.Children[0], n2.Children[1]); Assert.NotSame(n2.Children[1], n2.Children[2]); Assert.NotSame(n2.Children[2], n2.Children[3]); } [Fact] public void TestWideObjectGraph() { int id = 0; var graph = ConstructGraph(ref id, 5, 3); TestRoundTripValue(graph); } [Fact] public void TestDeepObjectGraph_RecursiveSucceeds() { int id = 0; var graph = ConstructGraph(ref id, 1, 1000); TestRoundTripValue(graph); } [Fact] public void TestDeepObjectGraph_NonRecursiveSucceeds() { int id = 0; var graph = ConstructGraph(ref id, 1, 1000); TestRoundTripValue(graph, recursive: false); } private Node ConstructGraph(ref int id, int width, int depth) { var name = "node" + (id++); Node[] children; if (depth > 0) { children = new Node[width]; for (int i = 0; i < width; i++) { children[i] = ConstructGraph(ref id, width, depth - 1); } } else { children = Array.Empty<Node>(); } return new Node(name, children); } private class Node : IObjectWritable, IEquatable<Node> { internal readonly string Name; internal readonly Node[] Children; private readonly bool _isReusable = true; public Node(string name, params Node[] children) { this.Name = name; this.Children = children; } public Node(string name, bool isReusable) : this(name) { this._isReusable = isReusable; } private Node(ObjectReader reader) { this.Name = reader.ReadString(); this.Children = (Node[])reader.ReadValue(); } private static readonly Func<ObjectReader, object> s_createInstance = r => new Node(r); bool IObjectWritable.ShouldReuseInSerialization => _isReusable; public void WriteTo(ObjectWriter writer) { writer.WriteString(this.Name); writer.WriteValue(this.Children); } static Node() { ObjectBinder.RegisterTypeReader(typeof(Node), r => new Node(r)); } public override Int32 GetHashCode() { return this.Name != null ? this.Name.GetHashCode() : 0; } public override Boolean Equals(Object obj) { return Equals(obj as Node); } public bool Equals(Node node) { if (node == null || this.Name != node.Name) { return false; } if (this.Children.Length != node.Children.Length) { return false; } for (int i = 0; i < this.Children.Length; i++) { if (!this.Children[i].Equals(node.Children[i])) { return false; } } return true; } } // keep these around for analyzing perf issues #if false [Fact] public void TestReaderPerf() { var iterations = 10000; var recTime = TestReaderPerf(iterations, recursive: true); var nonTime = TestReaderPerf(iterations, recursive: false); Console.WriteLine($"Recursive Time : {recTime.TotalMilliseconds}"); Console.WriteLine($"Non Recursive Time: {nonTime.TotalMilliseconds}"); } [Fact] public void TestNonRecursiveReaderPerf() { var iterations = 10000; var nonTime = TestReaderPerf(iterations, recursive: false); } private TimeSpan TestReaderPerf(int iterations, bool recursive) { int id = 0; var graph = ConstructGraph(ref id, 5, 3); var stream = new MemoryStream(); var binder = new RecordingObjectBinder(); var writer = new StreamObjectWriter(stream, binder: binder, recursive: recursive); writer.WriteValue(graph); writer.Dispose(); var start = DateTime.Now; for (int i = 0; i < iterations; i++) { stream.Position = 0; var reader = new StreamObjectReader(stream, binder: binder); var item = reader.ReadValue(); } return DateTime.Now - start; } #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 using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { public sealed class ObjectSerializationTests { static ObjectSerializationTests() { // Register appropriate deserialization methods. new PrimitiveArrayMemberTest(); new PrimitiveMemberTest(); new PrimitiveValueTest(); } [Fact] public void TestInvalidStreamVersion() { var stream = new MemoryStream(); stream.WriteByte(0); stream.WriteByte(0); stream.Position = 0; var reader = ObjectReader.TryGetReader(stream); Assert.Null(reader); } private void RoundTrip(Action<ObjectWriter> writeAction, Action<ObjectReader> readAction, bool recursive) { using var stream = new MemoryStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true)) { writeAction(writer); } stream.Position = 0; using var reader = ObjectReader.TryGetReader(stream); readAction(reader); } private void TestRoundTrip(Action<ObjectWriter> writeAction, Action<ObjectReader> readAction) { RoundTrip(writeAction, readAction, recursive: true); RoundTrip(writeAction, readAction, recursive: false); } private T RoundTrip<T>(T value, Action<ObjectWriter, T> writeAction, Func<ObjectReader, T> readAction, bool recursive) { using var stream = new MemoryStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true)) { writeAction(writer, value); } stream.Position = 0; using var reader = ObjectReader.TryGetReader(stream); return readAction(reader); } private void TestRoundTrip<T>(T value, Action<ObjectWriter, T> writeAction, Func<ObjectReader, T> readAction, bool recursive) { var newValue = RoundTrip(value, writeAction, readAction, recursive); Assert.True(Equalish(value, newValue)); } private void TestRoundTrip<T>(T value, Action<ObjectWriter, T> writeAction, Func<ObjectReader, T> readAction) { TestRoundTrip(value, writeAction, readAction, recursive: true); TestRoundTrip(value, writeAction, readAction, recursive: false); } private T RoundTripValue<T>(T value, bool recursive) { return RoundTrip(value, (w, v) => { if (v != null && v.GetType().IsEnum) { w.WriteInt64(Convert.ToInt64((object)v)); } else { w.WriteValue(v); } }, r => value != null && value.GetType().IsEnum ? (T)Enum.ToObject(typeof(T), r.ReadInt64()) : (T)r.ReadValue(), recursive); } private void TestRoundTripValue<T>(T value, bool recursive) { var newValue = RoundTripValue(value, recursive); Assert.True(Equalish(value, newValue)); } private void TestRoundTripValue<T>(T value) { TestRoundTripValue(value, recursive: true); TestRoundTripValue(value, recursive: false); } private static bool Equalish<T>(T value1, T value2) { return object.Equals(value1, value2) || (value1 is Array && value2 is Array && ArrayEquals((Array)(object)value1, (Array)(object)value2)); } private static bool ArrayEquals(Array seq1, Array seq2) { if (seq1 == null && seq2 == null) { return true; } else if (seq1 == null || seq2 == null) { return false; } if (seq1.Length != seq2.Length) { return false; } for (int i = 0; i < seq1.Length; i++) { if (!Equalish(seq1.GetValue(i), seq2.GetValue(i))) { return false; } } return true; } private class TypeWithOneMember<T> : IObjectWritable, IEquatable<TypeWithOneMember<T>> { private readonly T _member; public TypeWithOneMember(T value) { _member = value; } private TypeWithOneMember(ObjectReader reader) { _member = typeof(T).IsEnum ? (T)Enum.ToObject(typeof(T), reader.ReadInt64()) : (T)reader.ReadValue(); } bool IObjectWritable.ShouldReuseInSerialization => true; void IObjectWritable.WriteTo(ObjectWriter writer) { if (typeof(T).IsEnum) { writer.WriteInt64(Convert.ToInt64(_member)); } else { writer.WriteValue(_member); } } static TypeWithOneMember() { ObjectBinder.RegisterTypeReader(typeof(TypeWithOneMember<T>), r => new TypeWithOneMember<T>(r)); } public override Int32 GetHashCode() { if (_member == null) { return 0; } else { return _member.GetHashCode(); } } public override Boolean Equals(Object obj) { return Equals(obj as TypeWithOneMember<T>); } public bool Equals(TypeWithOneMember<T> other) { return other != null && Equalish(_member, other._member); } } private class TypeWithTwoMembers<T, S> : IObjectWritable, IEquatable<TypeWithTwoMembers<T, S>> { private readonly T _member1; private readonly S _member2; public TypeWithTwoMembers(T value1, S value2) { _member1 = value1; _member2 = value2; } private TypeWithTwoMembers(ObjectReader reader) { _member1 = (T)reader.ReadValue(); _member2 = (S)reader.ReadValue(); } bool IObjectWritable.ShouldReuseInSerialization => true; void IObjectWritable.WriteTo(ObjectWriter writer) { writer.WriteValue(_member1); writer.WriteValue(_member2); } static TypeWithTwoMembers() { ObjectBinder.RegisterTypeReader(typeof(TypeWithTwoMembers<T, S>), r => new TypeWithTwoMembers<T, S>(r)); } public override int GetHashCode() { if (_member1 == null) { return 0; } else { return _member1.GetHashCode(); } } public override Boolean Equals(Object obj) { return Equals(obj as TypeWithTwoMembers<T, S>); } public bool Equals(TypeWithTwoMembers<T, S> other) { return other != null && Equalish(_member1, other._member1) && Equalish(_member2, other._member2); } } // this type simulates a class with many members.. // it serializes each member individually, not as an array. private class TypeWithManyMembers<T> : IObjectWritable, IEquatable<TypeWithManyMembers<T>> { private readonly T[] _members; public TypeWithManyMembers(T[] values) { _members = values; } private TypeWithManyMembers(ObjectReader reader) { var count = reader.ReadInt32(); _members = new T[count]; for (int i = 0; i < count; i++) { _members[i] = (T)reader.ReadValue(); } } bool IObjectWritable.ShouldReuseInSerialization => true; void IObjectWritable.WriteTo(ObjectWriter writer) { writer.WriteInt32(_members.Length); for (int i = 0; i < _members.Length; i++) { writer.WriteValue(_members[i]); } } static TypeWithManyMembers() { ObjectBinder.RegisterTypeReader(typeof(TypeWithManyMembers<T>), r => new TypeWithManyMembers<T>(r)); } public override int GetHashCode() { return _members.Length; } public override Boolean Equals(Object obj) { return Equals(obj as TypeWithManyMembers<T>); } public bool Equals(TypeWithManyMembers<T> other) { if (other == null) { return false; } if (_members.Length != other._members.Length) { return false; } return Equalish(_members, other._members); } } private void TestRoundTripMember<T>(T value) { TestRoundTripValue(new TypeWithOneMember<T>(value)); } private void TestRoundTripMembers<T, S>(T value1, S value2) { TestRoundTripValue(new TypeWithTwoMembers<T, S>(value1, value2)); } private void TestRoundTripMembers<T>(params T[] values) { TestRoundTripValue(new TypeWithManyMembers<T>(values)); } [Fact] public void TestValueInt32() { TestRoundTripValue(123); } [Fact] public void TestMemberInt32() { TestRoundTripMember(123); } [Fact] public void TestMemberIntString() { TestRoundTripMembers(123, "Hello"); } [Fact] public void TestManyMembersInt32() { TestRoundTripMembers(Enumerable.Range(0, 1000).ToArray()); } [Fact] public void TestSmallArrayMember() { TestRoundTripMember(Enumerable.Range(0, 3).ToArray()); } [Fact] public void TestEmptyArrayMember() { TestRoundTripMember(new int[] { }); } [Fact] public void TestNullArrayMember() { TestRoundTripMember<int[]>(null); } [Fact] public void TestLargeArrayMember() { TestRoundTripMember(Enumerable.Range(0, 1000).ToArray()); } [Fact] public void TestEnumMember() { TestRoundTripMember(EByte.Value); } [Fact] public void TestInt32EncodingKinds() { Assert.Equal(ObjectWriter.EncodingKind.Int32_1, ObjectWriter.EncodingKind.Int32_0 + 1); Assert.Equal(ObjectWriter.EncodingKind.Int32_2, ObjectWriter.EncodingKind.Int32_0 + 2); Assert.Equal(ObjectWriter.EncodingKind.Int32_3, ObjectWriter.EncodingKind.Int32_0 + 3); Assert.Equal(ObjectWriter.EncodingKind.Int32_4, ObjectWriter.EncodingKind.Int32_0 + 4); Assert.Equal(ObjectWriter.EncodingKind.Int32_5, ObjectWriter.EncodingKind.Int32_0 + 5); Assert.Equal(ObjectWriter.EncodingKind.Int32_6, ObjectWriter.EncodingKind.Int32_0 + 6); Assert.Equal(ObjectWriter.EncodingKind.Int32_7, ObjectWriter.EncodingKind.Int32_0 + 7); Assert.Equal(ObjectWriter.EncodingKind.Int32_8, ObjectWriter.EncodingKind.Int32_0 + 8); Assert.Equal(ObjectWriter.EncodingKind.Int32_9, ObjectWriter.EncodingKind.Int32_0 + 9); Assert.Equal(ObjectWriter.EncodingKind.Int32_10, ObjectWriter.EncodingKind.Int32_0 + 10); } [Fact] public void TestUInt32EncodingKinds() { Assert.Equal(ObjectWriter.EncodingKind.UInt32_1, ObjectWriter.EncodingKind.UInt32_0 + 1); Assert.Equal(ObjectWriter.EncodingKind.UInt32_2, ObjectWriter.EncodingKind.UInt32_0 + 2); Assert.Equal(ObjectWriter.EncodingKind.UInt32_3, ObjectWriter.EncodingKind.UInt32_0 + 3); Assert.Equal(ObjectWriter.EncodingKind.UInt32_4, ObjectWriter.EncodingKind.UInt32_0 + 4); Assert.Equal(ObjectWriter.EncodingKind.UInt32_5, ObjectWriter.EncodingKind.UInt32_0 + 5); Assert.Equal(ObjectWriter.EncodingKind.UInt32_6, ObjectWriter.EncodingKind.UInt32_0 + 6); Assert.Equal(ObjectWriter.EncodingKind.UInt32_7, ObjectWriter.EncodingKind.UInt32_0 + 7); Assert.Equal(ObjectWriter.EncodingKind.UInt32_8, ObjectWriter.EncodingKind.UInt32_0 + 8); Assert.Equal(ObjectWriter.EncodingKind.UInt32_9, ObjectWriter.EncodingKind.UInt32_0 + 9); Assert.Equal(ObjectWriter.EncodingKind.UInt32_10, ObjectWriter.EncodingKind.UInt32_0 + 10); } private void TestRoundTripType(Type type) { TestRoundTrip(type, (w, v) => w.WriteType(v), r => r.ReadType()); } [Fact] public void TestTypes() { TestRoundTripType(typeof(int)); TestRoundTripType(typeof(string)); TestRoundTripType(typeof(ObjectSerializationTests)); } private void TestRoundTripCompressedUint(uint value) { TestRoundTrip(value, (w, v) => ((ObjectWriter)w).WriteCompressedUInt(v), r => ((ObjectReader)r).ReadCompressedUInt()); } [Fact] public void TestCompressedUInt() { TestRoundTripCompressedUint(0); TestRoundTripCompressedUint(0x01u); TestRoundTripCompressedUint(0x0123u); // unique bytes tests order TestRoundTripCompressedUint(0x012345u); // unique bytes tests order TestRoundTripCompressedUint(0x01234567u); // unique bytes tests order TestRoundTripCompressedUint(0x3Fu); // largest value packed in one byte TestRoundTripCompressedUint(0x3FFFu); // largest value packed into two bytes TestRoundTripCompressedUint(0x3FFFFFu); // no three byte option yet, but test anyway TestRoundTripCompressedUint(0x3FFFFFFFu); // largest unit allowed in four bytes Assert.Throws<ArgumentException>(() => TestRoundTripCompressedUint(uint.MaxValue)); // max uint not allowed Assert.Throws<ArgumentException>(() => TestRoundTripCompressedUint(0x80000000u)); // highest bit set not allowed Assert.Throws<ArgumentException>(() => TestRoundTripCompressedUint(0x40000000u)); // second highest bit set not allowed Assert.Throws<ArgumentException>(() => TestRoundTripCompressedUint(0xC0000000u)); // both high bits set not allowed } [Fact] public void TestArraySizes() { TestArrayValues<byte>(1, 2, 3, 4, 5); TestArrayValues<sbyte>(1, 2, 3, 4, 5); TestArrayValues<short>(1, 2, 3, 4, 5); TestArrayValues<ushort>(1, 2, 3, 4, 5); TestArrayValues<int>(1, 2, 3, 4, 5); TestArrayValues<uint>(1, 2, 3, 4, 5); TestArrayValues<long>(1, 2, 3, 4, 5); TestArrayValues<ulong>(1, 2, 3, 4, 5); TestArrayValues<decimal>(1m, 2m, 3m, 4m, 5m); TestArrayValues<float>(1.0f, 2.0f, 3.0f, 4.0f, 5.0f); TestArrayValues<double>(1.0, 2.0, 3.0, 4.0, 5.0); TestArrayValues<char>('1', '2', '3', '4', '5'); TestArrayValues<string>("1", "2", "3", "4", "5"); TestArrayValues( new TypeWithOneMember<int>(1), new TypeWithOneMember<int>(2), new TypeWithOneMember<int>(3), new TypeWithOneMember<int>(4), new TypeWithOneMember<int>(5)); } private void TestArrayValues<T>(T v1, T v2, T v3, T v4, T v5) { TestRoundTripValue((T[])null); TestRoundTripValue(new T[] { }); TestRoundTripValue(new T[] { v1 }); TestRoundTripValue(new T[] { v1, v2 }); TestRoundTripValue(new T[] { v1, v2, v3 }); TestRoundTripValue(new T[] { v1, v2, v3, v4 }); TestRoundTripValue(new T[] { v1, v2, v3, v4, v5 }); } [Fact] public void TestPrimitiveArrayValues() { TestRoundTrip(w => TestWritingPrimitiveArrays(w), r => TestReadingPrimitiveArrays(r)); } [Theory] [CombinatorialData] public void TestByteSpan([CombinatorialValues(0, 1, 2, 3, 1000, 1000000)] int size) { var data = new byte[size]; for (int i = 0; i < data.Length; i++) { data[i] = (byte)i; } TestRoundTrip(w => TestWritingByteSpan(data, w), r => TestReadingByteSpan(data, r)); } [Fact] public void TestPrimitiveArrayMembers() { TestRoundTrip(w => w.WriteValue(new PrimitiveArrayMemberTest()), r => r.ReadValue()); } public class PrimitiveArrayMemberTest : IObjectWritable { public PrimitiveArrayMemberTest() { } private PrimitiveArrayMemberTest(ObjectReader reader) { TestReadingPrimitiveArrays(reader); } bool IObjectWritable.ShouldReuseInSerialization => true; void IObjectWritable.WriteTo(ObjectWriter writer) { TestWritingPrimitiveArrays(writer); } static PrimitiveArrayMemberTest() { ObjectBinder.RegisterTypeReader(typeof(PrimitiveArrayMemberTest), r => new PrimitiveArrayMemberTest(r)); } } private static void TestWritingPrimitiveArrays(ObjectWriter writer) { var inputBool = new bool[] { true, false }; var inputByte = new byte[] { 1, 2, 3, 4, 5 }; var inputChar = new char[] { 'h', 'e', 'l', 'l', 'o' }; var inputDecimal = new decimal[] { 1.0M, 2.0M, 3.0M, 4.0M, 5.0M }; var inputDouble = new double[] { 1.0, 2.0, 3.0, 4.0, 5.0 }; var inputFloat = new float[] { 1.0F, 2.0F, 3.0F, 4.0F, 5.0F }; var inputInt = new int[] { -1, -2, -3, -4, -5 }; var inputLong = new long[] { 1, 2, 3, 4, 5 }; var inputSByte = new sbyte[] { -1, -2, -3, -4, -5 }; var inputShort = new short[] { -1, -2, -3, -4, -5 }; var inputUInt = new uint[] { 1, 2, 3, 4, 5 }; var inputULong = new ulong[] { 1, 2, 3, 4, 5 }; var inputUShort = new ushort[] { 1, 2, 3, 4, 5 }; var inputString = new string[] { "h", "e", "l", "l", "o" }; writer.WriteValue(inputBool); writer.WriteValue((object)inputByte); writer.WriteValue(inputChar); writer.WriteValue(inputDecimal); writer.WriteValue(inputDouble); writer.WriteValue(inputFloat); writer.WriteValue(inputInt); writer.WriteValue(inputLong); writer.WriteValue(inputSByte); writer.WriteValue(inputShort); writer.WriteValue(inputUInt); writer.WriteValue(inputULong); writer.WriteValue(inputUShort); writer.WriteValue(inputString); } private static void TestReadingPrimitiveArrays(ObjectReader reader) { var inputBool = new bool[] { true, false }; var inputByte = new byte[] { 1, 2, 3, 4, 5 }; var inputChar = new char[] { 'h', 'e', 'l', 'l', 'o' }; var inputDecimal = new decimal[] { 1.0M, 2.0M, 3.0M, 4.0M, 5.0M }; var inputDouble = new double[] { 1.0, 2.0, 3.0, 4.0, 5.0 }; var inputFloat = new float[] { 1.0F, 2.0F, 3.0F, 4.0F, 5.0F }; var inputInt = new int[] { -1, -2, -3, -4, -5 }; var inputLong = new long[] { 1, 2, 3, 4, 5 }; var inputSByte = new sbyte[] { -1, -2, -3, -4, -5 }; var inputShort = new short[] { -1, -2, -3, -4, -5 }; var inputUInt = new uint[] { 1, 2, 3, 4, 5 }; var inputULong = new ulong[] { 1, 2, 3, 4, 5 }; var inputUShort = new ushort[] { 1, 2, 3, 4, 5 }; var inputString = new string[] { "h", "e", "l", "l", "o" }; Assert.True(Enumerable.SequenceEqual(inputBool, (bool[])reader.ReadValue())); Assert.True(Enumerable.SequenceEqual(inputByte, (byte[])reader.ReadValue())); Assert.True(Enumerable.SequenceEqual(inputChar, (char[])reader.ReadValue())); Assert.True(Enumerable.SequenceEqual(inputDecimal, (decimal[])reader.ReadValue())); Assert.True(Enumerable.SequenceEqual(inputDouble, (double[])reader.ReadValue())); Assert.True(Enumerable.SequenceEqual(inputFloat, (float[])reader.ReadValue())); Assert.True(Enumerable.SequenceEqual(inputInt, (int[])reader.ReadValue())); Assert.True(Enumerable.SequenceEqual(inputLong, (long[])reader.ReadValue())); Assert.True(Enumerable.SequenceEqual(inputSByte, (sbyte[])reader.ReadValue())); Assert.True(Enumerable.SequenceEqual(inputShort, (short[])reader.ReadValue())); Assert.True(Enumerable.SequenceEqual(inputUInt, (uint[])reader.ReadValue())); Assert.True(Enumerable.SequenceEqual(inputULong, (ulong[])reader.ReadValue())); Assert.True(Enumerable.SequenceEqual(inputUShort, (ushort[])reader.ReadValue())); Assert.True(Enumerable.SequenceEqual(inputString, (string[])reader.ReadValue())); } private static void TestWritingByteSpan(byte[] data, ObjectWriter writer) { writer.WriteValue(data.AsSpan()); } private static void TestReadingByteSpan(byte[] expected, ObjectReader reader) { Assert.True(Enumerable.SequenceEqual(expected, (byte[])reader.ReadValue())); } [Fact] public void TestBooleanArrays() { for (var i = 0; i < 1000; i++) { var inputBool = new bool[i]; for (var j = 0; j < i; j++) { inputBool[j] = j % 2 == 0; } TestRoundTripValue(inputBool); TestRoundTripMember(inputBool); } } [Fact] public void TestFalseBooleanArray() { var inputBool = Enumerable.Repeat<bool>(false, 1000).ToArray(); TestRoundTripValue(inputBool); TestRoundTripMember(inputBool); } private static readonly DateTime _testNow = DateTime.Now; [Fact] public void TestPrimitiveValues() { TestRoundTripValue(true); TestRoundTripValue(false); TestRoundTripValue(Byte.MaxValue); TestRoundTripValue(SByte.MaxValue); TestRoundTripValue(Int16.MaxValue); TestRoundTripValue(Int32.MaxValue); TestRoundTripValue(Byte.MaxValue); TestRoundTripValue(Int16.MaxValue); TestRoundTripValue(Int64.MaxValue); TestRoundTripValue(UInt16.MaxValue); TestRoundTripValue(UInt32.MaxValue); TestRoundTripValue(UInt64.MaxValue); TestRoundTripValue(Decimal.MaxValue); TestRoundTripValue(Double.MaxValue); TestRoundTripValue(Single.MaxValue); TestRoundTripValue('X'); TestRoundTripValue("YYY"); TestRoundTripValue("\uD800\uDC00"); // valid surrogate pair TestRoundTripValue("\uDC00\uD800"); // invalid surrogate pair TestRoundTripValue("\uD800"); // incomplete surrogate pair TestRoundTripValue<object>(null); TestRoundTripValue(ConsoleColor.Cyan); TestRoundTripValue(EByte.Value); TestRoundTripValue(ESByte.Value); TestRoundTripValue(EShort.Value); TestRoundTripValue(EUShort.Value); TestRoundTripValue(EInt.Value); TestRoundTripValue(EUInt.Value); TestRoundTripValue(ELong.Value); TestRoundTripValue(EULong.Value); TestRoundTripValue(_testNow); } [Fact] public void TestInt32Values() { TestRoundTripValue<Int32>(0); TestRoundTripValue<Int32>(1); TestRoundTripValue<Int32>(2); TestRoundTripValue<Int32>(3); TestRoundTripValue<Int32>(4); TestRoundTripValue<Int32>(5); TestRoundTripValue<Int32>(6); TestRoundTripValue<Int32>(7); TestRoundTripValue<Int32>(8); TestRoundTripValue<Int32>(9); TestRoundTripValue<Int32>(10); TestRoundTripValue<Int32>(-1); TestRoundTripValue<Int32>(Int32.MinValue); TestRoundTripValue<Int32>(Byte.MaxValue); TestRoundTripValue<Int32>(UInt16.MaxValue); TestRoundTripValue<Int32>(Int32.MaxValue); } [Fact] public void TestUInt32Values() { TestRoundTripValue<UInt32>(0); TestRoundTripValue<UInt32>(1); TestRoundTripValue<UInt32>(2); TestRoundTripValue<UInt32>(3); TestRoundTripValue<UInt32>(4); TestRoundTripValue<UInt32>(5); TestRoundTripValue<UInt32>(6); TestRoundTripValue<UInt32>(7); TestRoundTripValue<UInt32>(8); TestRoundTripValue<UInt32>(9); TestRoundTripValue<UInt32>(10); TestRoundTripValue<Int32>(Byte.MaxValue); TestRoundTripValue<Int32>(UInt16.MaxValue); TestRoundTripValue<Int32>(Int32.MaxValue); } [Fact] public void TestInt64Values() { TestRoundTripValue<Int64>(0); TestRoundTripValue<Int64>(1); TestRoundTripValue<Int64>(2); TestRoundTripValue<Int64>(3); TestRoundTripValue<Int64>(4); TestRoundTripValue<Int64>(5); TestRoundTripValue<Int64>(6); TestRoundTripValue<Int64>(7); TestRoundTripValue<Int64>(8); TestRoundTripValue<Int64>(9); TestRoundTripValue<Int64>(10); TestRoundTripValue<Int64>(-1); TestRoundTripValue<Int64>(Byte.MinValue); TestRoundTripValue<Int64>(Byte.MaxValue); TestRoundTripValue<Int64>(Int16.MinValue); TestRoundTripValue<Int64>(Int16.MaxValue); TestRoundTripValue<Int64>(UInt16.MinValue); TestRoundTripValue<Int64>(UInt16.MaxValue); TestRoundTripValue<Int64>(Int32.MinValue); TestRoundTripValue<Int64>(Int32.MaxValue); TestRoundTripValue<Int64>(UInt32.MinValue); TestRoundTripValue<Int64>(UInt32.MaxValue); TestRoundTripValue<Int64>(Int64.MinValue); TestRoundTripValue<Int64>(Int64.MaxValue); } [Fact] public void TestUInt64Values() { TestRoundTripValue<UInt64>(0); TestRoundTripValue<UInt64>(1); TestRoundTripValue<UInt64>(2); TestRoundTripValue<UInt64>(3); TestRoundTripValue<UInt64>(4); TestRoundTripValue<UInt64>(5); TestRoundTripValue<UInt64>(6); TestRoundTripValue<UInt64>(7); TestRoundTripValue<UInt64>(8); TestRoundTripValue<UInt64>(9); TestRoundTripValue<UInt64>(10); TestRoundTripValue<UInt64>(Byte.MinValue); TestRoundTripValue<UInt64>(Byte.MaxValue); TestRoundTripValue<UInt64>(UInt16.MinValue); TestRoundTripValue<UInt64>(UInt16.MaxValue); TestRoundTripValue<UInt64>(Int32.MaxValue); TestRoundTripValue<UInt64>(UInt32.MinValue); TestRoundTripValue<UInt64>(UInt32.MaxValue); TestRoundTripValue<UInt64>(UInt64.MinValue); TestRoundTripValue<UInt64>(UInt64.MaxValue); } [Fact] public void TestPrimitiveMemberValues() { TestRoundTripMember(true); TestRoundTripMember(false); TestRoundTripMember(Byte.MaxValue); TestRoundTripMember(SByte.MaxValue); TestRoundTripMember(Int16.MaxValue); TestRoundTripMember(Int32.MaxValue); TestRoundTripMember(Byte.MaxValue); TestRoundTripMember(Int16.MaxValue); TestRoundTripMember(Int64.MaxValue); TestRoundTripMember(UInt16.MaxValue); TestRoundTripMember(UInt32.MaxValue); TestRoundTripMember(UInt64.MaxValue); TestRoundTripMember(Decimal.MaxValue); TestRoundTripMember(Double.MaxValue); TestRoundTripMember(Single.MaxValue); TestRoundTripMember('X'); TestRoundTripMember("YYY"); TestRoundTripMember("\uD800\uDC00"); // valid surrogate pair TestRoundTripMember("\uDC00\uD800"); // invalid surrogate pair TestRoundTripMember("\uD800"); // incomplete surrogate pair TestRoundTripMember<object>(null); TestRoundTripMember(ConsoleColor.Cyan); TestRoundTripMember(EByte.Value); TestRoundTripMember(ESByte.Value); TestRoundTripMember(EShort.Value); TestRoundTripMember(EUShort.Value); TestRoundTripMember(EInt.Value); TestRoundTripMember(EUInt.Value); TestRoundTripMember(ELong.Value); TestRoundTripMember(EULong.Value); TestRoundTripMember(_testNow); } [Fact] public void TestPrimitiveAPIs() { TestRoundTrip(w => TestWritingPrimitiveAPIs(w), r => TestReadingPrimitiveAPIs(r)); } [Fact] public void TestPrimitiveMemberAPIs() { TestRoundTrip(w => w.WriteValue(new PrimitiveMemberTest()), r => r.ReadValue()); } public class PrimitiveMemberTest : IObjectWritable { public PrimitiveMemberTest() { } private PrimitiveMemberTest(ObjectReader reader) { TestReadingPrimitiveAPIs(reader); } bool IObjectWritable.ShouldReuseInSerialization => true; void IObjectWritable.WriteTo(ObjectWriter writer) { TestWritingPrimitiveAPIs(writer); } static PrimitiveMemberTest() { ObjectBinder.RegisterTypeReader(typeof(PrimitiveMemberTest), r => new PrimitiveMemberTest(r)); } } private static void TestWritingPrimitiveAPIs(ObjectWriter writer) { writer.WriteBoolean(true); writer.WriteBoolean(false); writer.WriteByte(Byte.MaxValue); writer.WriteSByte(SByte.MaxValue); writer.WriteInt16(Int16.MaxValue); writer.WriteInt32(Int32.MaxValue); writer.WriteInt32(Byte.MaxValue); writer.WriteInt32(Int16.MaxValue); writer.WriteInt64(Int64.MaxValue); writer.WriteUInt16(UInt16.MaxValue); writer.WriteUInt32(UInt32.MaxValue); writer.WriteUInt64(UInt64.MaxValue); writer.WriteDecimal(Decimal.MaxValue); writer.WriteDouble(Double.MaxValue); writer.WriteSingle(Single.MaxValue); writer.WriteChar('X'); writer.WriteString("YYY"); writer.WriteString("\uD800\uDC00"); // valid surrogate pair writer.WriteString("\uDC00\uD800"); // invalid surrogate pair writer.WriteString("\uD800"); // incomplete surrogate pair } private static void TestReadingPrimitiveAPIs(ObjectReader reader) { Assert.True(reader.ReadBoolean()); Assert.False(reader.ReadBoolean()); Assert.Equal(Byte.MaxValue, reader.ReadByte()); Assert.Equal(SByte.MaxValue, reader.ReadSByte()); Assert.Equal(Int16.MaxValue, reader.ReadInt16()); Assert.Equal(Int32.MaxValue, reader.ReadInt32()); Assert.Equal(Byte.MaxValue, reader.ReadInt32()); Assert.Equal(Int16.MaxValue, reader.ReadInt32()); Assert.Equal(Int64.MaxValue, reader.ReadInt64()); Assert.Equal(UInt16.MaxValue, reader.ReadUInt16()); Assert.Equal(UInt32.MaxValue, reader.ReadUInt32()); Assert.Equal(UInt64.MaxValue, reader.ReadUInt64()); Assert.Equal(Decimal.MaxValue, reader.ReadDecimal()); Assert.Equal(Double.MaxValue, reader.ReadDouble()); Assert.Equal(Single.MaxValue, reader.ReadSingle()); Assert.Equal('X', reader.ReadChar()); Assert.Equal("YYY", reader.ReadString()); Assert.Equal("\uD800\uDC00", reader.ReadString()); // valid surrogate pair Assert.Equal("\uDC00\uD800", reader.ReadString()); // invalid surrogate pair Assert.Equal("\uD800", reader.ReadString()); // incomplete surrogate pair } [Fact] public void TestPrimitivesValue() { TestRoundTrip(w => TestWritingPrimitiveValues(w), r => TestReadingPrimitiveValues(r)); } [Fact] public void TestPrimitiveValueAPIs() { TestRoundTrip(w => w.WriteValue(new PrimitiveValueTest()), r => r.ReadValue()); } public class PrimitiveValueTest : IObjectWritable { public PrimitiveValueTest() { } private PrimitiveValueTest(ObjectReader reader) { TestReadingPrimitiveValues(reader); } bool IObjectWritable.ShouldReuseInSerialization => true; void IObjectWritable.WriteTo(ObjectWriter writer) { TestWritingPrimitiveValues(writer); } static PrimitiveValueTest() { ObjectBinder.RegisterTypeReader(typeof(PrimitiveValueTest), r => new PrimitiveValueTest(r)); } } private static void TestWritingPrimitiveValues(ObjectWriter writer) { writer.WriteValue(true); writer.WriteValue(false); writer.WriteValue(Byte.MaxValue); writer.WriteValue(SByte.MaxValue); writer.WriteValue(Int16.MaxValue); writer.WriteValue(Int32.MaxValue); writer.WriteValue((Int32)Byte.MaxValue); writer.WriteValue((Int32)Int16.MaxValue); writer.WriteValue(Int64.MaxValue); writer.WriteValue(UInt16.MaxValue); writer.WriteValue(UInt32.MaxValue); writer.WriteValue(UInt64.MaxValue); writer.WriteValue(Decimal.MaxValue); writer.WriteValue(Double.MaxValue); writer.WriteValue(Single.MaxValue); writer.WriteValue('X'); writer.WriteValue("YYY"); writer.WriteValue("\uD800\uDC00"); // valid surrogate pair writer.WriteValue("\uDC00\uD800"); // invalid surrogate pair writer.WriteValue("\uD800"); // incomplete surrogate pair writer.WriteValue((object)null); writer.WriteValue((IObjectWritable)null); unchecked { writer.WriteInt64((long)ConsoleColor.Cyan); writer.WriteInt64((long)EByte.Value); writer.WriteInt64((long)ESByte.Value); writer.WriteInt64((long)EShort.Value); writer.WriteInt64((long)EUShort.Value); writer.WriteInt64((long)EInt.Value); writer.WriteInt64((long)EUInt.Value); writer.WriteInt64((long)ELong.Value); writer.WriteInt64((long)EULong.Value); } writer.WriteValue(_testNow); } private static void TestReadingPrimitiveValues(ObjectReader reader) { Assert.True((bool)reader.ReadValue()); Assert.False((bool)reader.ReadValue()); Assert.Equal(Byte.MaxValue, (Byte)reader.ReadValue()); Assert.Equal(SByte.MaxValue, (SByte)reader.ReadValue()); Assert.Equal(Int16.MaxValue, (Int16)reader.ReadValue()); Assert.Equal(Int32.MaxValue, (Int32)reader.ReadValue()); Assert.Equal(Byte.MaxValue, (Int32)reader.ReadValue()); Assert.Equal(Int16.MaxValue, (Int32)reader.ReadValue()); Assert.Equal(Int64.MaxValue, (Int64)reader.ReadValue()); Assert.Equal(UInt16.MaxValue, (UInt16)reader.ReadValue()); Assert.Equal(UInt32.MaxValue, (UInt32)reader.ReadValue()); Assert.Equal(UInt64.MaxValue, (UInt64)reader.ReadValue()); Assert.Equal(Decimal.MaxValue, (Decimal)reader.ReadValue()); Assert.Equal(Double.MaxValue, (Double)reader.ReadValue()); Assert.Equal(Single.MaxValue, (Single)reader.ReadValue()); Assert.Equal('X', (Char)reader.ReadValue()); Assert.Equal("YYY", (String)reader.ReadValue()); Assert.Equal("\uD800\uDC00", (String)reader.ReadValue()); // valid surrogate pair Assert.Equal("\uDC00\uD800", (String)reader.ReadValue()); // invalid surrogate pair Assert.Equal("\uD800", (String)reader.ReadValue()); // incomplete surrogate pair Assert.Null(reader.ReadValue()); Assert.Null(reader.ReadValue()); unchecked { Assert.Equal((long)ConsoleColor.Cyan, reader.ReadInt64()); Assert.Equal((long)EByte.Value, reader.ReadInt64()); Assert.Equal((long)ESByte.Value, reader.ReadInt64()); Assert.Equal((long)EShort.Value, reader.ReadInt64()); Assert.Equal((long)EUShort.Value, reader.ReadInt64()); Assert.Equal((long)EInt.Value, reader.ReadInt64()); Assert.Equal((long)EUInt.Value, reader.ReadInt64()); Assert.Equal((long)ELong.Value, reader.ReadInt64()); Assert.Equal((long)EULong.Value, reader.ReadInt64()); } Assert.Equal(_testNow, (DateTime)reader.ReadValue()); } public enum EByte : byte { Value = 1 } public enum ESByte : sbyte { Value = 2 } public enum EShort : short { Value = 3 } public enum EUShort : ushort { Value = 4 } public enum EInt : int { Value = 5 } public enum EUInt : uint { Value = 6 } public enum ELong : long { Value = 7 } public enum EULong : ulong { Value = 8 } [Fact] public void TestRoundTripCharacters() { // round trip all possible characters as a string for (int i = ushort.MinValue; i <= ushort.MaxValue; i++) { TestRoundTripChar((char)i); } } private void TestRoundTripChar(Char ch) { TestRoundTrip(ch, (w, v) => w.WriteChar(v), r => r.ReadChar()); } [Fact] public void TestRoundTripGuid() { void test(Guid guid) { TestRoundTrip(guid, (w, v) => w.WriteGuid(v), r => r.ReadGuid()); } test(Guid.Empty); test(new Guid(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)); test(new Guid(0b10000000000000000000000000000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1)); test(new Guid(0b10000000000000000000000000000000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)); for (int i = 0; i < 10; i++) { test(Guid.NewGuid()); } } [Fact] public void TestRoundTripStringCharacters() { // round trip all possible characters as a string for (int i = ushort.MinValue; i <= ushort.MaxValue; i++) { TestRoundTripStringCharacter((ushort)i); } // round trip single string with all possible characters var sb = new StringBuilder(); for (int i = ushort.MinValue; i <= ushort.MaxValue; i++) { sb.Append((char)i); } TestRoundTripString(sb.ToString()); } private void TestRoundTripString(string text) { TestRoundTrip(text, (w, v) => w.WriteString(v), r => r.ReadString()); } private void TestRoundTripStringCharacter(ushort code) { TestRoundTripString(new String((char)code, 1)); } [Fact] public void TestRoundTripArrays() { //TestRoundTripArray(new object[] { }); //TestRoundTripArray(new object[] { "hello" }); //TestRoundTripArray(new object[] { "hello", "world" }); //TestRoundTripArray(new object[] { "hello", "world", "good" }); //TestRoundTripArray(new object[] { "hello", "world", "good", "bye" }); //TestRoundTripArray(new object[] { "hello", 123, 45m, 99.9, 'c' }); TestRoundTripArray(new string[] { "hello", null, "world" }); } private void TestRoundTripArray<T>(T[] values) { TestRoundTripValue(values); } [Theory] [CombinatorialData] public void Encoding_UTF8(bool byteOrderMark) { TestRoundtripEncoding(new UTF8Encoding(byteOrderMark)); } [Theory] [CombinatorialData] public void Encoding_UTF32(bool bigEndian, bool byteOrderMark) { TestRoundtripEncoding(new UTF32Encoding(bigEndian, byteOrderMark)); } [Theory] [CombinatorialData] public void Encoding_Unicode(bool bigEndian, bool byteOrderMark) { TestRoundtripEncoding(new UnicodeEncoding(bigEndian, byteOrderMark)); } [Fact] public void Encoding_AllAvailable() { foreach (var info in Encoding.GetEncodings()) { TestRoundtripEncoding(Encoding.GetEncoding(info.Name)); } } private static void TestRoundtripEncoding(Encoding encoding) { using var stream = new MemoryStream(); using (var writer = new ObjectWriter(stream, leaveOpen: true)) { writer.WriteEncoding(encoding); } stream.Position = 0; using var reader = ObjectReader.TryGetReader(stream); Assert.NotNull(reader); var actualEncoding = (Encoding)((Encoding)reader.ReadValue()).Clone(); var expectedEncoding = (Encoding)encoding.Clone(); // set the fallbacks to the same instance so that equality comparison does not take them into account: actualEncoding.EncoderFallback = EncoderFallback.ExceptionFallback; actualEncoding.DecoderFallback = DecoderFallback.ExceptionFallback; expectedEncoding.EncoderFallback = EncoderFallback.ExceptionFallback; expectedEncoding.DecoderFallback = DecoderFallback.ExceptionFallback; Assert.Equal(expectedEncoding.GetPreamble(), actualEncoding.GetPreamble()); Assert.Equal(expectedEncoding.CodePage, actualEncoding.CodePage); Assert.Equal(expectedEncoding.WebName, actualEncoding.WebName); Assert.Equal(expectedEncoding, actualEncoding); } [Fact] public void TestObjectMapLimits() { using var stream = new MemoryStream(); var instances = new List<TypeWithTwoMembers<int, string>>(); // We need enough items to exercise all sizes of ObjectRef for (int i = 0; i < ushort.MaxValue + 1; i++) { instances.Add(new TypeWithTwoMembers<int, string>(i, i.ToString())); } using (var writer = new ObjectWriter(stream, leaveOpen: true)) { // Write each instance twice. The second time around, they'll become ObjectRefs for (int pass = 0; pass < 2; pass++) { foreach (var instance in instances) { writer.WriteValue(instance); } } } stream.Position = 0; using (var reader = ObjectReader.TryGetReader(stream, leaveOpen: true)) { for (int pass = 0; pass < 2; pass++) { foreach (var instance in instances) { var obj = reader.ReadValue(); Assert.NotNull(obj); Assert.True(Equalish(obj, instance)); } } } } [Fact] public void TestObjectGraph() { var oneNode = new Node("one"); TestRoundTripValue(oneNode); TestRoundTripValue(new Node("a", new Node("b"), new Node("c"))); TestRoundTripValue(new Node("x", oneNode, oneNode, oneNode, oneNode)); } [Fact] public void TestReuse() { var oneNode = new Node("one"); var n1 = new Node("x", oneNode, oneNode, oneNode, oneNode); var n2 = RoundTripValue(n1, recursive: true); Assert.Same(n2.Children[0], n2.Children[1]); Assert.Same(n2.Children[1], n2.Children[2]); Assert.Same(n2.Children[2], n2.Children[3]); } [Fact] public void TestReuseNegative() { var oneNode = new Node("one", isReusable: false); var n1 = new Node("x", oneNode, oneNode, oneNode, oneNode); var n2 = RoundTripValue(n1, recursive: true); Assert.NotSame(n2.Children[0], n2.Children[1]); Assert.NotSame(n2.Children[1], n2.Children[2]); Assert.NotSame(n2.Children[2], n2.Children[3]); } [Fact] public void TestWideObjectGraph() { int id = 0; var graph = ConstructGraph(ref id, 5, 3); TestRoundTripValue(graph); } [Fact] public void TestDeepObjectGraph_RecursiveSucceeds() { int id = 0; var graph = ConstructGraph(ref id, 1, 1000); TestRoundTripValue(graph); } [Fact] public void TestDeepObjectGraph_NonRecursiveSucceeds() { int id = 0; var graph = ConstructGraph(ref id, 1, 1000); TestRoundTripValue(graph, recursive: false); } private Node ConstructGraph(ref int id, int width, int depth) { var name = "node" + (id++); Node[] children; if (depth > 0) { children = new Node[width]; for (int i = 0; i < width; i++) { children[i] = ConstructGraph(ref id, width, depth - 1); } } else { children = Array.Empty<Node>(); } return new Node(name, children); } private class Node : IObjectWritable, IEquatable<Node> { internal readonly string Name; internal readonly Node[] Children; private readonly bool _isReusable = true; public Node(string name, params Node[] children) { this.Name = name; this.Children = children; } public Node(string name, bool isReusable) : this(name) { this._isReusable = isReusable; } private Node(ObjectReader reader) { this.Name = reader.ReadString(); this.Children = (Node[])reader.ReadValue(); } private static readonly Func<ObjectReader, object> s_createInstance = r => new Node(r); bool IObjectWritable.ShouldReuseInSerialization => _isReusable; public void WriteTo(ObjectWriter writer) { writer.WriteString(this.Name); writer.WriteValue(this.Children); } static Node() { ObjectBinder.RegisterTypeReader(typeof(Node), r => new Node(r)); } public override Int32 GetHashCode() { return this.Name != null ? this.Name.GetHashCode() : 0; } public override Boolean Equals(Object obj) { return Equals(obj as Node); } public bool Equals(Node node) { if (node == null || this.Name != node.Name) { return false; } if (this.Children.Length != node.Children.Length) { return false; } for (int i = 0; i < this.Children.Length; i++) { if (!this.Children[i].Equals(node.Children[i])) { return false; } } return true; } } // keep these around for analyzing perf issues #if false [Fact] public void TestReaderPerf() { var iterations = 10000; var recTime = TestReaderPerf(iterations, recursive: true); var nonTime = TestReaderPerf(iterations, recursive: false); Console.WriteLine($"Recursive Time : {recTime.TotalMilliseconds}"); Console.WriteLine($"Non Recursive Time: {nonTime.TotalMilliseconds}"); } [Fact] public void TestNonRecursiveReaderPerf() { var iterations = 10000; var nonTime = TestReaderPerf(iterations, recursive: false); } private TimeSpan TestReaderPerf(int iterations, bool recursive) { int id = 0; var graph = ConstructGraph(ref id, 5, 3); var stream = new MemoryStream(); var binder = new RecordingObjectBinder(); var writer = new StreamObjectWriter(stream, binder: binder, recursive: recursive); writer.WriteValue(graph); writer.Dispose(); var start = DateTime.Now; for (int i = 0; i < iterations; i++) { stream.Position = 0; var reader = new StreamObjectReader(stream, binder: binder); var item = reader.ReadValue(); } return DateTime.Now - start; } #endif } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Features/LanguageServer/Protocol/Handler/RequestExecutionQueue.QueueItem.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 enable using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { internal partial class RequestExecutionQueue { private readonly struct QueueItem { /// <summary> /// Callback to call into underlying <see cref="IRequestHandler"/> to perform the actual work of this item. /// </summary> private readonly Func<RequestContext, CancellationToken, Task> _callbackAsync; /// <summary> /// <see cref="CorrelationManager.ActivityId"/> used to properly correlate this work with the loghub /// tracing/logging subsystem. /// </summary> public readonly Guid ActivityId; private readonly ILspLogger _logger; /// <inheritdoc cref="IRequestHandler.MutatesSolutionState" /> public readonly bool MutatesSolutionState; /// <inheritdoc cref="IRequestHandler.RequiresLSPSolution" /> public readonly bool RequiresLSPSolution; /// <inheritdoc cref="RequestContext.ClientName" /> public readonly string? ClientName; public readonly string MethodName; /// <inheritdoc cref="RequestContext.ClientCapabilities" /> public readonly ClientCapabilities ClientCapabilities; /// <summary> /// The document identifier that will be used to find the solution and document for this request. This comes from the <see cref="TextDocumentIdentifier"/> returned from the handler itself via a call to <see cref="IRequestHandler{RequestType, ResponseType}.GetTextDocumentIdentifier(RequestType)"/>. /// </summary> public readonly TextDocumentIdentifier? TextDocument; /// <summary> /// A cancellation token that will cancel the handing of this request. The request could also be cancelled by the queue shutting down. /// </summary> public readonly CancellationToken CancellationToken; public readonly RequestMetrics Metrics; public QueueItem( bool mutatesSolutionState, bool requiresLSPSolution, ClientCapabilities clientCapabilities, string? clientName, string methodName, TextDocumentIdentifier? textDocument, Guid activityId, ILspLogger logger, RequestTelemetryLogger telemetryLogger, Func<RequestContext, CancellationToken, Task> callbackAsync, CancellationToken cancellationToken) { Metrics = new RequestMetrics(methodName, telemetryLogger); _callbackAsync = callbackAsync; _logger = logger; ActivityId = activityId; MutatesSolutionState = mutatesSolutionState; RequiresLSPSolution = requiresLSPSolution; ClientCapabilities = clientCapabilities; ClientName = clientName; MethodName = methodName; TextDocument = textDocument; CancellationToken = cancellationToken; } /// <summary> /// Processes the queued request. Exceptions that occur will be sent back to the requesting client, then re-thrown /// </summary> public async Task CallbackAsync(RequestContext context, CancellationToken cancellationToken) { // Restore our activity id so that logging/tracking works. Trace.CorrelationManager.ActivityId = ActivityId; _logger.TraceStart($"{MethodName} - Roslyn"); try { await _callbackAsync(context, cancellationToken).ConfigureAwait(false); this.Metrics.RecordSuccess(); } catch (OperationCanceledException) { _logger.TraceInformation($"{MethodName} - Canceled"); this.Metrics.RecordCancellation(); throw; } catch (Exception ex) { _logger.TraceException(ex); this.Metrics.RecordFailure(); throw; } finally { _logger.TraceStop($"{MethodName} - Roslyn"); } } } } }
// Licensed to the .NET Foundation under one or more 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 enable using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { internal partial class RequestExecutionQueue { private readonly struct QueueItem { /// <summary> /// Callback to call into underlying <see cref="IRequestHandler"/> to perform the actual work of this item. /// </summary> private readonly Func<RequestContext, CancellationToken, Task> _callbackAsync; /// <summary> /// <see cref="CorrelationManager.ActivityId"/> used to properly correlate this work with the loghub /// tracing/logging subsystem. /// </summary> public readonly Guid ActivityId; private readonly ILspLogger _logger; /// <inheritdoc cref="IRequestHandler.MutatesSolutionState" /> public readonly bool MutatesSolutionState; /// <inheritdoc cref="IRequestHandler.RequiresLSPSolution" /> public readonly bool RequiresLSPSolution; /// <inheritdoc cref="RequestContext.ClientName" /> public readonly string? ClientName; public readonly string MethodName; /// <inheritdoc cref="RequestContext.ClientCapabilities" /> public readonly ClientCapabilities ClientCapabilities; /// <summary> /// The document identifier that will be used to find the solution and document for this request. This comes from the <see cref="TextDocumentIdentifier"/> returned from the handler itself via a call to <see cref="IRequestHandler{RequestType, ResponseType}.GetTextDocumentIdentifier(RequestType)"/>. /// </summary> public readonly TextDocumentIdentifier? TextDocument; /// <summary> /// A cancellation token that will cancel the handing of this request. The request could also be cancelled by the queue shutting down. /// </summary> public readonly CancellationToken CancellationToken; public readonly RequestMetrics Metrics; public QueueItem( bool mutatesSolutionState, bool requiresLSPSolution, ClientCapabilities clientCapabilities, string? clientName, string methodName, TextDocumentIdentifier? textDocument, Guid activityId, ILspLogger logger, RequestTelemetryLogger telemetryLogger, Func<RequestContext, CancellationToken, Task> callbackAsync, CancellationToken cancellationToken) { Metrics = new RequestMetrics(methodName, telemetryLogger); _callbackAsync = callbackAsync; _logger = logger; ActivityId = activityId; MutatesSolutionState = mutatesSolutionState; RequiresLSPSolution = requiresLSPSolution; ClientCapabilities = clientCapabilities; ClientName = clientName; MethodName = methodName; TextDocument = textDocument; CancellationToken = cancellationToken; } /// <summary> /// Processes the queued request. Exceptions that occur will be sent back to the requesting client, then re-thrown /// </summary> public async Task CallbackAsync(RequestContext context, CancellationToken cancellationToken) { // Restore our activity id so that logging/tracking works. Trace.CorrelationManager.ActivityId = ActivityId; _logger.TraceStart($"{MethodName} - Roslyn"); try { await _callbackAsync(context, cancellationToken).ConfigureAwait(false); this.Metrics.RecordSuccess(); } catch (OperationCanceledException) { _logger.TraceInformation($"{MethodName} - Canceled"); this.Metrics.RecordCancellation(); throw; } catch (Exception ex) { _logger.TraceException(ex); this.Metrics.RecordFailure(); throw; } finally { _logger.TraceStop($"{MethodName} - Roslyn"); } } } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/Core/Portable/Workspace/Solution/TreeAndVersion.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 { /// <summary> /// A class that represents both a tree and its top level signature version /// </summary> internal sealed class TreeAndVersion { /// <summary> /// The syntax tree /// </summary> public SyntaxTree Tree { get; } /// <summary> /// The version of the top level signature of the tree /// </summary> public VersionStamp Version { get; } private TreeAndVersion(SyntaxTree tree, VersionStamp version) { this.Tree = tree; this.Version = version; } public static TreeAndVersion Create(SyntaxTree tree, VersionStamp version) { if (tree == null) { throw new ArgumentNullException(nameof(tree)); } return new TreeAndVersion(tree, version); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis { /// <summary> /// A class that represents both a tree and its top level signature version /// </summary> internal sealed class TreeAndVersion { /// <summary> /// The syntax tree /// </summary> public SyntaxTree Tree { get; } /// <summary> /// The version of the top level signature of the tree /// </summary> public VersionStamp Version { get; } private TreeAndVersion(SyntaxTree tree, VersionStamp version) { this.Tree = tree; this.Version = version; } public static TreeAndVersion Create(SyntaxTree tree, VersionStamp version) { if (tree == null) { throw new ArgumentNullException(nameof(tree)); } return new TreeAndVersion(tree, version); } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/VisualStudio/Core/Def/Implementation/Library/ObjectBrowser/AbstractObjectBrowserLibraryManager_Description.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.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser { internal abstract partial class AbstractObjectBrowserLibraryManager { internal bool TryFillDescription(ObjectListItem listItem, IVsObjectBrowserDescription3 description, _VSOBJDESCOPTIONS options) { var project = GetProject(listItem); if (project == null) { return false; } return CreateDescriptionBuilder(description, listItem, project).TryBuild(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. #nullable disable using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser { internal abstract partial class AbstractObjectBrowserLibraryManager { internal bool TryFillDescription(ObjectListItem listItem, IVsObjectBrowserDescription3 description, _VSOBJDESCOPTIONS options) { var project = GetProject(listItem); if (project == null) { return false; } return CreateDescriptionBuilder(description, listItem, project).TryBuild(options); } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/VisualStudio/CSharp/Impl/Options/Formatting/StyleViewModel.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.Windows.Data; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.AddImports; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options.Formatting { /// <summary> /// This is the view model for CodeStyle options page. /// </summary> /// <remarks> /// The codestyle options page is defined in <see cref="CodeStylePage"/> /// </remarks> internal class StyleViewModel : AbstractOptionPreviewViewModel { #region "Preview Text" private const string s_fieldDeclarationPreviewTrue = @" class C{ int capacity; void Method() { //[ this.capacity = 0; //] } }"; private const string s_fieldDeclarationPreviewFalse = @" class C{ int capacity; void Method() { //[ capacity = 0; //] } }"; private const string s_propertyDeclarationPreviewTrue = @" class C{ public int Id { get; set; } void Method() { //[ this.Id = 0; //] } }"; private const string s_propertyDeclarationPreviewFalse = @" class C{ public int Id { get; set; } void Method() { //[ Id = 0; //] } }"; private const string s_eventDeclarationPreviewTrue = @" using System; class C{ event EventHandler Elapsed; void Handler(object sender, EventArgs args) { //[ this.Elapsed += Handler; //] } }"; private const string s_eventDeclarationPreviewFalse = @" using System; class C{ event EventHandler Elapsed; void Handler(object sender, EventArgs args) { //[ Elapsed += Handler; //] } }"; private const string s_methodDeclarationPreviewTrue = @" using System; class C{ void Display() { //[ this.Display(); //] } }"; private const string s_methodDeclarationPreviewFalse = @" using System; class C{ void Display() { //[ Display(); //] } }"; private const string s_intrinsicPreviewDeclarationTrue = @" class Program { //[ private int _member; static void M(int argument) { int local; } //] }"; private const string s_intrinsicPreviewDeclarationFalse = @" using System; class Program { //[ private Int32 _member; static void M(Int32 argument) { Int32 local; } //] }"; private const string s_intrinsicPreviewMemberAccessTrue = @" class Program { //[ static void M() { var local = int.MaxValue; } //] }"; private const string s_intrinsicPreviewMemberAccessFalse = @" using System; class Program { //[ static void M() { var local = Int32.MaxValue; } //] }"; private static readonly string s_varForIntrinsicsPreviewFalse = $@" using System; class C{{ void Method() {{ //[ int x = 5; // {ServicesVSResources.built_in_types} //] }} }}"; private static readonly string s_varForIntrinsicsPreviewTrue = $@" using System; class C{{ void Method() {{ //[ var x = 5; // {ServicesVSResources.built_in_types} //] }} }}"; private static readonly string s_varWhereApparentPreviewFalse = $@" using System; class C{{ void Method() {{ //[ C cobj = new C(); // {ServicesVSResources.type_is_apparent_from_assignment_expression} //] }} }}"; private static readonly string s_varWhereApparentPreviewTrue = $@" using System; class C{{ void Method() {{ //[ var cobj = new C(); // {ServicesVSResources.type_is_apparent_from_assignment_expression} //] }} }}"; private static readonly string s_varWherePossiblePreviewFalse = $@" using System; class C{{ void Init() {{ //[ Action f = this.Init(); // {ServicesVSResources.everywhere_else} //] }} }}"; private static readonly string s_varWherePossiblePreviewTrue = $@" using System; class C{{ void Init() {{ //[ var f = this.Init(); // {ServicesVSResources.everywhere_else} //] }} }}"; private static readonly string s_preferThrowExpression = $@" using System; class C {{ private string s; void M1(string s) {{ //[ // {ServicesVSResources.Prefer_colon} this.s = s ?? throw new ArgumentNullException(nameof(s)); //] }} void M2(string s) {{ //[ // {ServicesVSResources.Over_colon} if (s == null) {{ throw new ArgumentNullException(nameof(s)); }} this.s = s; //] }} }} "; private static readonly string s_preferCoalesceExpression = $@" using System; class C {{ private string s; void M1(string s) {{ //[ // {ServicesVSResources.Prefer_colon} var v = x ?? y; //] }} void M2(string s) {{ //[ // {ServicesVSResources.Over_colon} var v = x != null ? x : y; // {ServicesVSResources.or} var v = x == null ? y : x; //] }} }} "; private static readonly string s_preferConditionalDelegateCall = $@" using System; class C {{ private string s; void M1(string s) {{ //[ // {ServicesVSResources.Prefer_colon} func?.Invoke(args); //] }} void M2(string s) {{ //[ // {ServicesVSResources.Over_colon} if (func != null) {{ func(args); }} //] }} }} "; private static readonly string s_preferNullPropagation = $@" using System; class C {{ void M1(object o) {{ //[ // {ServicesVSResources.Prefer_colon} var v = o?.ToString(); //] }} void M2(object o) {{ //[ // {ServicesVSResources.Over_colon} var v = o == null ? null : o.ToString(); // {ServicesVSResources.or} var v = o != null ? o.ToString() : null; //] }} }} "; private static readonly string s_preferSwitchExpression = $@" class C {{ void M1() {{ //[ // {ServicesVSResources.Prefer_colon} return num switch {{ 1 => 1, _ => 2, }} //] }} void M2() {{ //[ // {ServicesVSResources.Over_colon} switch (num) {{ case 1: return 1; default: return 2; }} //] }} }} "; private static readonly string s_preferPatternMatching = $@" class C {{ void M1() {{ //[ // {ServicesVSResources.Prefer_colon} return num is 1 or 2; //] }} void M2() {{ //[ // {ServicesVSResources.Over_colon} return num == 1 || num == 2; //] }} }} "; private static readonly string s_preferPatternMatchingOverAsWithNullCheck = $@" class C {{ void M1() {{ //[ // {ServicesVSResources.Prefer_colon} if (o is string s) {{ }} //] }} void M2() {{ //[ // {ServicesVSResources.Over_colon} var s = o as string; if (s != null) {{ }} //] }} }} "; private static readonly string s_preferPatternMatchingOverMixedTypeCheck = $@" class C {{ void M1() {{ //[ // {ServicesVSResources.Prefer_colon} if (o is not string s) {{ }} //] }} void M2() {{ //[ // {ServicesVSResources.Over_colon} if (!(o is string s)) {{ }} //] }} }} "; private static readonly string s_preferConditionalExpressionOverIfWithAssignments = $@" class C {{ void M() {{ //[ // {ServicesVSResources.Prefer_colon} string s = expr ? ""hello"" : ""world""; // {ServicesVSResources.Over_colon} string s; if (expr) {{ s = ""hello""; }} else {{ s = ""world""; }} //] }} }} "; private static readonly string s_preferConditionalExpressionOverIfWithReturns = $@" class C {{ void M() {{ //[ // {ServicesVSResources.Prefer_colon} return expr ? ""hello"" : ""world""; // {ServicesVSResources.Over_colon} if (expr) {{ return ""hello""; }} else {{ return ""world""; }} //] }} }} "; private static readonly string s_preferPatternMatchingOverIsWithCastCheck = $@" class C {{ void M1() {{ //[ // {ServicesVSResources.Prefer_colon} if (o is int i) {{ }} //] }} void M2() {{ //[ // {ServicesVSResources.Over_colon} if (o is int) {{ var i = (int)o; }} //] }} }} "; private static readonly string s_preferObjectInitializer = $@" using System; class Customer {{ private int Age; void M1() {{ //[ // {ServicesVSResources.Prefer_colon} var c = new Customer() {{ Age = 21 }}; //] }} void M2() {{ //[ // {ServicesVSResources.Over_colon} var c = new Customer(); c.Age = 21; //] }} }} "; private static readonly string s_preferCollectionInitializer = $@" using System.Collections.Generic; class Customer {{ private int Age; void M1() {{ //[ // {ServicesVSResources.Prefer_colon} var list = new List<int> {{ 1, 2, 3 }}; //] }} void M2() {{ //[ // {ServicesVSResources.Over_colon} var list = new List<int>(); list.Add(1); list.Add(2); list.Add(3); //] }} }} "; private static readonly string s_preferExplicitTupleName = $@" class Customer {{ void M1() {{ //[ // {ServicesVSResources.Prefer_colon} (string name, int age) customer = GetCustomer(); var name = customer.name; var age = customer.age; //] }} void M2() {{ //[ // {ServicesVSResources.Over_colon} (string name, int age) customer = GetCustomer(); var name = customer.Item1; var age = customer.Item2; //] }} }} "; private static readonly string s_preferSimpleDefaultExpression = $@" using System.Threading; class Customer1 {{ //[ // {ServicesVSResources.Prefer_colon} void DoWork(CancellationToken cancellationToken = default) {{ }} //] }} class Customer2 {{ //[ // {ServicesVSResources.Over_colon} void DoWork(CancellationToken cancellationToken = default(CancellationToken)) {{ }} //] }} "; private static readonly string s_preferSimplifiedConditionalExpression = $@" using System.Threading; class Customer1 {{ bool A() => true; bool B() => true; void M1() {{ //[ // {ServicesVSResources.Prefer_colon} var x = A() && B(); //] }} void M2() {{ //[ // {ServicesVSResources.Over_colon} var x = A() && B() ? true : false //] }} }} "; private static readonly string s_preferInferredTupleName = $@" using System.Threading; class Customer {{ void M1(int age, string name) {{ //[ // {ServicesVSResources.Prefer_colon} var tuple = (age, name); //] }} void M2(int age, string name) {{ //[ // {ServicesVSResources.Over_colon} var tuple = (age: age, name: name); //] }} }} "; private static readonly string s_preferInferredAnonymousTypeMemberName = $@" using System.Threading; class Customer {{ void M1(int age, string name) {{ //[ // {ServicesVSResources.Prefer_colon} var anon = new {{ age, name }}; //] }} void M2(int age, string name) {{ //[ // {ServicesVSResources.Over_colon} var anon = new {{ age = age, name = name }}; //] }} }} "; private static readonly string s_preferInlinedVariableDeclaration = $@" using System; class Customer {{ void M1(string value) {{ //[ // {ServicesVSResources.Prefer_colon} if (int.TryParse(value, out int i)) {{ }} //] }} void M2(string value) {{ //[ // {ServicesVSResources.Over_colon} int i; if (int.TryParse(value, out i)) {{ }} //] }} }} "; private static readonly string s_preferDeconstructedVariableDeclaration = $@" using System; class Customer {{ void M1(string value) {{ //[ // {ServicesVSResources.Prefer_colon} var (name, age) = GetPersonTuple(); Console.WriteLine($""{{name}} {{age}}""); (int x, int y) = GetPointTuple(); Console.WriteLine($""{{x}} {{y}}""); //] }} void M2(string value) {{ //[ // {ServicesVSResources.Over_colon} var person = GetPersonTuple(); Console.WriteLine($""{{person.name}} {{person.age}}""); (int x, int y) point = GetPointTuple(); Console.WriteLine($""{{point.x}} {{point.y}}""); //] }} }} "; private static readonly string s_doNotPreferBraces = $@" using System; class Customer {{ private int Age; void M1() {{ //[ // {ServicesVSResources.Allow_colon} if (test) Console.WriteLine(""Text""); // {ServicesVSResources.Allow_colon} if (test) Console.WriteLine(""Text""); // {ServicesVSResources.Allow_colon} if (test) Console.WriteLine( ""Text""); // {ServicesVSResources.Allow_colon} if (test) {{ Console.WriteLine( ""Text""); }} //] }} }} "; private static readonly string s_preferBracesWhenMultiline = $@" using System; class Customer {{ private int Age; void M1() {{ //[ // {ServicesVSResources.Allow_colon} if (test) Console.WriteLine(""Text""); // {ServicesVSResources.Allow_colon} if (test) Console.WriteLine(""Text""); // {ServicesVSResources.Prefer_colon} if (test) {{ Console.WriteLine( ""Text""); }} //] }} void M2() {{ //[ // {ServicesVSResources.Over_colon} if (test) Console.WriteLine( ""Text""); //] }} }} "; private static readonly string s_preferBraces = $@" using System; class Customer {{ private int Age; void M1() {{ //[ // {ServicesVSResources.Prefer_colon} if (test) {{ Console.WriteLine(""Text""); }} //] }} void M2() {{ //[ // {ServicesVSResources.Over_colon} if (test) Console.WriteLine(""Text""); //] }} }} "; private static readonly string s_preferAutoProperties = $@" using System; class Customer1 {{ //[ // {ServicesVSResources.Prefer_colon} public int Age {{ get; }} //] }} class Customer2 {{ //[ // {ServicesVSResources.Over_colon} private int age; public int Age {{ get {{ return age; }} }} //] }} "; private static readonly string s_preferFileScopedNamespace = $@" //[ // {ServicesVSResources.Prefer_colon} namespace A.B.C; public class Program {{ }} //] //[ // {ServicesVSResources.Over_colon} namespace A.B.C {{ public class Program {{ }} }} //] "; private static readonly string s_preferBlockNamespace = $@" //[ // {ServicesVSResources.Prefer_colon} namespace A.B.C {{ public class Program {{ }} }} //] //[ // {ServicesVSResources.Over_colon} namespace A.B.C; public class Program {{ }} //] "; private static readonly string s_preferSimpleUsingStatement = $@" using System; class Customer1 {{ //[ // {ServicesVSResources.Prefer_colon} void Method() {{ using var resource = GetResource(); ProcessResource(resource); }} //] }} class Customer2 {{ //[ // {ServicesVSResources.Over_colon} void Method() {{ using (var resource = GetResource()) {{ ProcessResource(resource); }} }} //] }} "; private static readonly string s_preferSystemHashCode = $@" using System; class Customer1 {{ int a, b, c; //[ // {ServicesVSResources.Prefer_colon} // {ServicesVSResources.Requires_System_HashCode_be_present_in_project} public override int GetHashCode() {{ return System.HashCode.Combine(a, b, c); }} //] }} class Customer2 {{ int a, b, c; //[ // {ServicesVSResources.Over_colon} public override int GetHashCode() {{ var hashCode = 339610899; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); hashCode = hashCode * -1521134295 + c.GetHashCode(); return hashCode; }} //] }} "; private static readonly string s_preferLocalFunctionOverAnonymousFunction = $@" using System; class Customer {{ void M1(string value) {{ //[ // {ServicesVSResources.Prefer_colon} int fibonacci(int n) {{ return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); }} //] }} void M2(string value) {{ //[ // {ServicesVSResources.Over_colon} Func<int, int> fibonacci = null; fibonacci = (int n) => {{ return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); }}; //] }} }} "; private static readonly string s_preferCompoundAssignments = $@" using System; class Customer {{ void M1(int value) {{ //[ // {ServicesVSResources.Prefer_colon} value += 10; //] }} void M2(int value) {{ //[ // {ServicesVSResources.Over_colon} value = value + 10 //] }} }} "; private static readonly string s_preferImplicitObjectCreationWhenTypeIsApparent = $@" using System.Collections.Generic; class Order {{}} //[ class Customer {{ // {ServicesVSResources.Prefer_colon} private readonly List<Order> orders = new(); // {ServicesVSResources.Over_colon} private readonly List<Order> orders = new List<Order>(); }} //] "; private static readonly string s_preferIndexOperator = $@" using System; class Customer {{ void M1(string value) {{ //[ // {ServicesVSResources.Prefer_colon} var ch = value[^1]; //] }} void M2(string value) {{ //[ // {ServicesVSResources.Over_colon} var ch = value[value.Length - 1]; //] }} }} "; private static readonly string s_preferRangeOperator = $@" using System; class Customer {{ void M1(string value) {{ //[ // {ServicesVSResources.Prefer_colon} var sub = value[1..^1]; //] }} void M2(string value) {{ //[ // {ServicesVSResources.Over_colon} var sub = value.Substring(1, value.Length - 2); //] }} }} "; private static readonly string s_preferIsNullOverReferenceEquals = $@" using System; class Customer {{ void M1(string value1, string value2) {{ //[ // {ServicesVSResources.Prefer_colon} if (value1 is null) return; if (value2 is null) return; //] }} void M2(string value1, string value2) {{ //[ // {ServicesVSResources.Over_colon} if (object.ReferenceEquals(value1, null)) return; if ((object)value2 == null) return; //] }} }} "; private static readonly string s_preferNullcheckOverTypeCheck = $@" using System; class Customer {{ void M1(string value1, string value2) {{ //[ // {ServicesVSResources.Prefer_colon} if (value1 is null) return; if (value2 is not null) return; //] }} void M2(string value1, string value2) {{ //[ // {ServicesVSResources.Over_colon} if (value1 is not object) return; if (value2 is object) return; //] }} }} "; #region expression and block bodies private const string s_preferExpressionBodyForMethods = @" using System; //[ class Customer { private int Age; public int GetAge() => this.Age; } //] "; private const string s_preferBlockBodyForMethods = @" using System; //[ class Customer { private int Age; public int GetAge() { return this.Age; } } //] "; private const string s_preferExpressionBodyForConstructors = @" using System; //[ class Customer { private int Age; public Customer(int age) => Age = age; } //] "; private const string s_preferBlockBodyForConstructors = @" using System; //[ class Customer { private int Age; public Customer(int age) { Age = age; } } //] "; private const string s_preferExpressionBodyForOperators = @" using System; struct ComplexNumber { //[ public static ComplexNumber operator +(ComplexNumber c1, ComplexNumber c2) => new ComplexNumber(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary); //] } "; private const string s_preferBlockBodyForOperators = @" using System; struct ComplexNumber { //[ public static ComplexNumber operator +(ComplexNumber c1, ComplexNumber c2) { return new ComplexNumber(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary); } //] } "; private const string s_preferExpressionBodyForProperties = @" using System; //[ class Customer { private int _age; public int Age => _age; } //] "; private const string s_preferBlockBodyForProperties = @" using System; //[ class Customer { private int _age; public int Age { get { return _age; } } } //] "; private const string s_preferExpressionBodyForAccessors = @" using System; //[ class Customer { private int _age; public int Age { get => _age; set => _age = value; } } //] "; private const string s_preferBlockBodyForAccessors = @" using System; //[ class Customer { private int _age; public int Age { get { return _age; } set { _age = value; } } } //] "; private const string s_preferExpressionBodyForIndexers = @" using System; //[ class List<T> { private T[] _values; public T this[int i] => _values[i]; } //] "; private const string s_preferBlockBodyForIndexers = @" using System; //[ class List<T> { private T[] _values; public T this[int i] { get { return _values[i]; } } } //] "; private const string s_preferExpressionBodyForLambdas = @" using System; class Customer { void Method() { //[ Func<int, string> f = a => a.ToString(); //] } } "; private const string s_preferBlockBodyForLambdas = @" using System; class Customer { void Method() { //[ Func<int, string> f = a => { return a.ToString(); }; //] } } "; private const string s_preferExpressionBodyForLocalFunctions = @" using System; //[ class Customer { private int Age; public int GetAge() { return GetAgeLocal(); int GetAgeLocal() => this.Age; } } //] "; private const string s_preferBlockBodyForLocalFunctions = @" using System; //[ class Customer { private int Age; public int GetAge() { return GetAgeLocal(); int GetAgeLocal() { return this.Age; } } } //] "; private static readonly string s_preferReadonly = $@" class Customer1 {{ //[ // {ServicesVSResources.Prefer_colon} // '_value' can only be assigned in constructor private readonly int _value = 0; //] }} class Customer2 {{ //[ // {ServicesVSResources.Over_colon} // '_value' can be assigned anywhere private int _value = 0; //] }} "; private static readonly string[] s_usingDirectivePlacement = new[] { $@" //[ namespace Namespace {{ // {CSharpVSResources.Inside_namespace} using System; using System.Linq; class Customer {{ }} }} //]", $@" //[ // {CSharpVSResources.Outside_namespace} using System; using System.Linq; namespace Namespace {{ class Customer {{ }} }} //] " }; private static readonly string s_preferStaticLocalFunction = $@" class Customer1 {{ //[ void Method() {{ // {ServicesVSResources.Prefer_colon} static int fibonacci(int n) {{ return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); }} }} //] }} class Customer2 {{ //[ void Method() {{ // {ServicesVSResources.Over_colon} int fibonacci(int n) {{ return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); }} }} //] }} "; private static readonly string s_allow_embedded_statements_on_same_line_true = $@" class Class2 {{ void Method(int a, int b) {{ //[ // {ServicesVSResources.Allow_colon} if (a > b) return true; //] return false; }} }} "; private static readonly string s_allow_embedded_statements_on_same_line_false = $@" class Class1 {{ void Method(int a, int b) {{ //[ // {ServicesVSResources.Require_colon} if (a > b) return true; //] return false; }} }} class Class2 {{ void Method(int a, int b) {{ //[ // {ServicesVSResources.Over_colon} if (a > b) return true; //] return false; }} }} "; private static readonly string s_allow_blank_line_between_consecutive_braces_true = $@" class Class2 {{ //[ // {ServicesVSResources.Allow_colon} void Method() {{ if (true) {{ DoWork(); }} }} //] }} "; private static readonly string s_allow_blank_line_between_consecutive_braces_false = $@" class Class1 {{ //[ // {ServicesVSResources.Require_colon} void Method() {{ if (true) {{ DoWork(); }} }} //] }} class Class2 {{ //[ // {ServicesVSResources.Over_colon} void Method() {{ if (true) {{ DoWork(); }} }} //] }} "; private static readonly string s_allow_multiple_blank_lines_true = $@" class Class2 {{ void Method() {{ //[ // {ServicesVSResources.Allow_colon} if (true) {{ DoWork(); }} return; //] }} }} "; private static readonly string s_allow_multiple_blank_lines_false = $@" class Class1 {{ void Method() {{ //[ // {ServicesVSResources.Require_colon} if (true) {{ DoWork(); }} return; //] }} }} class Class2 {{ void Method() {{ //[ // {ServicesVSResources.Over_colon} if (true) {{ DoWork(); }} return; //] }} }} "; private static readonly string s_allow_statement_immediately_after_block_true = $@" class Class2 {{ void Method() {{ //[ // {ServicesVSResources.Allow_colon} if (true) {{ DoWork(); }} return; //] }} }} "; private static readonly string s_allow_statement_immediately_after_block_false = $@" class Class1 {{ void Method() {{ //[ // {ServicesVSResources.Require_colon} if (true) {{ DoWork(); }} return; //] }} }} class Class2 {{ void Method() {{ //[ // {ServicesVSResources.Over_colon} if (true) {{ DoWork(); }} return; //] }} }} "; private static readonly string s_allow_bank_line_after_colon_in_constructor_initializer_true = $@" class Class {{ //[ // {ServicesVSResources.Allow_colon} public Class() : base() {{ }} //] }} "; private static readonly string s_allow_bank_line_after_colon_in_constructor_initializer_false = $@" namespace NS1 {{ class Class {{ //[ // {ServicesVSResources.Require_colon} public Class() : base() {{ }} //] }} }} namespace NS2 {{ class Class {{ //[ // {ServicesVSResources.Over_colon} public Class() : base() {{ }} //] }} }} "; #endregion #region arithmetic binary parentheses private readonly string s_arithmeticBinaryAlwaysForClarity = $@" class C {{ void M() {{ //[ // {ServicesVSResources.Prefer_colon} var v = a + (b * c); // {ServicesVSResources.Over_colon} var v = a + b * c; //] }} }} "; private readonly string s_arithmeticBinaryNeverIfUnnecessary = $@" class C {{ void M() {{ //[ // {ServicesVSResources.Prefer_colon} var v = a + b * c; // {ServicesVSResources.Over_colon} var v = a + (b * c); //] }} }} "; #endregion #region relational binary parentheses private readonly string s_relationalBinaryAlwaysForClarity = $@" class C {{ void M() {{ //[ // {ServicesVSResources.Prefer_colon} var v = (a < b) == (c > d); // {ServicesVSResources.Over_colon} var v = a < b == c > d; //] }} }} "; private readonly string s_relationalBinaryNeverIfUnnecessary = $@" class C {{ void M() {{ //[ // {ServicesVSResources.Prefer_colon} var v = a < b == c > d; // {ServicesVSResources.Over_colon} var v = (a < b) == (c > d); //] }} }} "; #endregion #region other binary parentheses private readonly string s_otherBinaryAlwaysForClarity = $@" class C {{ void M() {{ //[ // {ServicesVSResources.Prefer_colon} var v = a || (b && c); // {ServicesVSResources.Over_colon} var v = a || b && c; //] }} }} "; private readonly string s_otherBinaryNeverIfUnnecessary = $@" class C {{ void M() {{ //[ // {ServicesVSResources.Prefer_colon} var v = a || b && c; // {ServicesVSResources.Over_colon} var v = a || (b && c); //] }} }} "; #endregion #region other parentheses private readonly string s_otherParenthesesAlwaysForClarity = $@" class C {{ void M() {{ //[ // {ServicesVSResources.Keep_all_parentheses_in_colon} var v = (a.b).Length; //] }} }} "; private readonly string s_otherParenthesesNeverIfUnnecessary = $@" class C {{ void M() {{ //[ // {ServicesVSResources.Prefer_colon} var v = a.b.Length; // {ServicesVSResources.Over_colon} var v = (a.b).Length; //] }} }} "; #endregion #region unused parameters private static readonly string s_avoidUnusedParametersNonPublicMethods = $@" class C1 {{ //[ // {ServicesVSResources.Prefer_colon} private void M() {{ }} //] }} class C2 {{ //[ // {ServicesVSResources.Over_colon} private void M(int param) {{ }} //] }} "; private static readonly string s_avoidUnusedParametersAllMethods = $@" class C1 {{ //[ // {ServicesVSResources.Prefer_colon} public void M() {{ }} //] }} class C2 {{ //[ // {ServicesVSResources.Over_colon} public void M(int param) {{ }} //] }} "; #endregion #region unused values private static readonly string s_avoidUnusedValueAssignmentUnusedLocal = $@" class C {{ int M() {{ //[ // {ServicesVSResources.Prefer_colon} int unused = Computation(); // {ServicesVSResources.Unused_value_is_explicitly_assigned_to_an_unused_local} int x = 1; //] return x; }} int Computation() => 0; }} class C2 {{ int M() {{ //[ // {ServicesVSResources.Over_colon} int x = Computation(); // {ServicesVSResources.Value_assigned_here_is_never_used} x = 1; //] return x; }} int Computation() => 0; }} "; private static readonly string s_avoidUnusedValueAssignmentDiscard = $@" class C {{ int M() {{ //[ // {ServicesVSResources.Prefer_colon} _ = Computation(); // {ServicesVSResources.Unused_value_is_explicitly_assigned_to_discard} int x = 1; //] return x; }} int Computation() => 0; }} class C2 {{ int M() {{ //[ // {ServicesVSResources.Over_colon} int x = Computation(); // {ServicesVSResources.Value_assigned_here_is_never_used} x = 1; //] return x; }} int Computation() => 0; }} "; private static readonly string s_avoidUnusedValueExpressionStatementUnusedLocal = $@" class C {{ void M() {{ //[ // {ServicesVSResources.Prefer_colon} int unused = Computation(); // {ServicesVSResources.Unused_value_is_explicitly_assigned_to_an_unused_local} //] }} int Computation() => 0; }} class C2 {{ void M() {{ //[ // {ServicesVSResources.Over_colon} Computation(); // {ServicesVSResources.Value_returned_by_invocation_is_implicitly_ignored} //] }} int Computation() => 0; }} "; private static readonly string s_avoidUnusedValueExpressionStatementDiscard = $@" class C {{ void M() {{ //[ // {ServicesVSResources.Prefer_colon} _ = Computation(); // {ServicesVSResources.Unused_value_is_explicitly_assigned_to_discard} //] }} int Computation() => 0; }} class C2 {{ void M() {{ //[ // {ServicesVSResources.Over_colon} Computation(); // {ServicesVSResources.Value_returned_by_invocation_is_implicitly_ignored} //] }} int Computation() => 0; }} "; #endregion #endregion internal StyleViewModel(OptionStore optionStore, IServiceProvider serviceProvider) : base(optionStore, serviceProvider, LanguageNames.CSharp) { var collectionView = (ListCollectionView)CollectionViewSource.GetDefaultView(CodeStyleItems); collectionView.GroupDescriptions.Add(new PropertyGroupDescription(nameof(AbstractCodeStyleOptionViewModel.GroupName))); var qualifyGroupTitle = CSharpVSResources.this_preferences_colon; var predefinedTypesGroupTitle = CSharpVSResources.predefined_type_preferences_colon; var varGroupTitle = CSharpVSResources.var_preferences_colon; var nullCheckingGroupTitle = CSharpVSResources.null_checking_colon; var usingsGroupTitle = CSharpVSResources.using_preferences_colon; var modifierGroupTitle = ServicesVSResources.Modifier_preferences_colon; var codeBlockPreferencesGroupTitle = ServicesVSResources.Code_block_preferences_colon; var expressionPreferencesGroupTitle = ServicesVSResources.Expression_preferences_colon; var patternMatchingPreferencesGroupTitle = CSharpVSResources.Pattern_matching_preferences_colon; var variablePreferencesGroupTitle = ServicesVSResources.Variable_preferences_colon; var parameterPreferencesGroupTitle = ServicesVSResources.Parameter_preferences_colon; var newLinePreferencesGroupTitle = ServicesVSResources.New_line_preferences_experimental_colon; var usingDirectivePlacementPreferences = new List<CodeStylePreference> { new CodeStylePreference(CSharpVSResources.Inside_namespace, isChecked: false), new CodeStylePreference(CSharpVSResources.Outside_namespace, isChecked: false), }; var qualifyMemberAccessPreferences = new List<CodeStylePreference> { new CodeStylePreference(CSharpVSResources.Prefer_this, isChecked: true), new CodeStylePreference(CSharpVSResources.Do_not_prefer_this, isChecked: false), }; var predefinedTypesPreferences = new List<CodeStylePreference> { new CodeStylePreference(ServicesVSResources.Prefer_predefined_type, isChecked: true), new CodeStylePreference(ServicesVSResources.Prefer_framework_type, isChecked: false), }; var typeStylePreferences = new List<CodeStylePreference> { new CodeStylePreference(CSharpVSResources.Prefer_var, isChecked: true), new CodeStylePreference(CSharpVSResources.Prefer_explicit_type, isChecked: false), }; CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.QualifyFieldAccess, CSharpVSResources.Qualify_field_access_with_this, s_fieldDeclarationPreviewTrue, s_fieldDeclarationPreviewFalse, this, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.QualifyPropertyAccess, CSharpVSResources.Qualify_property_access_with_this, s_propertyDeclarationPreviewTrue, s_propertyDeclarationPreviewFalse, this, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.QualifyMethodAccess, CSharpVSResources.Qualify_method_access_with_this, s_methodDeclarationPreviewTrue, s_methodDeclarationPreviewFalse, this, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.QualifyEventAccess, CSharpVSResources.Qualify_event_access_with_this, s_eventDeclarationPreviewTrue, s_eventDeclarationPreviewFalse, this, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, ServicesVSResources.For_locals_parameters_and_members, s_intrinsicPreviewDeclarationTrue, s_intrinsicPreviewDeclarationFalse, this, optionStore, predefinedTypesGroupTitle, predefinedTypesPreferences)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, ServicesVSResources.For_member_access_expressions, s_intrinsicPreviewMemberAccessTrue, s_intrinsicPreviewMemberAccessFalse, this, optionStore, predefinedTypesGroupTitle, predefinedTypesPreferences)); // Use var CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.VarForBuiltInTypes, CSharpVSResources.For_built_in_types, s_varForIntrinsicsPreviewTrue, s_varForIntrinsicsPreviewFalse, this, optionStore, varGroupTitle, typeStylePreferences)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.VarWhenTypeIsApparent, CSharpVSResources.When_variable_type_is_apparent, s_varWhereApparentPreviewTrue, s_varWhereApparentPreviewFalse, this, optionStore, varGroupTitle, typeStylePreferences)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.VarElsewhere, CSharpVSResources.Elsewhere, s_varWherePossiblePreviewTrue, s_varWherePossiblePreviewFalse, this, optionStore, varGroupTitle, typeStylePreferences)); // Code block AddBracesOptions(optionStore, codeBlockPreferencesGroupTitle); AddNamespaceDeclarationsOptions(optionStore, codeBlockPreferencesGroupTitle); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferAutoProperties, ServicesVSResources.analyzer_Prefer_auto_properties, s_preferAutoProperties, s_preferAutoProperties, this, optionStore, codeBlockPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferSimpleUsingStatement, ServicesVSResources.Prefer_simple_using_statement, s_preferSimpleUsingStatement, s_preferSimpleUsingStatement, this, optionStore, codeBlockPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferSystemHashCode, ServicesVSResources.Prefer_System_HashCode_in_GetHashCode, s_preferSystemHashCode, s_preferSystemHashCode, this, optionStore, codeBlockPreferencesGroupTitle)); AddParenthesesOptions(OptionStore); // Expression preferences CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferObjectInitializer, ServicesVSResources.Prefer_object_initializer, s_preferObjectInitializer, s_preferObjectInitializer, this, optionStore, expressionPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferCollectionInitializer, ServicesVSResources.Prefer_collection_initializer, s_preferCollectionInitializer, s_preferCollectionInitializer, this, optionStore, expressionPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferSimplifiedBooleanExpressions, ServicesVSResources.Prefer_simplified_boolean_expressions, s_preferSimplifiedConditionalExpression, s_preferSimplifiedConditionalExpression, this, optionStore, expressionPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferSwitchExpression, CSharpVSResources.Prefer_switch_expression, s_preferSwitchExpression, s_preferSwitchExpression, this, optionStore, expressionPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferConditionalExpressionOverAssignment, ServicesVSResources.Prefer_conditional_expression_over_if_with_assignments, s_preferConditionalExpressionOverIfWithAssignments, s_preferConditionalExpressionOverIfWithAssignments, this, optionStore, expressionPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferConditionalExpressionOverReturn, ServicesVSResources.Prefer_conditional_expression_over_if_with_returns, s_preferConditionalExpressionOverIfWithReturns, s_preferConditionalExpressionOverIfWithReturns, this, optionStore, expressionPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferExplicitTupleNames, ServicesVSResources.Prefer_explicit_tuple_name, s_preferExplicitTupleName, s_preferExplicitTupleName, this, optionStore, expressionPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferSimpleDefaultExpression, ServicesVSResources.Prefer_simple_default_expression, s_preferSimpleDefaultExpression, s_preferSimpleDefaultExpression, this, optionStore, expressionPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferInferredTupleNames, ServicesVSResources.Prefer_inferred_tuple_names, s_preferInferredTupleName, s_preferInferredTupleName, this, optionStore, expressionPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferInferredAnonymousTypeMemberNames, ServicesVSResources.Prefer_inferred_anonymous_type_member_names, s_preferInferredAnonymousTypeMemberName, s_preferInferredAnonymousTypeMemberName, this, optionStore, expressionPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferLocalOverAnonymousFunction, ServicesVSResources.Prefer_local_function_over_anonymous_function, s_preferLocalFunctionOverAnonymousFunction, s_preferLocalFunctionOverAnonymousFunction, this, optionStore, expressionPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferCompoundAssignment, ServicesVSResources.Prefer_compound_assignments, s_preferCompoundAssignments, s_preferCompoundAssignments, this, optionStore, expressionPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.ImplicitObjectCreationWhenTypeIsApparent, CSharpVSResources.Prefer_implicit_object_creation_when_type_is_apparent, s_preferImplicitObjectCreationWhenTypeIsApparent, s_preferImplicitObjectCreationWhenTypeIsApparent, this, optionStore, expressionPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferIndexOperator, ServicesVSResources.Prefer_index_operator, s_preferIndexOperator, s_preferIndexOperator, this, optionStore, expressionPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferRangeOperator, ServicesVSResources.Prefer_range_operator, s_preferRangeOperator, s_preferRangeOperator, this, optionStore, expressionPreferencesGroupTitle)); // Pattern matching CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferPatternMatching, CSharpVSResources.Prefer_pattern_matching, s_preferPatternMatching, s_preferPatternMatching, this, optionStore, patternMatchingPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferPatternMatchingOverIsWithCastCheck, CSharpVSResources.Prefer_pattern_matching_over_is_with_cast_check, s_preferPatternMatchingOverIsWithCastCheck, s_preferPatternMatchingOverIsWithCastCheck, this, optionStore, patternMatchingPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferPatternMatchingOverAsWithNullCheck, CSharpVSResources.Prefer_pattern_matching_over_as_with_null_check, s_preferPatternMatchingOverAsWithNullCheck, s_preferPatternMatchingOverAsWithNullCheck, this, optionStore, patternMatchingPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferNotPattern, CSharpVSResources.Prefer_pattern_matching_over_mixed_type_check, s_preferPatternMatchingOverMixedTypeCheck, s_preferPatternMatchingOverMixedTypeCheck, this, optionStore, patternMatchingPreferencesGroupTitle)); AddExpressionBodyOptions(optionStore, expressionPreferencesGroupTitle); AddUnusedValueOptions(optionStore, expressionPreferencesGroupTitle); // Variable preferences CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferInlinedVariableDeclaration, ServicesVSResources.Prefer_inlined_variable_declaration, s_preferInlinedVariableDeclaration, s_preferInlinedVariableDeclaration, this, optionStore, variablePreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferDeconstructedVariableDeclaration, ServicesVSResources.Prefer_deconstructed_variable_declaration, s_preferDeconstructedVariableDeclaration, s_preferDeconstructedVariableDeclaration, this, optionStore, variablePreferencesGroupTitle)); // Null preferences. CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferThrowExpression, CSharpVSResources.Prefer_throw_expression, s_preferThrowExpression, s_preferThrowExpression, this, optionStore, nullCheckingGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferConditionalDelegateCall, CSharpVSResources.Prefer_conditional_delegate_call, s_preferConditionalDelegateCall, s_preferConditionalDelegateCall, this, optionStore, nullCheckingGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferCoalesceExpression, ServicesVSResources.Prefer_coalesce_expression, s_preferCoalesceExpression, s_preferCoalesceExpression, this, optionStore, nullCheckingGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferNullPropagation, ServicesVSResources.Prefer_null_propagation, s_preferNullPropagation, s_preferNullPropagation, this, optionStore, nullCheckingGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferIsNullCheckOverReferenceEqualityMethod, CSharpVSResources.Prefer_is_null_for_reference_equality_checks, s_preferIsNullOverReferenceEquals, s_preferIsNullOverReferenceEquals, this, optionStore, nullCheckingGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferNullCheckOverTypeCheck, CSharpVSResources.Prefer_null_check_over_type_check, s_preferNullcheckOverTypeCheck, s_preferNullcheckOverTypeCheck, this, optionStore, nullCheckingGroupTitle)); // Using directive preferences. CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<AddImportPlacement>( CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, CSharpVSResources.Preferred_using_directive_placement, new[] { AddImportPlacement.InsideNamespace, AddImportPlacement.OutsideNamespace }, s_usingDirectivePlacement, this, optionStore, usingsGroupTitle, usingDirectivePlacementPreferences)); // Modifier preferences. CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferReadonly, ServicesVSResources.Prefer_readonly_fields, s_preferReadonly, s_preferReadonly, this, optionStore, modifierGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferStaticLocalFunction, ServicesVSResources.Prefer_static_local_functions, s_preferStaticLocalFunction, s_preferStaticLocalFunction, this, optionStore, modifierGroupTitle)); // Parameter preferences AddParameterOptions(optionStore, parameterPreferencesGroupTitle); // New line preferences. CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.AllowMultipleBlankLines, ServicesVSResources.Allow_multiple_blank_lines, s_allow_multiple_blank_lines_true, s_allow_multiple_blank_lines_false, this, optionStore, newLinePreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.AllowEmbeddedStatementsOnSameLine, CSharpVSResources.Allow_embedded_statements_on_same_line, s_allow_embedded_statements_on_same_line_true, s_allow_embedded_statements_on_same_line_false, this, optionStore, newLinePreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CSharpVSResources.Allow_blank_lines_between_consecutive_braces, s_allow_blank_line_between_consecutive_braces_true, s_allow_blank_line_between_consecutive_braces_false, this, optionStore, newLinePreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, ServicesVSResources.Allow_statement_immediately_after_block, s_allow_statement_immediately_after_block_true, s_allow_statement_immediately_after_block_false, this, optionStore, newLinePreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer, CSharpVSResources.Allow_bank_line_after_colon_in_constructor_initializer, s_allow_bank_line_after_colon_in_constructor_initializer_true, s_allow_bank_line_after_colon_in_constructor_initializer_false, this, optionStore, newLinePreferencesGroupTitle)); } private void AddParenthesesOptions(OptionStore optionStore) { AddParenthesesOption( LanguageNames.CSharp, optionStore, CodeStyleOptions2.ArithmeticBinaryParentheses, CSharpVSResources.In_arithmetic_binary_operators, new[] { s_arithmeticBinaryAlwaysForClarity, s_arithmeticBinaryNeverIfUnnecessary }, defaultAddForClarity: true); AddParenthesesOption( LanguageNames.CSharp, optionStore, CodeStyleOptions2.OtherBinaryParentheses, CSharpVSResources.In_other_binary_operators, new[] { s_otherBinaryAlwaysForClarity, s_otherBinaryNeverIfUnnecessary }, defaultAddForClarity: true); AddParenthesesOption( LanguageNames.CSharp, optionStore, CodeStyleOptions2.RelationalBinaryParentheses, CSharpVSResources.In_relational_binary_operators, new[] { s_relationalBinaryAlwaysForClarity, s_relationalBinaryNeverIfUnnecessary }, defaultAddForClarity: true); AddParenthesesOption( LanguageNames.CSharp, optionStore, CodeStyleOptions2.OtherParentheses, ServicesVSResources.In_other_operators, new[] { s_otherParenthesesAlwaysForClarity, s_otherParenthesesNeverIfUnnecessary }, defaultAddForClarity: false); } private void AddBracesOptions(OptionStore optionStore, string bracesPreferenceGroupTitle) { var bracesPreferences = new List<CodeStylePreference> { new CodeStylePreference(ServicesVSResources.Yes, isChecked: false), new CodeStylePreference(ServicesVSResources.No, isChecked: false), new CodeStylePreference(CSharpVSResources.When_on_multiple_lines, isChecked: false), }; var enumValues = new[] { PreferBracesPreference.Always, PreferBracesPreference.None, PreferBracesPreference.WhenMultiline }; CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<PreferBracesPreference>( CSharpCodeStyleOptions.PreferBraces, ServicesVSResources.Prefer_braces, enumValues, new[] { s_preferBraces, s_doNotPreferBraces, s_preferBracesWhenMultiline }, this, optionStore, bracesPreferenceGroupTitle, bracesPreferences)); } private void AddNamespaceDeclarationsOptions(OptionStore optionStore, string group) { var preferences = new List<CodeStylePreference> { new CodeStylePreference(CSharpVSResources.Block_scoped, isChecked: false), new CodeStylePreference(CSharpVSResources.File_scoped, isChecked: false), }; var enumValues = new[] { NamespaceDeclarationPreference.BlockScoped, NamespaceDeclarationPreference.FileScoped }; CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<NamespaceDeclarationPreference>( CSharpCodeStyleOptions.NamespaceDeclarations, ServicesVSResources.Namespace_declarations, enumValues, new[] { s_preferBlockNamespace, s_preferFileScopedNamespace }, this, optionStore, group, preferences)); } private void AddExpressionBodyOptions(OptionStore optionStore, string expressionPreferencesGroupTitle) { var expressionBodyPreferences = new List<CodeStylePreference> { new CodeStylePreference(CSharpVSResources.Never, isChecked: false), new CodeStylePreference(CSharpVSResources.When_possible, isChecked: false), new CodeStylePreference(CSharpVSResources.When_on_single_line, isChecked: false), }; var enumValues = new[] { ExpressionBodyPreference.Never, ExpressionBodyPreference.WhenPossible, ExpressionBodyPreference.WhenOnSingleLine }; CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<ExpressionBodyPreference>( CSharpCodeStyleOptions.PreferExpressionBodiedMethods, ServicesVSResources.Use_expression_body_for_methods, enumValues, new[] { s_preferBlockBodyForMethods, s_preferExpressionBodyForMethods, s_preferExpressionBodyForMethods }, this, optionStore, expressionPreferencesGroupTitle, expressionBodyPreferences)); CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<ExpressionBodyPreference>( CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, ServicesVSResources.Use_expression_body_for_constructors, enumValues, new[] { s_preferBlockBodyForConstructors, s_preferExpressionBodyForConstructors, s_preferExpressionBodyForConstructors }, this, optionStore, expressionPreferencesGroupTitle, expressionBodyPreferences)); CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<ExpressionBodyPreference>( CSharpCodeStyleOptions.PreferExpressionBodiedOperators, ServicesVSResources.Use_expression_body_for_operators, enumValues, new[] { s_preferBlockBodyForOperators, s_preferExpressionBodyForOperators, s_preferExpressionBodyForOperators }, this, optionStore, expressionPreferencesGroupTitle, expressionBodyPreferences)); CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<ExpressionBodyPreference>( CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ServicesVSResources.Use_expression_body_for_properties, enumValues, new[] { s_preferBlockBodyForProperties, s_preferExpressionBodyForProperties, s_preferExpressionBodyForProperties }, this, optionStore, expressionPreferencesGroupTitle, expressionBodyPreferences)); CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<ExpressionBodyPreference>( CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ServicesVSResources.Use_expression_body_for_indexers, enumValues, new[] { s_preferBlockBodyForIndexers, s_preferExpressionBodyForIndexers, s_preferExpressionBodyForIndexers }, this, optionStore, expressionPreferencesGroupTitle, expressionBodyPreferences)); CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<ExpressionBodyPreference>( CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ServicesVSResources.Use_expression_body_for_accessors, enumValues, new[] { s_preferBlockBodyForAccessors, s_preferExpressionBodyForAccessors, s_preferExpressionBodyForAccessors }, this, optionStore, expressionPreferencesGroupTitle, expressionBodyPreferences)); CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<ExpressionBodyPreference>( CSharpCodeStyleOptions.PreferExpressionBodiedLambdas, ServicesVSResources.Use_expression_body_for_lambdas, enumValues, new[] { s_preferBlockBodyForLambdas, s_preferExpressionBodyForLambdas, s_preferExpressionBodyForLambdas }, this, optionStore, expressionPreferencesGroupTitle, expressionBodyPreferences)); CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<ExpressionBodyPreference>( CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, ServicesVSResources.Use_expression_body_for_local_functions, enumValues, new[] { s_preferBlockBodyForLocalFunctions, s_preferExpressionBodyForLocalFunctions, s_preferExpressionBodyForLocalFunctions }, this, optionStore, expressionPreferencesGroupTitle, expressionBodyPreferences)); } private void AddUnusedValueOptions(OptionStore optionStore, string expressionPreferencesGroupTitle) { var unusedValuePreferences = new List<CodeStylePreference> { new CodeStylePreference(CSharpVSResources.Unused_local, isChecked: false), new CodeStylePreference(CSharpVSResources.Discard, isChecked: true), }; var enumValues = new[] { UnusedValuePreference.UnusedLocalVariable, UnusedValuePreference.DiscardVariable }; CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<UnusedValuePreference>( CSharpCodeStyleOptions.UnusedValueAssignment, ServicesVSResources.Avoid_unused_value_assignments, enumValues, new[] { s_avoidUnusedValueAssignmentUnusedLocal, s_avoidUnusedValueAssignmentDiscard }, this, optionStore, expressionPreferencesGroupTitle, unusedValuePreferences)); CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<UnusedValuePreference>( CSharpCodeStyleOptions.UnusedValueExpressionStatement, ServicesVSResources.Avoid_expression_statements_that_implicitly_ignore_value, enumValues, new[] { s_avoidUnusedValueExpressionStatementUnusedLocal, s_avoidUnusedValueExpressionStatementDiscard }, this, optionStore, expressionPreferencesGroupTitle, unusedValuePreferences)); } private void AddParameterOptions(OptionStore optionStore, string parameterPreferencesGroupTitle) { var examples = new[] { s_avoidUnusedParametersNonPublicMethods, s_avoidUnusedParametersAllMethods }; AddUnusedParameterOption(LanguageNames.CSharp, optionStore, parameterPreferencesGroupTitle, examples); } } }
// Licensed to the .NET Foundation under one or more 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.Windows.Data; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.AddImports; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options.Formatting { /// <summary> /// This is the view model for CodeStyle options page. /// </summary> /// <remarks> /// The codestyle options page is defined in <see cref="CodeStylePage"/> /// </remarks> internal class StyleViewModel : AbstractOptionPreviewViewModel { #region "Preview Text" private const string s_fieldDeclarationPreviewTrue = @" class C{ int capacity; void Method() { //[ this.capacity = 0; //] } }"; private const string s_fieldDeclarationPreviewFalse = @" class C{ int capacity; void Method() { //[ capacity = 0; //] } }"; private const string s_propertyDeclarationPreviewTrue = @" class C{ public int Id { get; set; } void Method() { //[ this.Id = 0; //] } }"; private const string s_propertyDeclarationPreviewFalse = @" class C{ public int Id { get; set; } void Method() { //[ Id = 0; //] } }"; private const string s_eventDeclarationPreviewTrue = @" using System; class C{ event EventHandler Elapsed; void Handler(object sender, EventArgs args) { //[ this.Elapsed += Handler; //] } }"; private const string s_eventDeclarationPreviewFalse = @" using System; class C{ event EventHandler Elapsed; void Handler(object sender, EventArgs args) { //[ Elapsed += Handler; //] } }"; private const string s_methodDeclarationPreviewTrue = @" using System; class C{ void Display() { //[ this.Display(); //] } }"; private const string s_methodDeclarationPreviewFalse = @" using System; class C{ void Display() { //[ Display(); //] } }"; private const string s_intrinsicPreviewDeclarationTrue = @" class Program { //[ private int _member; static void M(int argument) { int local; } //] }"; private const string s_intrinsicPreviewDeclarationFalse = @" using System; class Program { //[ private Int32 _member; static void M(Int32 argument) { Int32 local; } //] }"; private const string s_intrinsicPreviewMemberAccessTrue = @" class Program { //[ static void M() { var local = int.MaxValue; } //] }"; private const string s_intrinsicPreviewMemberAccessFalse = @" using System; class Program { //[ static void M() { var local = Int32.MaxValue; } //] }"; private static readonly string s_varForIntrinsicsPreviewFalse = $@" using System; class C{{ void Method() {{ //[ int x = 5; // {ServicesVSResources.built_in_types} //] }} }}"; private static readonly string s_varForIntrinsicsPreviewTrue = $@" using System; class C{{ void Method() {{ //[ var x = 5; // {ServicesVSResources.built_in_types} //] }} }}"; private static readonly string s_varWhereApparentPreviewFalse = $@" using System; class C{{ void Method() {{ //[ C cobj = new C(); // {ServicesVSResources.type_is_apparent_from_assignment_expression} //] }} }}"; private static readonly string s_varWhereApparentPreviewTrue = $@" using System; class C{{ void Method() {{ //[ var cobj = new C(); // {ServicesVSResources.type_is_apparent_from_assignment_expression} //] }} }}"; private static readonly string s_varWherePossiblePreviewFalse = $@" using System; class C{{ void Init() {{ //[ Action f = this.Init(); // {ServicesVSResources.everywhere_else} //] }} }}"; private static readonly string s_varWherePossiblePreviewTrue = $@" using System; class C{{ void Init() {{ //[ var f = this.Init(); // {ServicesVSResources.everywhere_else} //] }} }}"; private static readonly string s_preferThrowExpression = $@" using System; class C {{ private string s; void M1(string s) {{ //[ // {ServicesVSResources.Prefer_colon} this.s = s ?? throw new ArgumentNullException(nameof(s)); //] }} void M2(string s) {{ //[ // {ServicesVSResources.Over_colon} if (s == null) {{ throw new ArgumentNullException(nameof(s)); }} this.s = s; //] }} }} "; private static readonly string s_preferCoalesceExpression = $@" using System; class C {{ private string s; void M1(string s) {{ //[ // {ServicesVSResources.Prefer_colon} var v = x ?? y; //] }} void M2(string s) {{ //[ // {ServicesVSResources.Over_colon} var v = x != null ? x : y; // {ServicesVSResources.or} var v = x == null ? y : x; //] }} }} "; private static readonly string s_preferConditionalDelegateCall = $@" using System; class C {{ private string s; void M1(string s) {{ //[ // {ServicesVSResources.Prefer_colon} func?.Invoke(args); //] }} void M2(string s) {{ //[ // {ServicesVSResources.Over_colon} if (func != null) {{ func(args); }} //] }} }} "; private static readonly string s_preferNullPropagation = $@" using System; class C {{ void M1(object o) {{ //[ // {ServicesVSResources.Prefer_colon} var v = o?.ToString(); //] }} void M2(object o) {{ //[ // {ServicesVSResources.Over_colon} var v = o == null ? null : o.ToString(); // {ServicesVSResources.or} var v = o != null ? o.ToString() : null; //] }} }} "; private static readonly string s_preferSwitchExpression = $@" class C {{ void M1() {{ //[ // {ServicesVSResources.Prefer_colon} return num switch {{ 1 => 1, _ => 2, }} //] }} void M2() {{ //[ // {ServicesVSResources.Over_colon} switch (num) {{ case 1: return 1; default: return 2; }} //] }} }} "; private static readonly string s_preferPatternMatching = $@" class C {{ void M1() {{ //[ // {ServicesVSResources.Prefer_colon} return num is 1 or 2; //] }} void M2() {{ //[ // {ServicesVSResources.Over_colon} return num == 1 || num == 2; //] }} }} "; private static readonly string s_preferPatternMatchingOverAsWithNullCheck = $@" class C {{ void M1() {{ //[ // {ServicesVSResources.Prefer_colon} if (o is string s) {{ }} //] }} void M2() {{ //[ // {ServicesVSResources.Over_colon} var s = o as string; if (s != null) {{ }} //] }} }} "; private static readonly string s_preferPatternMatchingOverMixedTypeCheck = $@" class C {{ void M1() {{ //[ // {ServicesVSResources.Prefer_colon} if (o is not string s) {{ }} //] }} void M2() {{ //[ // {ServicesVSResources.Over_colon} if (!(o is string s)) {{ }} //] }} }} "; private static readonly string s_preferConditionalExpressionOverIfWithAssignments = $@" class C {{ void M() {{ //[ // {ServicesVSResources.Prefer_colon} string s = expr ? ""hello"" : ""world""; // {ServicesVSResources.Over_colon} string s; if (expr) {{ s = ""hello""; }} else {{ s = ""world""; }} //] }} }} "; private static readonly string s_preferConditionalExpressionOverIfWithReturns = $@" class C {{ void M() {{ //[ // {ServicesVSResources.Prefer_colon} return expr ? ""hello"" : ""world""; // {ServicesVSResources.Over_colon} if (expr) {{ return ""hello""; }} else {{ return ""world""; }} //] }} }} "; private static readonly string s_preferPatternMatchingOverIsWithCastCheck = $@" class C {{ void M1() {{ //[ // {ServicesVSResources.Prefer_colon} if (o is int i) {{ }} //] }} void M2() {{ //[ // {ServicesVSResources.Over_colon} if (o is int) {{ var i = (int)o; }} //] }} }} "; private static readonly string s_preferObjectInitializer = $@" using System; class Customer {{ private int Age; void M1() {{ //[ // {ServicesVSResources.Prefer_colon} var c = new Customer() {{ Age = 21 }}; //] }} void M2() {{ //[ // {ServicesVSResources.Over_colon} var c = new Customer(); c.Age = 21; //] }} }} "; private static readonly string s_preferCollectionInitializer = $@" using System.Collections.Generic; class Customer {{ private int Age; void M1() {{ //[ // {ServicesVSResources.Prefer_colon} var list = new List<int> {{ 1, 2, 3 }}; //] }} void M2() {{ //[ // {ServicesVSResources.Over_colon} var list = new List<int>(); list.Add(1); list.Add(2); list.Add(3); //] }} }} "; private static readonly string s_preferExplicitTupleName = $@" class Customer {{ void M1() {{ //[ // {ServicesVSResources.Prefer_colon} (string name, int age) customer = GetCustomer(); var name = customer.name; var age = customer.age; //] }} void M2() {{ //[ // {ServicesVSResources.Over_colon} (string name, int age) customer = GetCustomer(); var name = customer.Item1; var age = customer.Item2; //] }} }} "; private static readonly string s_preferSimpleDefaultExpression = $@" using System.Threading; class Customer1 {{ //[ // {ServicesVSResources.Prefer_colon} void DoWork(CancellationToken cancellationToken = default) {{ }} //] }} class Customer2 {{ //[ // {ServicesVSResources.Over_colon} void DoWork(CancellationToken cancellationToken = default(CancellationToken)) {{ }} //] }} "; private static readonly string s_preferSimplifiedConditionalExpression = $@" using System.Threading; class Customer1 {{ bool A() => true; bool B() => true; void M1() {{ //[ // {ServicesVSResources.Prefer_colon} var x = A() && B(); //] }} void M2() {{ //[ // {ServicesVSResources.Over_colon} var x = A() && B() ? true : false //] }} }} "; private static readonly string s_preferInferredTupleName = $@" using System.Threading; class Customer {{ void M1(int age, string name) {{ //[ // {ServicesVSResources.Prefer_colon} var tuple = (age, name); //] }} void M2(int age, string name) {{ //[ // {ServicesVSResources.Over_colon} var tuple = (age: age, name: name); //] }} }} "; private static readonly string s_preferInferredAnonymousTypeMemberName = $@" using System.Threading; class Customer {{ void M1(int age, string name) {{ //[ // {ServicesVSResources.Prefer_colon} var anon = new {{ age, name }}; //] }} void M2(int age, string name) {{ //[ // {ServicesVSResources.Over_colon} var anon = new {{ age = age, name = name }}; //] }} }} "; private static readonly string s_preferInlinedVariableDeclaration = $@" using System; class Customer {{ void M1(string value) {{ //[ // {ServicesVSResources.Prefer_colon} if (int.TryParse(value, out int i)) {{ }} //] }} void M2(string value) {{ //[ // {ServicesVSResources.Over_colon} int i; if (int.TryParse(value, out i)) {{ }} //] }} }} "; private static readonly string s_preferDeconstructedVariableDeclaration = $@" using System; class Customer {{ void M1(string value) {{ //[ // {ServicesVSResources.Prefer_colon} var (name, age) = GetPersonTuple(); Console.WriteLine($""{{name}} {{age}}""); (int x, int y) = GetPointTuple(); Console.WriteLine($""{{x}} {{y}}""); //] }} void M2(string value) {{ //[ // {ServicesVSResources.Over_colon} var person = GetPersonTuple(); Console.WriteLine($""{{person.name}} {{person.age}}""); (int x, int y) point = GetPointTuple(); Console.WriteLine($""{{point.x}} {{point.y}}""); //] }} }} "; private static readonly string s_doNotPreferBraces = $@" using System; class Customer {{ private int Age; void M1() {{ //[ // {ServicesVSResources.Allow_colon} if (test) Console.WriteLine(""Text""); // {ServicesVSResources.Allow_colon} if (test) Console.WriteLine(""Text""); // {ServicesVSResources.Allow_colon} if (test) Console.WriteLine( ""Text""); // {ServicesVSResources.Allow_colon} if (test) {{ Console.WriteLine( ""Text""); }} //] }} }} "; private static readonly string s_preferBracesWhenMultiline = $@" using System; class Customer {{ private int Age; void M1() {{ //[ // {ServicesVSResources.Allow_colon} if (test) Console.WriteLine(""Text""); // {ServicesVSResources.Allow_colon} if (test) Console.WriteLine(""Text""); // {ServicesVSResources.Prefer_colon} if (test) {{ Console.WriteLine( ""Text""); }} //] }} void M2() {{ //[ // {ServicesVSResources.Over_colon} if (test) Console.WriteLine( ""Text""); //] }} }} "; private static readonly string s_preferBraces = $@" using System; class Customer {{ private int Age; void M1() {{ //[ // {ServicesVSResources.Prefer_colon} if (test) {{ Console.WriteLine(""Text""); }} //] }} void M2() {{ //[ // {ServicesVSResources.Over_colon} if (test) Console.WriteLine(""Text""); //] }} }} "; private static readonly string s_preferAutoProperties = $@" using System; class Customer1 {{ //[ // {ServicesVSResources.Prefer_colon} public int Age {{ get; }} //] }} class Customer2 {{ //[ // {ServicesVSResources.Over_colon} private int age; public int Age {{ get {{ return age; }} }} //] }} "; private static readonly string s_preferFileScopedNamespace = $@" //[ // {ServicesVSResources.Prefer_colon} namespace A.B.C; public class Program {{ }} //] //[ // {ServicesVSResources.Over_colon} namespace A.B.C {{ public class Program {{ }} }} //] "; private static readonly string s_preferBlockNamespace = $@" //[ // {ServicesVSResources.Prefer_colon} namespace A.B.C {{ public class Program {{ }} }} //] //[ // {ServicesVSResources.Over_colon} namespace A.B.C; public class Program {{ }} //] "; private static readonly string s_preferSimpleUsingStatement = $@" using System; class Customer1 {{ //[ // {ServicesVSResources.Prefer_colon} void Method() {{ using var resource = GetResource(); ProcessResource(resource); }} //] }} class Customer2 {{ //[ // {ServicesVSResources.Over_colon} void Method() {{ using (var resource = GetResource()) {{ ProcessResource(resource); }} }} //] }} "; private static readonly string s_preferSystemHashCode = $@" using System; class Customer1 {{ int a, b, c; //[ // {ServicesVSResources.Prefer_colon} // {ServicesVSResources.Requires_System_HashCode_be_present_in_project} public override int GetHashCode() {{ return System.HashCode.Combine(a, b, c); }} //] }} class Customer2 {{ int a, b, c; //[ // {ServicesVSResources.Over_colon} public override int GetHashCode() {{ var hashCode = 339610899; hashCode = hashCode * -1521134295 + a.GetHashCode(); hashCode = hashCode * -1521134295 + b.GetHashCode(); hashCode = hashCode * -1521134295 + c.GetHashCode(); return hashCode; }} //] }} "; private static readonly string s_preferLocalFunctionOverAnonymousFunction = $@" using System; class Customer {{ void M1(string value) {{ //[ // {ServicesVSResources.Prefer_colon} int fibonacci(int n) {{ return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); }} //] }} void M2(string value) {{ //[ // {ServicesVSResources.Over_colon} Func<int, int> fibonacci = null; fibonacci = (int n) => {{ return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); }}; //] }} }} "; private static readonly string s_preferCompoundAssignments = $@" using System; class Customer {{ void M1(int value) {{ //[ // {ServicesVSResources.Prefer_colon} value += 10; //] }} void M2(int value) {{ //[ // {ServicesVSResources.Over_colon} value = value + 10 //] }} }} "; private static readonly string s_preferImplicitObjectCreationWhenTypeIsApparent = $@" using System.Collections.Generic; class Order {{}} //[ class Customer {{ // {ServicesVSResources.Prefer_colon} private readonly List<Order> orders = new(); // {ServicesVSResources.Over_colon} private readonly List<Order> orders = new List<Order>(); }} //] "; private static readonly string s_preferIndexOperator = $@" using System; class Customer {{ void M1(string value) {{ //[ // {ServicesVSResources.Prefer_colon} var ch = value[^1]; //] }} void M2(string value) {{ //[ // {ServicesVSResources.Over_colon} var ch = value[value.Length - 1]; //] }} }} "; private static readonly string s_preferRangeOperator = $@" using System; class Customer {{ void M1(string value) {{ //[ // {ServicesVSResources.Prefer_colon} var sub = value[1..^1]; //] }} void M2(string value) {{ //[ // {ServicesVSResources.Over_colon} var sub = value.Substring(1, value.Length - 2); //] }} }} "; private static readonly string s_preferIsNullOverReferenceEquals = $@" using System; class Customer {{ void M1(string value1, string value2) {{ //[ // {ServicesVSResources.Prefer_colon} if (value1 is null) return; if (value2 is null) return; //] }} void M2(string value1, string value2) {{ //[ // {ServicesVSResources.Over_colon} if (object.ReferenceEquals(value1, null)) return; if ((object)value2 == null) return; //] }} }} "; private static readonly string s_preferNullcheckOverTypeCheck = $@" using System; class Customer {{ void M1(string value1, string value2) {{ //[ // {ServicesVSResources.Prefer_colon} if (value1 is null) return; if (value2 is not null) return; //] }} void M2(string value1, string value2) {{ //[ // {ServicesVSResources.Over_colon} if (value1 is not object) return; if (value2 is object) return; //] }} }} "; #region expression and block bodies private const string s_preferExpressionBodyForMethods = @" using System; //[ class Customer { private int Age; public int GetAge() => this.Age; } //] "; private const string s_preferBlockBodyForMethods = @" using System; //[ class Customer { private int Age; public int GetAge() { return this.Age; } } //] "; private const string s_preferExpressionBodyForConstructors = @" using System; //[ class Customer { private int Age; public Customer(int age) => Age = age; } //] "; private const string s_preferBlockBodyForConstructors = @" using System; //[ class Customer { private int Age; public Customer(int age) { Age = age; } } //] "; private const string s_preferExpressionBodyForOperators = @" using System; struct ComplexNumber { //[ public static ComplexNumber operator +(ComplexNumber c1, ComplexNumber c2) => new ComplexNumber(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary); //] } "; private const string s_preferBlockBodyForOperators = @" using System; struct ComplexNumber { //[ public static ComplexNumber operator +(ComplexNumber c1, ComplexNumber c2) { return new ComplexNumber(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary); } //] } "; private const string s_preferExpressionBodyForProperties = @" using System; //[ class Customer { private int _age; public int Age => _age; } //] "; private const string s_preferBlockBodyForProperties = @" using System; //[ class Customer { private int _age; public int Age { get { return _age; } } } //] "; private const string s_preferExpressionBodyForAccessors = @" using System; //[ class Customer { private int _age; public int Age { get => _age; set => _age = value; } } //] "; private const string s_preferBlockBodyForAccessors = @" using System; //[ class Customer { private int _age; public int Age { get { return _age; } set { _age = value; } } } //] "; private const string s_preferExpressionBodyForIndexers = @" using System; //[ class List<T> { private T[] _values; public T this[int i] => _values[i]; } //] "; private const string s_preferBlockBodyForIndexers = @" using System; //[ class List<T> { private T[] _values; public T this[int i] { get { return _values[i]; } } } //] "; private const string s_preferExpressionBodyForLambdas = @" using System; class Customer { void Method() { //[ Func<int, string> f = a => a.ToString(); //] } } "; private const string s_preferBlockBodyForLambdas = @" using System; class Customer { void Method() { //[ Func<int, string> f = a => { return a.ToString(); }; //] } } "; private const string s_preferExpressionBodyForLocalFunctions = @" using System; //[ class Customer { private int Age; public int GetAge() { return GetAgeLocal(); int GetAgeLocal() => this.Age; } } //] "; private const string s_preferBlockBodyForLocalFunctions = @" using System; //[ class Customer { private int Age; public int GetAge() { return GetAgeLocal(); int GetAgeLocal() { return this.Age; } } } //] "; private static readonly string s_preferReadonly = $@" class Customer1 {{ //[ // {ServicesVSResources.Prefer_colon} // '_value' can only be assigned in constructor private readonly int _value = 0; //] }} class Customer2 {{ //[ // {ServicesVSResources.Over_colon} // '_value' can be assigned anywhere private int _value = 0; //] }} "; private static readonly string[] s_usingDirectivePlacement = new[] { $@" //[ namespace Namespace {{ // {CSharpVSResources.Inside_namespace} using System; using System.Linq; class Customer {{ }} }} //]", $@" //[ // {CSharpVSResources.Outside_namespace} using System; using System.Linq; namespace Namespace {{ class Customer {{ }} }} //] " }; private static readonly string s_preferStaticLocalFunction = $@" class Customer1 {{ //[ void Method() {{ // {ServicesVSResources.Prefer_colon} static int fibonacci(int n) {{ return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); }} }} //] }} class Customer2 {{ //[ void Method() {{ // {ServicesVSResources.Over_colon} int fibonacci(int n) {{ return n <= 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); }} }} //] }} "; private static readonly string s_allow_embedded_statements_on_same_line_true = $@" class Class2 {{ void Method(int a, int b) {{ //[ // {ServicesVSResources.Allow_colon} if (a > b) return true; //] return false; }} }} "; private static readonly string s_allow_embedded_statements_on_same_line_false = $@" class Class1 {{ void Method(int a, int b) {{ //[ // {ServicesVSResources.Require_colon} if (a > b) return true; //] return false; }} }} class Class2 {{ void Method(int a, int b) {{ //[ // {ServicesVSResources.Over_colon} if (a > b) return true; //] return false; }} }} "; private static readonly string s_allow_blank_line_between_consecutive_braces_true = $@" class Class2 {{ //[ // {ServicesVSResources.Allow_colon} void Method() {{ if (true) {{ DoWork(); }} }} //] }} "; private static readonly string s_allow_blank_line_between_consecutive_braces_false = $@" class Class1 {{ //[ // {ServicesVSResources.Require_colon} void Method() {{ if (true) {{ DoWork(); }} }} //] }} class Class2 {{ //[ // {ServicesVSResources.Over_colon} void Method() {{ if (true) {{ DoWork(); }} }} //] }} "; private static readonly string s_allow_multiple_blank_lines_true = $@" class Class2 {{ void Method() {{ //[ // {ServicesVSResources.Allow_colon} if (true) {{ DoWork(); }} return; //] }} }} "; private static readonly string s_allow_multiple_blank_lines_false = $@" class Class1 {{ void Method() {{ //[ // {ServicesVSResources.Require_colon} if (true) {{ DoWork(); }} return; //] }} }} class Class2 {{ void Method() {{ //[ // {ServicesVSResources.Over_colon} if (true) {{ DoWork(); }} return; //] }} }} "; private static readonly string s_allow_statement_immediately_after_block_true = $@" class Class2 {{ void Method() {{ //[ // {ServicesVSResources.Allow_colon} if (true) {{ DoWork(); }} return; //] }} }} "; private static readonly string s_allow_statement_immediately_after_block_false = $@" class Class1 {{ void Method() {{ //[ // {ServicesVSResources.Require_colon} if (true) {{ DoWork(); }} return; //] }} }} class Class2 {{ void Method() {{ //[ // {ServicesVSResources.Over_colon} if (true) {{ DoWork(); }} return; //] }} }} "; private static readonly string s_allow_bank_line_after_colon_in_constructor_initializer_true = $@" class Class {{ //[ // {ServicesVSResources.Allow_colon} public Class() : base() {{ }} //] }} "; private static readonly string s_allow_bank_line_after_colon_in_constructor_initializer_false = $@" namespace NS1 {{ class Class {{ //[ // {ServicesVSResources.Require_colon} public Class() : base() {{ }} //] }} }} namespace NS2 {{ class Class {{ //[ // {ServicesVSResources.Over_colon} public Class() : base() {{ }} //] }} }} "; #endregion #region arithmetic binary parentheses private readonly string s_arithmeticBinaryAlwaysForClarity = $@" class C {{ void M() {{ //[ // {ServicesVSResources.Prefer_colon} var v = a + (b * c); // {ServicesVSResources.Over_colon} var v = a + b * c; //] }} }} "; private readonly string s_arithmeticBinaryNeverIfUnnecessary = $@" class C {{ void M() {{ //[ // {ServicesVSResources.Prefer_colon} var v = a + b * c; // {ServicesVSResources.Over_colon} var v = a + (b * c); //] }} }} "; #endregion #region relational binary parentheses private readonly string s_relationalBinaryAlwaysForClarity = $@" class C {{ void M() {{ //[ // {ServicesVSResources.Prefer_colon} var v = (a < b) == (c > d); // {ServicesVSResources.Over_colon} var v = a < b == c > d; //] }} }} "; private readonly string s_relationalBinaryNeverIfUnnecessary = $@" class C {{ void M() {{ //[ // {ServicesVSResources.Prefer_colon} var v = a < b == c > d; // {ServicesVSResources.Over_colon} var v = (a < b) == (c > d); //] }} }} "; #endregion #region other binary parentheses private readonly string s_otherBinaryAlwaysForClarity = $@" class C {{ void M() {{ //[ // {ServicesVSResources.Prefer_colon} var v = a || (b && c); // {ServicesVSResources.Over_colon} var v = a || b && c; //] }} }} "; private readonly string s_otherBinaryNeverIfUnnecessary = $@" class C {{ void M() {{ //[ // {ServicesVSResources.Prefer_colon} var v = a || b && c; // {ServicesVSResources.Over_colon} var v = a || (b && c); //] }} }} "; #endregion #region other parentheses private readonly string s_otherParenthesesAlwaysForClarity = $@" class C {{ void M() {{ //[ // {ServicesVSResources.Keep_all_parentheses_in_colon} var v = (a.b).Length; //] }} }} "; private readonly string s_otherParenthesesNeverIfUnnecessary = $@" class C {{ void M() {{ //[ // {ServicesVSResources.Prefer_colon} var v = a.b.Length; // {ServicesVSResources.Over_colon} var v = (a.b).Length; //] }} }} "; #endregion #region unused parameters private static readonly string s_avoidUnusedParametersNonPublicMethods = $@" class C1 {{ //[ // {ServicesVSResources.Prefer_colon} private void M() {{ }} //] }} class C2 {{ //[ // {ServicesVSResources.Over_colon} private void M(int param) {{ }} //] }} "; private static readonly string s_avoidUnusedParametersAllMethods = $@" class C1 {{ //[ // {ServicesVSResources.Prefer_colon} public void M() {{ }} //] }} class C2 {{ //[ // {ServicesVSResources.Over_colon} public void M(int param) {{ }} //] }} "; #endregion #region unused values private static readonly string s_avoidUnusedValueAssignmentUnusedLocal = $@" class C {{ int M() {{ //[ // {ServicesVSResources.Prefer_colon} int unused = Computation(); // {ServicesVSResources.Unused_value_is_explicitly_assigned_to_an_unused_local} int x = 1; //] return x; }} int Computation() => 0; }} class C2 {{ int M() {{ //[ // {ServicesVSResources.Over_colon} int x = Computation(); // {ServicesVSResources.Value_assigned_here_is_never_used} x = 1; //] return x; }} int Computation() => 0; }} "; private static readonly string s_avoidUnusedValueAssignmentDiscard = $@" class C {{ int M() {{ //[ // {ServicesVSResources.Prefer_colon} _ = Computation(); // {ServicesVSResources.Unused_value_is_explicitly_assigned_to_discard} int x = 1; //] return x; }} int Computation() => 0; }} class C2 {{ int M() {{ //[ // {ServicesVSResources.Over_colon} int x = Computation(); // {ServicesVSResources.Value_assigned_here_is_never_used} x = 1; //] return x; }} int Computation() => 0; }} "; private static readonly string s_avoidUnusedValueExpressionStatementUnusedLocal = $@" class C {{ void M() {{ //[ // {ServicesVSResources.Prefer_colon} int unused = Computation(); // {ServicesVSResources.Unused_value_is_explicitly_assigned_to_an_unused_local} //] }} int Computation() => 0; }} class C2 {{ void M() {{ //[ // {ServicesVSResources.Over_colon} Computation(); // {ServicesVSResources.Value_returned_by_invocation_is_implicitly_ignored} //] }} int Computation() => 0; }} "; private static readonly string s_avoidUnusedValueExpressionStatementDiscard = $@" class C {{ void M() {{ //[ // {ServicesVSResources.Prefer_colon} _ = Computation(); // {ServicesVSResources.Unused_value_is_explicitly_assigned_to_discard} //] }} int Computation() => 0; }} class C2 {{ void M() {{ //[ // {ServicesVSResources.Over_colon} Computation(); // {ServicesVSResources.Value_returned_by_invocation_is_implicitly_ignored} //] }} int Computation() => 0; }} "; #endregion #endregion internal StyleViewModel(OptionStore optionStore, IServiceProvider serviceProvider) : base(optionStore, serviceProvider, LanguageNames.CSharp) { var collectionView = (ListCollectionView)CollectionViewSource.GetDefaultView(CodeStyleItems); collectionView.GroupDescriptions.Add(new PropertyGroupDescription(nameof(AbstractCodeStyleOptionViewModel.GroupName))); var qualifyGroupTitle = CSharpVSResources.this_preferences_colon; var predefinedTypesGroupTitle = CSharpVSResources.predefined_type_preferences_colon; var varGroupTitle = CSharpVSResources.var_preferences_colon; var nullCheckingGroupTitle = CSharpVSResources.null_checking_colon; var usingsGroupTitle = CSharpVSResources.using_preferences_colon; var modifierGroupTitle = ServicesVSResources.Modifier_preferences_colon; var codeBlockPreferencesGroupTitle = ServicesVSResources.Code_block_preferences_colon; var expressionPreferencesGroupTitle = ServicesVSResources.Expression_preferences_colon; var patternMatchingPreferencesGroupTitle = CSharpVSResources.Pattern_matching_preferences_colon; var variablePreferencesGroupTitle = ServicesVSResources.Variable_preferences_colon; var parameterPreferencesGroupTitle = ServicesVSResources.Parameter_preferences_colon; var newLinePreferencesGroupTitle = ServicesVSResources.New_line_preferences_experimental_colon; var usingDirectivePlacementPreferences = new List<CodeStylePreference> { new CodeStylePreference(CSharpVSResources.Inside_namespace, isChecked: false), new CodeStylePreference(CSharpVSResources.Outside_namespace, isChecked: false), }; var qualifyMemberAccessPreferences = new List<CodeStylePreference> { new CodeStylePreference(CSharpVSResources.Prefer_this, isChecked: true), new CodeStylePreference(CSharpVSResources.Do_not_prefer_this, isChecked: false), }; var predefinedTypesPreferences = new List<CodeStylePreference> { new CodeStylePreference(ServicesVSResources.Prefer_predefined_type, isChecked: true), new CodeStylePreference(ServicesVSResources.Prefer_framework_type, isChecked: false), }; var typeStylePreferences = new List<CodeStylePreference> { new CodeStylePreference(CSharpVSResources.Prefer_var, isChecked: true), new CodeStylePreference(CSharpVSResources.Prefer_explicit_type, isChecked: false), }; CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.QualifyFieldAccess, CSharpVSResources.Qualify_field_access_with_this, s_fieldDeclarationPreviewTrue, s_fieldDeclarationPreviewFalse, this, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.QualifyPropertyAccess, CSharpVSResources.Qualify_property_access_with_this, s_propertyDeclarationPreviewTrue, s_propertyDeclarationPreviewFalse, this, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.QualifyMethodAccess, CSharpVSResources.Qualify_method_access_with_this, s_methodDeclarationPreviewTrue, s_methodDeclarationPreviewFalse, this, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.QualifyEventAccess, CSharpVSResources.Qualify_event_access_with_this, s_eventDeclarationPreviewTrue, s_eventDeclarationPreviewFalse, this, optionStore, qualifyGroupTitle, qualifyMemberAccessPreferences)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration, ServicesVSResources.For_locals_parameters_and_members, s_intrinsicPreviewDeclarationTrue, s_intrinsicPreviewDeclarationFalse, this, optionStore, predefinedTypesGroupTitle, predefinedTypesPreferences)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess, ServicesVSResources.For_member_access_expressions, s_intrinsicPreviewMemberAccessTrue, s_intrinsicPreviewMemberAccessFalse, this, optionStore, predefinedTypesGroupTitle, predefinedTypesPreferences)); // Use var CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.VarForBuiltInTypes, CSharpVSResources.For_built_in_types, s_varForIntrinsicsPreviewTrue, s_varForIntrinsicsPreviewFalse, this, optionStore, varGroupTitle, typeStylePreferences)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.VarWhenTypeIsApparent, CSharpVSResources.When_variable_type_is_apparent, s_varWhereApparentPreviewTrue, s_varWhereApparentPreviewFalse, this, optionStore, varGroupTitle, typeStylePreferences)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.VarElsewhere, CSharpVSResources.Elsewhere, s_varWherePossiblePreviewTrue, s_varWherePossiblePreviewFalse, this, optionStore, varGroupTitle, typeStylePreferences)); // Code block AddBracesOptions(optionStore, codeBlockPreferencesGroupTitle); AddNamespaceDeclarationsOptions(optionStore, codeBlockPreferencesGroupTitle); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferAutoProperties, ServicesVSResources.analyzer_Prefer_auto_properties, s_preferAutoProperties, s_preferAutoProperties, this, optionStore, codeBlockPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferSimpleUsingStatement, ServicesVSResources.Prefer_simple_using_statement, s_preferSimpleUsingStatement, s_preferSimpleUsingStatement, this, optionStore, codeBlockPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferSystemHashCode, ServicesVSResources.Prefer_System_HashCode_in_GetHashCode, s_preferSystemHashCode, s_preferSystemHashCode, this, optionStore, codeBlockPreferencesGroupTitle)); AddParenthesesOptions(OptionStore); // Expression preferences CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferObjectInitializer, ServicesVSResources.Prefer_object_initializer, s_preferObjectInitializer, s_preferObjectInitializer, this, optionStore, expressionPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferCollectionInitializer, ServicesVSResources.Prefer_collection_initializer, s_preferCollectionInitializer, s_preferCollectionInitializer, this, optionStore, expressionPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferSimplifiedBooleanExpressions, ServicesVSResources.Prefer_simplified_boolean_expressions, s_preferSimplifiedConditionalExpression, s_preferSimplifiedConditionalExpression, this, optionStore, expressionPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferSwitchExpression, CSharpVSResources.Prefer_switch_expression, s_preferSwitchExpression, s_preferSwitchExpression, this, optionStore, expressionPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferConditionalExpressionOverAssignment, ServicesVSResources.Prefer_conditional_expression_over_if_with_assignments, s_preferConditionalExpressionOverIfWithAssignments, s_preferConditionalExpressionOverIfWithAssignments, this, optionStore, expressionPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferConditionalExpressionOverReturn, ServicesVSResources.Prefer_conditional_expression_over_if_with_returns, s_preferConditionalExpressionOverIfWithReturns, s_preferConditionalExpressionOverIfWithReturns, this, optionStore, expressionPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferExplicitTupleNames, ServicesVSResources.Prefer_explicit_tuple_name, s_preferExplicitTupleName, s_preferExplicitTupleName, this, optionStore, expressionPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferSimpleDefaultExpression, ServicesVSResources.Prefer_simple_default_expression, s_preferSimpleDefaultExpression, s_preferSimpleDefaultExpression, this, optionStore, expressionPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferInferredTupleNames, ServicesVSResources.Prefer_inferred_tuple_names, s_preferInferredTupleName, s_preferInferredTupleName, this, optionStore, expressionPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferInferredAnonymousTypeMemberNames, ServicesVSResources.Prefer_inferred_anonymous_type_member_names, s_preferInferredAnonymousTypeMemberName, s_preferInferredAnonymousTypeMemberName, this, optionStore, expressionPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferLocalOverAnonymousFunction, ServicesVSResources.Prefer_local_function_over_anonymous_function, s_preferLocalFunctionOverAnonymousFunction, s_preferLocalFunctionOverAnonymousFunction, this, optionStore, expressionPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferCompoundAssignment, ServicesVSResources.Prefer_compound_assignments, s_preferCompoundAssignments, s_preferCompoundAssignments, this, optionStore, expressionPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.ImplicitObjectCreationWhenTypeIsApparent, CSharpVSResources.Prefer_implicit_object_creation_when_type_is_apparent, s_preferImplicitObjectCreationWhenTypeIsApparent, s_preferImplicitObjectCreationWhenTypeIsApparent, this, optionStore, expressionPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferIndexOperator, ServicesVSResources.Prefer_index_operator, s_preferIndexOperator, s_preferIndexOperator, this, optionStore, expressionPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferRangeOperator, ServicesVSResources.Prefer_range_operator, s_preferRangeOperator, s_preferRangeOperator, this, optionStore, expressionPreferencesGroupTitle)); // Pattern matching CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferPatternMatching, CSharpVSResources.Prefer_pattern_matching, s_preferPatternMatching, s_preferPatternMatching, this, optionStore, patternMatchingPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferPatternMatchingOverIsWithCastCheck, CSharpVSResources.Prefer_pattern_matching_over_is_with_cast_check, s_preferPatternMatchingOverIsWithCastCheck, s_preferPatternMatchingOverIsWithCastCheck, this, optionStore, patternMatchingPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferPatternMatchingOverAsWithNullCheck, CSharpVSResources.Prefer_pattern_matching_over_as_with_null_check, s_preferPatternMatchingOverAsWithNullCheck, s_preferPatternMatchingOverAsWithNullCheck, this, optionStore, patternMatchingPreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferNotPattern, CSharpVSResources.Prefer_pattern_matching_over_mixed_type_check, s_preferPatternMatchingOverMixedTypeCheck, s_preferPatternMatchingOverMixedTypeCheck, this, optionStore, patternMatchingPreferencesGroupTitle)); AddExpressionBodyOptions(optionStore, expressionPreferencesGroupTitle); AddUnusedValueOptions(optionStore, expressionPreferencesGroupTitle); // Variable preferences CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferInlinedVariableDeclaration, ServicesVSResources.Prefer_inlined_variable_declaration, s_preferInlinedVariableDeclaration, s_preferInlinedVariableDeclaration, this, optionStore, variablePreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferDeconstructedVariableDeclaration, ServicesVSResources.Prefer_deconstructed_variable_declaration, s_preferDeconstructedVariableDeclaration, s_preferDeconstructedVariableDeclaration, this, optionStore, variablePreferencesGroupTitle)); // Null preferences. CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferThrowExpression, CSharpVSResources.Prefer_throw_expression, s_preferThrowExpression, s_preferThrowExpression, this, optionStore, nullCheckingGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferConditionalDelegateCall, CSharpVSResources.Prefer_conditional_delegate_call, s_preferConditionalDelegateCall, s_preferConditionalDelegateCall, this, optionStore, nullCheckingGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferCoalesceExpression, ServicesVSResources.Prefer_coalesce_expression, s_preferCoalesceExpression, s_preferCoalesceExpression, this, optionStore, nullCheckingGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferNullPropagation, ServicesVSResources.Prefer_null_propagation, s_preferNullPropagation, s_preferNullPropagation, this, optionStore, nullCheckingGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferIsNullCheckOverReferenceEqualityMethod, CSharpVSResources.Prefer_is_null_for_reference_equality_checks, s_preferIsNullOverReferenceEquals, s_preferIsNullOverReferenceEquals, this, optionStore, nullCheckingGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferNullCheckOverTypeCheck, CSharpVSResources.Prefer_null_check_over_type_check, s_preferNullcheckOverTypeCheck, s_preferNullcheckOverTypeCheck, this, optionStore, nullCheckingGroupTitle)); // Using directive preferences. CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<AddImportPlacement>( CSharpCodeStyleOptions.PreferredUsingDirectivePlacement, CSharpVSResources.Preferred_using_directive_placement, new[] { AddImportPlacement.InsideNamespace, AddImportPlacement.OutsideNamespace }, s_usingDirectivePlacement, this, optionStore, usingsGroupTitle, usingDirectivePlacementPreferences)); // Modifier preferences. CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.PreferReadonly, ServicesVSResources.Prefer_readonly_fields, s_preferReadonly, s_preferReadonly, this, optionStore, modifierGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.PreferStaticLocalFunction, ServicesVSResources.Prefer_static_local_functions, s_preferStaticLocalFunction, s_preferStaticLocalFunction, this, optionStore, modifierGroupTitle)); // Parameter preferences AddParameterOptions(optionStore, parameterPreferencesGroupTitle); // New line preferences. CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.AllowMultipleBlankLines, ServicesVSResources.Allow_multiple_blank_lines, s_allow_multiple_blank_lines_true, s_allow_multiple_blank_lines_false, this, optionStore, newLinePreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.AllowEmbeddedStatementsOnSameLine, CSharpVSResources.Allow_embedded_statements_on_same_line, s_allow_embedded_statements_on_same_line_true, s_allow_embedded_statements_on_same_line_false, this, optionStore, newLinePreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.AllowBlankLinesBetweenConsecutiveBraces, CSharpVSResources.Allow_blank_lines_between_consecutive_braces, s_allow_blank_line_between_consecutive_braces_true, s_allow_blank_line_between_consecutive_braces_false, this, optionStore, newLinePreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CodeStyleOptions2.AllowStatementImmediatelyAfterBlock, ServicesVSResources.Allow_statement_immediately_after_block, s_allow_statement_immediately_after_block_true, s_allow_statement_immediately_after_block_false, this, optionStore, newLinePreferencesGroupTitle)); CodeStyleItems.Add(new BooleanCodeStyleOptionViewModel(CSharpCodeStyleOptions.AllowBlankLineAfterColonInConstructorInitializer, CSharpVSResources.Allow_bank_line_after_colon_in_constructor_initializer, s_allow_bank_line_after_colon_in_constructor_initializer_true, s_allow_bank_line_after_colon_in_constructor_initializer_false, this, optionStore, newLinePreferencesGroupTitle)); } private void AddParenthesesOptions(OptionStore optionStore) { AddParenthesesOption( LanguageNames.CSharp, optionStore, CodeStyleOptions2.ArithmeticBinaryParentheses, CSharpVSResources.In_arithmetic_binary_operators, new[] { s_arithmeticBinaryAlwaysForClarity, s_arithmeticBinaryNeverIfUnnecessary }, defaultAddForClarity: true); AddParenthesesOption( LanguageNames.CSharp, optionStore, CodeStyleOptions2.OtherBinaryParentheses, CSharpVSResources.In_other_binary_operators, new[] { s_otherBinaryAlwaysForClarity, s_otherBinaryNeverIfUnnecessary }, defaultAddForClarity: true); AddParenthesesOption( LanguageNames.CSharp, optionStore, CodeStyleOptions2.RelationalBinaryParentheses, CSharpVSResources.In_relational_binary_operators, new[] { s_relationalBinaryAlwaysForClarity, s_relationalBinaryNeverIfUnnecessary }, defaultAddForClarity: true); AddParenthesesOption( LanguageNames.CSharp, optionStore, CodeStyleOptions2.OtherParentheses, ServicesVSResources.In_other_operators, new[] { s_otherParenthesesAlwaysForClarity, s_otherParenthesesNeverIfUnnecessary }, defaultAddForClarity: false); } private void AddBracesOptions(OptionStore optionStore, string bracesPreferenceGroupTitle) { var bracesPreferences = new List<CodeStylePreference> { new CodeStylePreference(ServicesVSResources.Yes, isChecked: false), new CodeStylePreference(ServicesVSResources.No, isChecked: false), new CodeStylePreference(CSharpVSResources.When_on_multiple_lines, isChecked: false), }; var enumValues = new[] { PreferBracesPreference.Always, PreferBracesPreference.None, PreferBracesPreference.WhenMultiline }; CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<PreferBracesPreference>( CSharpCodeStyleOptions.PreferBraces, ServicesVSResources.Prefer_braces, enumValues, new[] { s_preferBraces, s_doNotPreferBraces, s_preferBracesWhenMultiline }, this, optionStore, bracesPreferenceGroupTitle, bracesPreferences)); } private void AddNamespaceDeclarationsOptions(OptionStore optionStore, string group) { var preferences = new List<CodeStylePreference> { new CodeStylePreference(CSharpVSResources.Block_scoped, isChecked: false), new CodeStylePreference(CSharpVSResources.File_scoped, isChecked: false), }; var enumValues = new[] { NamespaceDeclarationPreference.BlockScoped, NamespaceDeclarationPreference.FileScoped }; CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<NamespaceDeclarationPreference>( CSharpCodeStyleOptions.NamespaceDeclarations, ServicesVSResources.Namespace_declarations, enumValues, new[] { s_preferBlockNamespace, s_preferFileScopedNamespace }, this, optionStore, group, preferences)); } private void AddExpressionBodyOptions(OptionStore optionStore, string expressionPreferencesGroupTitle) { var expressionBodyPreferences = new List<CodeStylePreference> { new CodeStylePreference(CSharpVSResources.Never, isChecked: false), new CodeStylePreference(CSharpVSResources.When_possible, isChecked: false), new CodeStylePreference(CSharpVSResources.When_on_single_line, isChecked: false), }; var enumValues = new[] { ExpressionBodyPreference.Never, ExpressionBodyPreference.WhenPossible, ExpressionBodyPreference.WhenOnSingleLine }; CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<ExpressionBodyPreference>( CSharpCodeStyleOptions.PreferExpressionBodiedMethods, ServicesVSResources.Use_expression_body_for_methods, enumValues, new[] { s_preferBlockBodyForMethods, s_preferExpressionBodyForMethods, s_preferExpressionBodyForMethods }, this, optionStore, expressionPreferencesGroupTitle, expressionBodyPreferences)); CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<ExpressionBodyPreference>( CSharpCodeStyleOptions.PreferExpressionBodiedConstructors, ServicesVSResources.Use_expression_body_for_constructors, enumValues, new[] { s_preferBlockBodyForConstructors, s_preferExpressionBodyForConstructors, s_preferExpressionBodyForConstructors }, this, optionStore, expressionPreferencesGroupTitle, expressionBodyPreferences)); CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<ExpressionBodyPreference>( CSharpCodeStyleOptions.PreferExpressionBodiedOperators, ServicesVSResources.Use_expression_body_for_operators, enumValues, new[] { s_preferBlockBodyForOperators, s_preferExpressionBodyForOperators, s_preferExpressionBodyForOperators }, this, optionStore, expressionPreferencesGroupTitle, expressionBodyPreferences)); CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<ExpressionBodyPreference>( CSharpCodeStyleOptions.PreferExpressionBodiedProperties, ServicesVSResources.Use_expression_body_for_properties, enumValues, new[] { s_preferBlockBodyForProperties, s_preferExpressionBodyForProperties, s_preferExpressionBodyForProperties }, this, optionStore, expressionPreferencesGroupTitle, expressionBodyPreferences)); CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<ExpressionBodyPreference>( CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, ServicesVSResources.Use_expression_body_for_indexers, enumValues, new[] { s_preferBlockBodyForIndexers, s_preferExpressionBodyForIndexers, s_preferExpressionBodyForIndexers }, this, optionStore, expressionPreferencesGroupTitle, expressionBodyPreferences)); CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<ExpressionBodyPreference>( CSharpCodeStyleOptions.PreferExpressionBodiedAccessors, ServicesVSResources.Use_expression_body_for_accessors, enumValues, new[] { s_preferBlockBodyForAccessors, s_preferExpressionBodyForAccessors, s_preferExpressionBodyForAccessors }, this, optionStore, expressionPreferencesGroupTitle, expressionBodyPreferences)); CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<ExpressionBodyPreference>( CSharpCodeStyleOptions.PreferExpressionBodiedLambdas, ServicesVSResources.Use_expression_body_for_lambdas, enumValues, new[] { s_preferBlockBodyForLambdas, s_preferExpressionBodyForLambdas, s_preferExpressionBodyForLambdas }, this, optionStore, expressionPreferencesGroupTitle, expressionBodyPreferences)); CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<ExpressionBodyPreference>( CSharpCodeStyleOptions.PreferExpressionBodiedLocalFunctions, ServicesVSResources.Use_expression_body_for_local_functions, enumValues, new[] { s_preferBlockBodyForLocalFunctions, s_preferExpressionBodyForLocalFunctions, s_preferExpressionBodyForLocalFunctions }, this, optionStore, expressionPreferencesGroupTitle, expressionBodyPreferences)); } private void AddUnusedValueOptions(OptionStore optionStore, string expressionPreferencesGroupTitle) { var unusedValuePreferences = new List<CodeStylePreference> { new CodeStylePreference(CSharpVSResources.Unused_local, isChecked: false), new CodeStylePreference(CSharpVSResources.Discard, isChecked: true), }; var enumValues = new[] { UnusedValuePreference.UnusedLocalVariable, UnusedValuePreference.DiscardVariable }; CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<UnusedValuePreference>( CSharpCodeStyleOptions.UnusedValueAssignment, ServicesVSResources.Avoid_unused_value_assignments, enumValues, new[] { s_avoidUnusedValueAssignmentUnusedLocal, s_avoidUnusedValueAssignmentDiscard }, this, optionStore, expressionPreferencesGroupTitle, unusedValuePreferences)); CodeStyleItems.Add(new EnumCodeStyleOptionViewModel<UnusedValuePreference>( CSharpCodeStyleOptions.UnusedValueExpressionStatement, ServicesVSResources.Avoid_expression_statements_that_implicitly_ignore_value, enumValues, new[] { s_avoidUnusedValueExpressionStatementUnusedLocal, s_avoidUnusedValueExpressionStatementDiscard }, this, optionStore, expressionPreferencesGroupTitle, unusedValuePreferences)); } private void AddParameterOptions(OptionStore optionStore, string parameterPreferencesGroupTitle) { var examples = new[] { s_avoidUnusedParametersNonPublicMethods, s_avoidUnusedParametersAllMethods }; AddUnusedParameterOption(LanguageNames.CSharp, optionStore, parameterPreferencesGroupTitle, examples); } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/VisualStudio/Core/Def/Implementation/Library/ObjectBrowser/Lists/SymbolListItem`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. #nullable disable using Microsoft.CodeAnalysis; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser.Lists { internal abstract class SymbolListItem<TSymbol> : SymbolListItem where TSymbol : ISymbol { protected SymbolListItem(ProjectId projectId, TSymbol symbol, string displayText, string fullNameText, string searchText, bool isHidden) : base(projectId, symbol, displayText, fullNameText, searchText, isHidden) { } public TSymbol ResolveTypedSymbol(Compilation compilation) => (TSymbol)ResolveSymbol(compilation); } }
// Licensed to the .NET Foundation under one or more 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; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.ObjectBrowser.Lists { internal abstract class SymbolListItem<TSymbol> : SymbolListItem where TSymbol : ISymbol { protected SymbolListItem(ProjectId projectId, TSymbol symbol, string displayText, string fullNameText, string searchText, bool isHidden) : base(projectId, symbol, displayText, fullNameText, searchText, isHidden) { } public TSymbol ResolveTypedSymbol(Compilation compilation) => (TSymbol)ResolveSymbol(compilation); } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Portable/Generated/CSharpSyntaxGenerator/CSharpSyntaxGenerator.SourceGenerator/Syntax.xml.Syntax.Generated.cs
// <auto-generated /> #nullable enable using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Syntax.InternalSyntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Syntax { /// <summary>Provides the base class from which the classes that represent name syntax nodes are derived. This is an abstract class.</summary> public abstract partial class NameSyntax : TypeSyntax { internal NameSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } } /// <summary>Provides the base class from which the classes that represent simple name syntax nodes are derived. This is an abstract class.</summary> public abstract partial class SimpleNameSyntax : NameSyntax { internal SimpleNameSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the identifier of the simple name.</summary> public abstract SyntaxToken Identifier { get; } public SimpleNameSyntax WithIdentifier(SyntaxToken identifier) => WithIdentifierCore(identifier); internal abstract SimpleNameSyntax WithIdentifierCore(SyntaxToken identifier); } /// <summary>Class which represents the syntax node for identifier name.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.IdentifierName"/></description></item> /// </list> /// </remarks> public sealed partial class IdentifierNameSyntax : SimpleNameSyntax { internal IdentifierNameSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the keyword for the kind of the identifier name.</summary> public override SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.IdentifierNameSyntax)this.Green).identifier, Position, 0); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitIdentifierName(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitIdentifierName(this); public IdentifierNameSyntax Update(SyntaxToken identifier) { if (identifier != this.Identifier) { var newNode = SyntaxFactory.IdentifierName(identifier); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override SimpleNameSyntax WithIdentifierCore(SyntaxToken identifier) => WithIdentifier(identifier); public new IdentifierNameSyntax WithIdentifier(SyntaxToken identifier) => Update(identifier); } /// <summary>Class which represents the syntax node for qualified name.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.QualifiedName"/></description></item> /// </list> /// </remarks> public sealed partial class QualifiedNameSyntax : NameSyntax { private NameSyntax? left; private SimpleNameSyntax? right; internal QualifiedNameSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>NameSyntax node representing the name on the left side of the dot token of the qualified name.</summary> public NameSyntax Left => GetRedAtZero(ref this.left)!; /// <summary>SyntaxToken representing the dot.</summary> public SyntaxToken DotToken => new SyntaxToken(this, ((Syntax.InternalSyntax.QualifiedNameSyntax)this.Green).dotToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>SimpleNameSyntax node representing the name on the right side of the dot token of the qualified name.</summary> public SimpleNameSyntax Right => GetRed(ref this.right, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.left)!, 2 => GetRed(ref this.right, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.left, 2 => this.right, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitQualifiedName(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitQualifiedName(this); public QualifiedNameSyntax Update(NameSyntax left, SyntaxToken dotToken, SimpleNameSyntax right) { if (left != this.Left || dotToken != this.DotToken || right != this.Right) { var newNode = SyntaxFactory.QualifiedName(left, dotToken, right); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public QualifiedNameSyntax WithLeft(NameSyntax left) => Update(left, this.DotToken, this.Right); public QualifiedNameSyntax WithDotToken(SyntaxToken dotToken) => Update(this.Left, dotToken, this.Right); public QualifiedNameSyntax WithRight(SimpleNameSyntax right) => Update(this.Left, this.DotToken, right); } /// <summary>Class which represents the syntax node for generic name.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.GenericName"/></description></item> /// </list> /// </remarks> public sealed partial class GenericNameSyntax : SimpleNameSyntax { private TypeArgumentListSyntax? typeArgumentList; internal GenericNameSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the name of the identifier of the generic name.</summary> public override SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.GenericNameSyntax)this.Green).identifier, Position, 0); /// <summary>TypeArgumentListSyntax node representing the list of type arguments of the generic name.</summary> public TypeArgumentListSyntax TypeArgumentList => GetRed(ref this.typeArgumentList, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.typeArgumentList, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.typeArgumentList : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitGenericName(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitGenericName(this); public GenericNameSyntax Update(SyntaxToken identifier, TypeArgumentListSyntax typeArgumentList) { if (identifier != this.Identifier || typeArgumentList != this.TypeArgumentList) { var newNode = SyntaxFactory.GenericName(identifier, typeArgumentList); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override SimpleNameSyntax WithIdentifierCore(SyntaxToken identifier) => WithIdentifier(identifier); public new GenericNameSyntax WithIdentifier(SyntaxToken identifier) => Update(identifier, this.TypeArgumentList); public GenericNameSyntax WithTypeArgumentList(TypeArgumentListSyntax typeArgumentList) => Update(this.Identifier, typeArgumentList); public GenericNameSyntax AddTypeArgumentListArguments(params TypeSyntax[] items) => WithTypeArgumentList(this.TypeArgumentList.WithArguments(this.TypeArgumentList.Arguments.AddRange(items))); } /// <summary>Class which represents the syntax node for type argument list.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.TypeArgumentList"/></description></item> /// </list> /// </remarks> public sealed partial class TypeArgumentListSyntax : CSharpSyntaxNode { private SyntaxNode? arguments; internal TypeArgumentListSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing less than.</summary> public SyntaxToken LessThanToken => new SyntaxToken(this, ((Syntax.InternalSyntax.TypeArgumentListSyntax)this.Green).lessThanToken, Position, 0); /// <summary>SeparatedSyntaxList of TypeSyntax node representing the type arguments.</summary> public SeparatedSyntaxList<TypeSyntax> Arguments { get { var red = GetRed(ref this.arguments, 1); return red != null ? new SeparatedSyntaxList<TypeSyntax>(red, GetChildIndex(1)) : default; } } /// <summary>SyntaxToken representing greater than.</summary> public SyntaxToken GreaterThanToken => new SyntaxToken(this, ((Syntax.InternalSyntax.TypeArgumentListSyntax)this.Green).greaterThanToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.arguments, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.arguments : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitTypeArgumentList(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitTypeArgumentList(this); public TypeArgumentListSyntax Update(SyntaxToken lessThanToken, SeparatedSyntaxList<TypeSyntax> arguments, SyntaxToken greaterThanToken) { if (lessThanToken != this.LessThanToken || arguments != this.Arguments || greaterThanToken != this.GreaterThanToken) { var newNode = SyntaxFactory.TypeArgumentList(lessThanToken, arguments, greaterThanToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public TypeArgumentListSyntax WithLessThanToken(SyntaxToken lessThanToken) => Update(lessThanToken, this.Arguments, this.GreaterThanToken); public TypeArgumentListSyntax WithArguments(SeparatedSyntaxList<TypeSyntax> arguments) => Update(this.LessThanToken, arguments, this.GreaterThanToken); public TypeArgumentListSyntax WithGreaterThanToken(SyntaxToken greaterThanToken) => Update(this.LessThanToken, this.Arguments, greaterThanToken); public TypeArgumentListSyntax AddArguments(params TypeSyntax[] items) => WithArguments(this.Arguments.AddRange(items)); } /// <summary>Class which represents the syntax node for alias qualified name.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.AliasQualifiedName"/></description></item> /// </list> /// </remarks> public sealed partial class AliasQualifiedNameSyntax : NameSyntax { private IdentifierNameSyntax? alias; private SimpleNameSyntax? name; internal AliasQualifiedNameSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>IdentifierNameSyntax node representing the name of the alias</summary> public IdentifierNameSyntax Alias => GetRedAtZero(ref this.alias)!; /// <summary>SyntaxToken representing colon colon.</summary> public SyntaxToken ColonColonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.AliasQualifiedNameSyntax)this.Green).colonColonToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>SimpleNameSyntax node representing the name that is being alias qualified.</summary> public SimpleNameSyntax Name => GetRed(ref this.name, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.alias)!, 2 => GetRed(ref this.name, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.alias, 2 => this.name, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitAliasQualifiedName(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitAliasQualifiedName(this); public AliasQualifiedNameSyntax Update(IdentifierNameSyntax alias, SyntaxToken colonColonToken, SimpleNameSyntax name) { if (alias != this.Alias || colonColonToken != this.ColonColonToken || name != this.Name) { var newNode = SyntaxFactory.AliasQualifiedName(alias, colonColonToken, name); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public AliasQualifiedNameSyntax WithAlias(IdentifierNameSyntax alias) => Update(alias, this.ColonColonToken, this.Name); public AliasQualifiedNameSyntax WithColonColonToken(SyntaxToken colonColonToken) => Update(this.Alias, colonColonToken, this.Name); public AliasQualifiedNameSyntax WithName(SimpleNameSyntax name) => Update(this.Alias, this.ColonColonToken, name); } /// <summary>Provides the base class from which the classes that represent type syntax nodes are derived. This is an abstract class.</summary> public abstract partial class TypeSyntax : ExpressionSyntax { internal TypeSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } } /// <summary>Class which represents the syntax node for predefined types.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.PredefinedType"/></description></item> /// </list> /// </remarks> public sealed partial class PredefinedTypeSyntax : TypeSyntax { internal PredefinedTypeSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken which represents the keyword corresponding to the predefined type.</summary> public SyntaxToken Keyword => new SyntaxToken(this, ((Syntax.InternalSyntax.PredefinedTypeSyntax)this.Green).keyword, Position, 0); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitPredefinedType(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitPredefinedType(this); public PredefinedTypeSyntax Update(SyntaxToken keyword) { if (keyword != this.Keyword) { var newNode = SyntaxFactory.PredefinedType(keyword); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public PredefinedTypeSyntax WithKeyword(SyntaxToken keyword) => Update(keyword); } /// <summary>Class which represents the syntax node for the array type.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ArrayType"/></description></item> /// </list> /// </remarks> public sealed partial class ArrayTypeSyntax : TypeSyntax { private TypeSyntax? elementType; private SyntaxNode? rankSpecifiers; internal ArrayTypeSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>TypeSyntax node representing the type of the element of the array.</summary> public TypeSyntax ElementType => GetRedAtZero(ref this.elementType)!; /// <summary>SyntaxList of ArrayRankSpecifierSyntax nodes representing the list of rank specifiers for the array.</summary> public SyntaxList<ArrayRankSpecifierSyntax> RankSpecifiers => new SyntaxList<ArrayRankSpecifierSyntax>(GetRed(ref this.rankSpecifiers, 1)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.elementType)!, 1 => GetRed(ref this.rankSpecifiers, 1)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.elementType, 1 => this.rankSpecifiers, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitArrayType(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitArrayType(this); public ArrayTypeSyntax Update(TypeSyntax elementType, SyntaxList<ArrayRankSpecifierSyntax> rankSpecifiers) { if (elementType != this.ElementType || rankSpecifiers != this.RankSpecifiers) { var newNode = SyntaxFactory.ArrayType(elementType, rankSpecifiers); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ArrayTypeSyntax WithElementType(TypeSyntax elementType) => Update(elementType, this.RankSpecifiers); public ArrayTypeSyntax WithRankSpecifiers(SyntaxList<ArrayRankSpecifierSyntax> rankSpecifiers) => Update(this.ElementType, rankSpecifiers); public ArrayTypeSyntax AddRankSpecifiers(params ArrayRankSpecifierSyntax[] items) => WithRankSpecifiers(this.RankSpecifiers.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ArrayRankSpecifier"/></description></item> /// </list> /// </remarks> public sealed partial class ArrayRankSpecifierSyntax : CSharpSyntaxNode { private SyntaxNode? sizes; internal ArrayRankSpecifierSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken OpenBracketToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ArrayRankSpecifierSyntax)this.Green).openBracketToken, Position, 0); public SeparatedSyntaxList<ExpressionSyntax> Sizes { get { var red = GetRed(ref this.sizes, 1); return red != null ? new SeparatedSyntaxList<ExpressionSyntax>(red, GetChildIndex(1)) : default; } } public SyntaxToken CloseBracketToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ArrayRankSpecifierSyntax)this.Green).closeBracketToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.sizes, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.sizes : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitArrayRankSpecifier(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitArrayRankSpecifier(this); public ArrayRankSpecifierSyntax Update(SyntaxToken openBracketToken, SeparatedSyntaxList<ExpressionSyntax> sizes, SyntaxToken closeBracketToken) { if (openBracketToken != this.OpenBracketToken || sizes != this.Sizes || closeBracketToken != this.CloseBracketToken) { var newNode = SyntaxFactory.ArrayRankSpecifier(openBracketToken, sizes, closeBracketToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ArrayRankSpecifierSyntax WithOpenBracketToken(SyntaxToken openBracketToken) => Update(openBracketToken, this.Sizes, this.CloseBracketToken); public ArrayRankSpecifierSyntax WithSizes(SeparatedSyntaxList<ExpressionSyntax> sizes) => Update(this.OpenBracketToken, sizes, this.CloseBracketToken); public ArrayRankSpecifierSyntax WithCloseBracketToken(SyntaxToken closeBracketToken) => Update(this.OpenBracketToken, this.Sizes, closeBracketToken); public ArrayRankSpecifierSyntax AddSizes(params ExpressionSyntax[] items) => WithSizes(this.Sizes.AddRange(items)); } /// <summary>Class which represents the syntax node for pointer type.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.PointerType"/></description></item> /// </list> /// </remarks> public sealed partial class PointerTypeSyntax : TypeSyntax { private TypeSyntax? elementType; internal PointerTypeSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>TypeSyntax node that represents the element type of the pointer.</summary> public TypeSyntax ElementType => GetRedAtZero(ref this.elementType)!; /// <summary>SyntaxToken representing the asterisk.</summary> public SyntaxToken AsteriskToken => new SyntaxToken(this, ((Syntax.InternalSyntax.PointerTypeSyntax)this.Green).asteriskToken, GetChildPosition(1), GetChildIndex(1)); internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.elementType)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.elementType : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitPointerType(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitPointerType(this); public PointerTypeSyntax Update(TypeSyntax elementType, SyntaxToken asteriskToken) { if (elementType != this.ElementType || asteriskToken != this.AsteriskToken) { var newNode = SyntaxFactory.PointerType(elementType, asteriskToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public PointerTypeSyntax WithElementType(TypeSyntax elementType) => Update(elementType, this.AsteriskToken); public PointerTypeSyntax WithAsteriskToken(SyntaxToken asteriskToken) => Update(this.ElementType, asteriskToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.FunctionPointerType"/></description></item> /// </list> /// </remarks> public sealed partial class FunctionPointerTypeSyntax : TypeSyntax { private FunctionPointerCallingConventionSyntax? callingConvention; private FunctionPointerParameterListSyntax? parameterList; internal FunctionPointerTypeSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the delegate keyword.</summary> public SyntaxToken DelegateKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.FunctionPointerTypeSyntax)this.Green).delegateKeyword, Position, 0); /// <summary>SyntaxToken representing the asterisk.</summary> public SyntaxToken AsteriskToken => new SyntaxToken(this, ((Syntax.InternalSyntax.FunctionPointerTypeSyntax)this.Green).asteriskToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>Node representing the optional calling convention.</summary> public FunctionPointerCallingConventionSyntax? CallingConvention => GetRed(ref this.callingConvention, 2); /// <summary>List of the parameter types and return type of the function pointer.</summary> public FunctionPointerParameterListSyntax ParameterList => GetRed(ref this.parameterList, 3)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 2 => GetRed(ref this.callingConvention, 2), 3 => GetRed(ref this.parameterList, 3)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 2 => this.callingConvention, 3 => this.parameterList, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitFunctionPointerType(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitFunctionPointerType(this); public FunctionPointerTypeSyntax Update(SyntaxToken delegateKeyword, SyntaxToken asteriskToken, FunctionPointerCallingConventionSyntax? callingConvention, FunctionPointerParameterListSyntax parameterList) { if (delegateKeyword != this.DelegateKeyword || asteriskToken != this.AsteriskToken || callingConvention != this.CallingConvention || parameterList != this.ParameterList) { var newNode = SyntaxFactory.FunctionPointerType(delegateKeyword, asteriskToken, callingConvention, parameterList); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public FunctionPointerTypeSyntax WithDelegateKeyword(SyntaxToken delegateKeyword) => Update(delegateKeyword, this.AsteriskToken, this.CallingConvention, this.ParameterList); public FunctionPointerTypeSyntax WithAsteriskToken(SyntaxToken asteriskToken) => Update(this.DelegateKeyword, asteriskToken, this.CallingConvention, this.ParameterList); public FunctionPointerTypeSyntax WithCallingConvention(FunctionPointerCallingConventionSyntax? callingConvention) => Update(this.DelegateKeyword, this.AsteriskToken, callingConvention, this.ParameterList); public FunctionPointerTypeSyntax WithParameterList(FunctionPointerParameterListSyntax parameterList) => Update(this.DelegateKeyword, this.AsteriskToken, this.CallingConvention, parameterList); public FunctionPointerTypeSyntax AddParameterListParameters(params FunctionPointerParameterSyntax[] items) => WithParameterList(this.ParameterList.WithParameters(this.ParameterList.Parameters.AddRange(items))); } /// <summary>Function pointer parameter list syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.FunctionPointerParameterList"/></description></item> /// </list> /// </remarks> public sealed partial class FunctionPointerParameterListSyntax : CSharpSyntaxNode { private SyntaxNode? parameters; internal FunctionPointerParameterListSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the less than token.</summary> public SyntaxToken LessThanToken => new SyntaxToken(this, ((Syntax.InternalSyntax.FunctionPointerParameterListSyntax)this.Green).lessThanToken, Position, 0); /// <summary>SeparatedSyntaxList of ParameterSyntaxes representing the list of parameters and return type.</summary> public SeparatedSyntaxList<FunctionPointerParameterSyntax> Parameters { get { var red = GetRed(ref this.parameters, 1); return red != null ? new SeparatedSyntaxList<FunctionPointerParameterSyntax>(red, GetChildIndex(1)) : default; } } /// <summary>SyntaxToken representing the greater than token.</summary> public SyntaxToken GreaterThanToken => new SyntaxToken(this, ((Syntax.InternalSyntax.FunctionPointerParameterListSyntax)this.Green).greaterThanToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.parameters, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.parameters : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitFunctionPointerParameterList(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitFunctionPointerParameterList(this); public FunctionPointerParameterListSyntax Update(SyntaxToken lessThanToken, SeparatedSyntaxList<FunctionPointerParameterSyntax> parameters, SyntaxToken greaterThanToken) { if (lessThanToken != this.LessThanToken || parameters != this.Parameters || greaterThanToken != this.GreaterThanToken) { var newNode = SyntaxFactory.FunctionPointerParameterList(lessThanToken, parameters, greaterThanToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public FunctionPointerParameterListSyntax WithLessThanToken(SyntaxToken lessThanToken) => Update(lessThanToken, this.Parameters, this.GreaterThanToken); public FunctionPointerParameterListSyntax WithParameters(SeparatedSyntaxList<FunctionPointerParameterSyntax> parameters) => Update(this.LessThanToken, parameters, this.GreaterThanToken); public FunctionPointerParameterListSyntax WithGreaterThanToken(SyntaxToken greaterThanToken) => Update(this.LessThanToken, this.Parameters, greaterThanToken); public FunctionPointerParameterListSyntax AddParameters(params FunctionPointerParameterSyntax[] items) => WithParameters(this.Parameters.AddRange(items)); } /// <summary>Function pointer calling convention syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.FunctionPointerCallingConvention"/></description></item> /// </list> /// </remarks> public sealed partial class FunctionPointerCallingConventionSyntax : CSharpSyntaxNode { private FunctionPointerUnmanagedCallingConventionListSyntax? unmanagedCallingConventionList; internal FunctionPointerCallingConventionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing whether the calling convention is managed or unmanaged.</summary> public SyntaxToken ManagedOrUnmanagedKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.FunctionPointerCallingConventionSyntax)this.Green).managedOrUnmanagedKeyword, Position, 0); /// <summary>Optional list of identifiers that will contribute to an unmanaged calling convention.</summary> public FunctionPointerUnmanagedCallingConventionListSyntax? UnmanagedCallingConventionList => GetRed(ref this.unmanagedCallingConventionList, 1); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.unmanagedCallingConventionList, 1) : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.unmanagedCallingConventionList : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitFunctionPointerCallingConvention(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitFunctionPointerCallingConvention(this); public FunctionPointerCallingConventionSyntax Update(SyntaxToken managedOrUnmanagedKeyword, FunctionPointerUnmanagedCallingConventionListSyntax? unmanagedCallingConventionList) { if (managedOrUnmanagedKeyword != this.ManagedOrUnmanagedKeyword || unmanagedCallingConventionList != this.UnmanagedCallingConventionList) { var newNode = SyntaxFactory.FunctionPointerCallingConvention(managedOrUnmanagedKeyword, unmanagedCallingConventionList); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public FunctionPointerCallingConventionSyntax WithManagedOrUnmanagedKeyword(SyntaxToken managedOrUnmanagedKeyword) => Update(managedOrUnmanagedKeyword, this.UnmanagedCallingConventionList); public FunctionPointerCallingConventionSyntax WithUnmanagedCallingConventionList(FunctionPointerUnmanagedCallingConventionListSyntax? unmanagedCallingConventionList) => Update(this.ManagedOrUnmanagedKeyword, unmanagedCallingConventionList); public FunctionPointerCallingConventionSyntax AddUnmanagedCallingConventionListCallingConventions(params FunctionPointerUnmanagedCallingConventionSyntax[] items) { var unmanagedCallingConventionList = this.UnmanagedCallingConventionList ?? SyntaxFactory.FunctionPointerUnmanagedCallingConventionList(); return WithUnmanagedCallingConventionList(unmanagedCallingConventionList.WithCallingConventions(unmanagedCallingConventionList.CallingConventions.AddRange(items))); } } /// <summary>Function pointer calling convention syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.FunctionPointerUnmanagedCallingConventionList"/></description></item> /// </list> /// </remarks> public sealed partial class FunctionPointerUnmanagedCallingConventionListSyntax : CSharpSyntaxNode { private SyntaxNode? callingConventions; internal FunctionPointerUnmanagedCallingConventionListSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing open bracket.</summary> public SyntaxToken OpenBracketToken => new SyntaxToken(this, ((Syntax.InternalSyntax.FunctionPointerUnmanagedCallingConventionListSyntax)this.Green).openBracketToken, Position, 0); /// <summary>SeparatedSyntaxList of calling convention identifiers.</summary> public SeparatedSyntaxList<FunctionPointerUnmanagedCallingConventionSyntax> CallingConventions { get { var red = GetRed(ref this.callingConventions, 1); return red != null ? new SeparatedSyntaxList<FunctionPointerUnmanagedCallingConventionSyntax>(red, GetChildIndex(1)) : default; } } /// <summary>SyntaxToken representing close bracket.</summary> public SyntaxToken CloseBracketToken => new SyntaxToken(this, ((Syntax.InternalSyntax.FunctionPointerUnmanagedCallingConventionListSyntax)this.Green).closeBracketToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.callingConventions, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.callingConventions : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitFunctionPointerUnmanagedCallingConventionList(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitFunctionPointerUnmanagedCallingConventionList(this); public FunctionPointerUnmanagedCallingConventionListSyntax Update(SyntaxToken openBracketToken, SeparatedSyntaxList<FunctionPointerUnmanagedCallingConventionSyntax> callingConventions, SyntaxToken closeBracketToken) { if (openBracketToken != this.OpenBracketToken || callingConventions != this.CallingConventions || closeBracketToken != this.CloseBracketToken) { var newNode = SyntaxFactory.FunctionPointerUnmanagedCallingConventionList(openBracketToken, callingConventions, closeBracketToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public FunctionPointerUnmanagedCallingConventionListSyntax WithOpenBracketToken(SyntaxToken openBracketToken) => Update(openBracketToken, this.CallingConventions, this.CloseBracketToken); public FunctionPointerUnmanagedCallingConventionListSyntax WithCallingConventions(SeparatedSyntaxList<FunctionPointerUnmanagedCallingConventionSyntax> callingConventions) => Update(this.OpenBracketToken, callingConventions, this.CloseBracketToken); public FunctionPointerUnmanagedCallingConventionListSyntax WithCloseBracketToken(SyntaxToken closeBracketToken) => Update(this.OpenBracketToken, this.CallingConventions, closeBracketToken); public FunctionPointerUnmanagedCallingConventionListSyntax AddCallingConventions(params FunctionPointerUnmanagedCallingConventionSyntax[] items) => WithCallingConventions(this.CallingConventions.AddRange(items)); } /// <summary>Individual function pointer unmanaged calling convention.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.FunctionPointerUnmanagedCallingConvention"/></description></item> /// </list> /// </remarks> public sealed partial class FunctionPointerUnmanagedCallingConventionSyntax : CSharpSyntaxNode { internal FunctionPointerUnmanagedCallingConventionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the calling convention identifier.</summary> public SyntaxToken Name => new SyntaxToken(this, ((Syntax.InternalSyntax.FunctionPointerUnmanagedCallingConventionSyntax)this.Green).name, Position, 0); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitFunctionPointerUnmanagedCallingConvention(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitFunctionPointerUnmanagedCallingConvention(this); public FunctionPointerUnmanagedCallingConventionSyntax Update(SyntaxToken name) { if (name != this.Name) { var newNode = SyntaxFactory.FunctionPointerUnmanagedCallingConvention(name); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public FunctionPointerUnmanagedCallingConventionSyntax WithName(SyntaxToken name) => Update(name); } /// <summary>Class which represents the syntax node for a nullable type.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.NullableType"/></description></item> /// </list> /// </remarks> public sealed partial class NullableTypeSyntax : TypeSyntax { private TypeSyntax? elementType; internal NullableTypeSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>TypeSyntax node representing the type of the element.</summary> public TypeSyntax ElementType => GetRedAtZero(ref this.elementType)!; /// <summary>SyntaxToken representing the question mark.</summary> public SyntaxToken QuestionToken => new SyntaxToken(this, ((Syntax.InternalSyntax.NullableTypeSyntax)this.Green).questionToken, GetChildPosition(1), GetChildIndex(1)); internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.elementType)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.elementType : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitNullableType(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitNullableType(this); public NullableTypeSyntax Update(TypeSyntax elementType, SyntaxToken questionToken) { if (elementType != this.ElementType || questionToken != this.QuestionToken) { var newNode = SyntaxFactory.NullableType(elementType, questionToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public NullableTypeSyntax WithElementType(TypeSyntax elementType) => Update(elementType, this.QuestionToken); public NullableTypeSyntax WithQuestionToken(SyntaxToken questionToken) => Update(this.ElementType, questionToken); } /// <summary>Class which represents the syntax node for tuple type.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.TupleType"/></description></item> /// </list> /// </remarks> public sealed partial class TupleTypeSyntax : TypeSyntax { private SyntaxNode? elements; internal TupleTypeSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the open parenthesis.</summary> public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.TupleTypeSyntax)this.Green).openParenToken, Position, 0); public SeparatedSyntaxList<TupleElementSyntax> Elements { get { var red = GetRed(ref this.elements, 1); return red != null ? new SeparatedSyntaxList<TupleElementSyntax>(red, GetChildIndex(1)) : default; } } /// <summary>SyntaxToken representing the close parenthesis.</summary> public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.TupleTypeSyntax)this.Green).closeParenToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.elements, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.elements : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitTupleType(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitTupleType(this); public TupleTypeSyntax Update(SyntaxToken openParenToken, SeparatedSyntaxList<TupleElementSyntax> elements, SyntaxToken closeParenToken) { if (openParenToken != this.OpenParenToken || elements != this.Elements || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.TupleType(openParenToken, elements, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public TupleTypeSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(openParenToken, this.Elements, this.CloseParenToken); public TupleTypeSyntax WithElements(SeparatedSyntaxList<TupleElementSyntax> elements) => Update(this.OpenParenToken, elements, this.CloseParenToken); public TupleTypeSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.OpenParenToken, this.Elements, closeParenToken); public TupleTypeSyntax AddElements(params TupleElementSyntax[] items) => WithElements(this.Elements.AddRange(items)); } /// <summary>Tuple type element.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.TupleElement"/></description></item> /// </list> /// </remarks> public sealed partial class TupleElementSyntax : CSharpSyntaxNode { private TypeSyntax? type; internal TupleElementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the type of the tuple element.</summary> public TypeSyntax Type => GetRedAtZero(ref this.type)!; /// <summary>Gets the name of the tuple element.</summary> public SyntaxToken Identifier { get { var slot = ((Syntax.InternalSyntax.TupleElementSyntax)this.Green).identifier; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.type)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.type : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitTupleElement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitTupleElement(this); public TupleElementSyntax Update(TypeSyntax type, SyntaxToken identifier) { if (type != this.Type || identifier != this.Identifier) { var newNode = SyntaxFactory.TupleElement(type, identifier); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public TupleElementSyntax WithType(TypeSyntax type) => Update(type, this.Identifier); public TupleElementSyntax WithIdentifier(SyntaxToken identifier) => Update(this.Type, identifier); } /// <summary>Class which represents a placeholder in the type argument list of an unbound generic type.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.OmittedTypeArgument"/></description></item> /// </list> /// </remarks> public sealed partial class OmittedTypeArgumentSyntax : TypeSyntax { internal OmittedTypeArgumentSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the omitted type argument.</summary> public SyntaxToken OmittedTypeArgumentToken => new SyntaxToken(this, ((Syntax.InternalSyntax.OmittedTypeArgumentSyntax)this.Green).omittedTypeArgumentToken, Position, 0); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitOmittedTypeArgument(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitOmittedTypeArgument(this); public OmittedTypeArgumentSyntax Update(SyntaxToken omittedTypeArgumentToken) { if (omittedTypeArgumentToken != this.OmittedTypeArgumentToken) { var newNode = SyntaxFactory.OmittedTypeArgument(omittedTypeArgumentToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public OmittedTypeArgumentSyntax WithOmittedTypeArgumentToken(SyntaxToken omittedTypeArgumentToken) => Update(omittedTypeArgumentToken); } /// <summary>The ref modifier of a method's return value or a local.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.RefType"/></description></item> /// </list> /// </remarks> public sealed partial class RefTypeSyntax : TypeSyntax { private TypeSyntax? type; internal RefTypeSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken RefKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.RefTypeSyntax)this.Green).refKeyword, Position, 0); /// <summary>Gets the optional "readonly" keyword.</summary> public SyntaxToken ReadOnlyKeyword { get { var slot = ((Syntax.InternalSyntax.RefTypeSyntax)this.Green).readOnlyKeyword; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public TypeSyntax Type => GetRed(ref this.type, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 2 ? GetRed(ref this.type, 2)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 2 ? this.type : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitRefType(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitRefType(this); public RefTypeSyntax Update(SyntaxToken refKeyword, SyntaxToken readOnlyKeyword, TypeSyntax type) { if (refKeyword != this.RefKeyword || readOnlyKeyword != this.ReadOnlyKeyword || type != this.Type) { var newNode = SyntaxFactory.RefType(refKeyword, readOnlyKeyword, type); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public RefTypeSyntax WithRefKeyword(SyntaxToken refKeyword) => Update(refKeyword, this.ReadOnlyKeyword, this.Type); public RefTypeSyntax WithReadOnlyKeyword(SyntaxToken readOnlyKeyword) => Update(this.RefKeyword, readOnlyKeyword, this.Type); public RefTypeSyntax WithType(TypeSyntax type) => Update(this.RefKeyword, this.ReadOnlyKeyword, type); } public abstract partial class ExpressionOrPatternSyntax : CSharpSyntaxNode { internal ExpressionOrPatternSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } } /// <summary>Provides the base class from which the classes that represent expression syntax nodes are derived. This is an abstract class.</summary> public abstract partial class ExpressionSyntax : ExpressionOrPatternSyntax { internal ExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } } /// <summary>Class which represents the syntax node for parenthesized expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ParenthesizedExpression"/></description></item> /// </list> /// </remarks> public sealed partial class ParenthesizedExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? expression; internal ParenthesizedExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the open parenthesis.</summary> public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ParenthesizedExpressionSyntax)this.Green).openParenToken, Position, 0); /// <summary>ExpressionSyntax node representing the expression enclosed within the parenthesis.</summary> public ExpressionSyntax Expression => GetRed(ref this.expression, 1)!; /// <summary>SyntaxToken representing the close parenthesis.</summary> public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ParenthesizedExpressionSyntax)this.Green).closeParenToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.expression, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.expression : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitParenthesizedExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitParenthesizedExpression(this); public ParenthesizedExpressionSyntax Update(SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken) { if (openParenToken != this.OpenParenToken || expression != this.Expression || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.ParenthesizedExpression(openParenToken, expression, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ParenthesizedExpressionSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(openParenToken, this.Expression, this.CloseParenToken); public ParenthesizedExpressionSyntax WithExpression(ExpressionSyntax expression) => Update(this.OpenParenToken, expression, this.CloseParenToken); public ParenthesizedExpressionSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.OpenParenToken, this.Expression, closeParenToken); } /// <summary>Class which represents the syntax node for tuple expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.TupleExpression"/></description></item> /// </list> /// </remarks> public sealed partial class TupleExpressionSyntax : ExpressionSyntax { private SyntaxNode? arguments; internal TupleExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the open parenthesis.</summary> public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.TupleExpressionSyntax)this.Green).openParenToken, Position, 0); /// <summary>SeparatedSyntaxList of ArgumentSyntax representing the list of arguments.</summary> public SeparatedSyntaxList<ArgumentSyntax> Arguments { get { var red = GetRed(ref this.arguments, 1); return red != null ? new SeparatedSyntaxList<ArgumentSyntax>(red, GetChildIndex(1)) : default; } } /// <summary>SyntaxToken representing the close parenthesis.</summary> public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.TupleExpressionSyntax)this.Green).closeParenToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.arguments, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.arguments : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitTupleExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitTupleExpression(this); public TupleExpressionSyntax Update(SyntaxToken openParenToken, SeparatedSyntaxList<ArgumentSyntax> arguments, SyntaxToken closeParenToken) { if (openParenToken != this.OpenParenToken || arguments != this.Arguments || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.TupleExpression(openParenToken, arguments, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public TupleExpressionSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(openParenToken, this.Arguments, this.CloseParenToken); public TupleExpressionSyntax WithArguments(SeparatedSyntaxList<ArgumentSyntax> arguments) => Update(this.OpenParenToken, arguments, this.CloseParenToken); public TupleExpressionSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.OpenParenToken, this.Arguments, closeParenToken); public TupleExpressionSyntax AddArguments(params ArgumentSyntax[] items) => WithArguments(this.Arguments.AddRange(items)); } /// <summary>Class which represents the syntax node for prefix unary expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.UnaryPlusExpression"/></description></item> /// <item><description><see cref="SyntaxKind.UnaryMinusExpression"/></description></item> /// <item><description><see cref="SyntaxKind.BitwiseNotExpression"/></description></item> /// <item><description><see cref="SyntaxKind.LogicalNotExpression"/></description></item> /// <item><description><see cref="SyntaxKind.PreIncrementExpression"/></description></item> /// <item><description><see cref="SyntaxKind.PreDecrementExpression"/></description></item> /// <item><description><see cref="SyntaxKind.AddressOfExpression"/></description></item> /// <item><description><see cref="SyntaxKind.PointerIndirectionExpression"/></description></item> /// <item><description><see cref="SyntaxKind.IndexExpression"/></description></item> /// </list> /// </remarks> public sealed partial class PrefixUnaryExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? operand; internal PrefixUnaryExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the kind of the operator of the prefix unary expression.</summary> public SyntaxToken OperatorToken => new SyntaxToken(this, ((Syntax.InternalSyntax.PrefixUnaryExpressionSyntax)this.Green).operatorToken, Position, 0); /// <summary>ExpressionSyntax representing the operand of the prefix unary expression.</summary> public ExpressionSyntax Operand => GetRed(ref this.operand, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.operand, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.operand : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitPrefixUnaryExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitPrefixUnaryExpression(this); public PrefixUnaryExpressionSyntax Update(SyntaxToken operatorToken, ExpressionSyntax operand) { if (operatorToken != this.OperatorToken || operand != this.Operand) { var newNode = SyntaxFactory.PrefixUnaryExpression(this.Kind(), operatorToken, operand); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public PrefixUnaryExpressionSyntax WithOperatorToken(SyntaxToken operatorToken) => Update(operatorToken, this.Operand); public PrefixUnaryExpressionSyntax WithOperand(ExpressionSyntax operand) => Update(this.OperatorToken, operand); } /// <summary>Class which represents the syntax node for an "await" expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.AwaitExpression"/></description></item> /// </list> /// </remarks> public sealed partial class AwaitExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? expression; internal AwaitExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the kind "await" keyword.</summary> public SyntaxToken AwaitKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.AwaitExpressionSyntax)this.Green).awaitKeyword, Position, 0); /// <summary>ExpressionSyntax representing the operand of the "await" operator.</summary> public ExpressionSyntax Expression => GetRed(ref this.expression, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.expression, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.expression : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitAwaitExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitAwaitExpression(this); public AwaitExpressionSyntax Update(SyntaxToken awaitKeyword, ExpressionSyntax expression) { if (awaitKeyword != this.AwaitKeyword || expression != this.Expression) { var newNode = SyntaxFactory.AwaitExpression(awaitKeyword, expression); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public AwaitExpressionSyntax WithAwaitKeyword(SyntaxToken awaitKeyword) => Update(awaitKeyword, this.Expression); public AwaitExpressionSyntax WithExpression(ExpressionSyntax expression) => Update(this.AwaitKeyword, expression); } /// <summary>Class which represents the syntax node for postfix unary expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.PostIncrementExpression"/></description></item> /// <item><description><see cref="SyntaxKind.PostDecrementExpression"/></description></item> /// <item><description><see cref="SyntaxKind.SuppressNullableWarningExpression"/></description></item> /// </list> /// </remarks> public sealed partial class PostfixUnaryExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? operand; internal PostfixUnaryExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>ExpressionSyntax representing the operand of the postfix unary expression.</summary> public ExpressionSyntax Operand => GetRedAtZero(ref this.operand)!; /// <summary>SyntaxToken representing the kind of the operator of the postfix unary expression.</summary> public SyntaxToken OperatorToken => new SyntaxToken(this, ((Syntax.InternalSyntax.PostfixUnaryExpressionSyntax)this.Green).operatorToken, GetChildPosition(1), GetChildIndex(1)); internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.operand)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.operand : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitPostfixUnaryExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitPostfixUnaryExpression(this); public PostfixUnaryExpressionSyntax Update(ExpressionSyntax operand, SyntaxToken operatorToken) { if (operand != this.Operand || operatorToken != this.OperatorToken) { var newNode = SyntaxFactory.PostfixUnaryExpression(this.Kind(), operand, operatorToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public PostfixUnaryExpressionSyntax WithOperand(ExpressionSyntax operand) => Update(operand, this.OperatorToken); public PostfixUnaryExpressionSyntax WithOperatorToken(SyntaxToken operatorToken) => Update(this.Operand, operatorToken); } /// <summary>Class which represents the syntax node for member access expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.SimpleMemberAccessExpression"/></description></item> /// <item><description><see cref="SyntaxKind.PointerMemberAccessExpression"/></description></item> /// </list> /// </remarks> public sealed partial class MemberAccessExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? expression; private SimpleNameSyntax? name; internal MemberAccessExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>ExpressionSyntax node representing the object that the member belongs to.</summary> public ExpressionSyntax Expression => GetRedAtZero(ref this.expression)!; /// <summary>SyntaxToken representing the kind of the operator in the member access expression.</summary> public SyntaxToken OperatorToken => new SyntaxToken(this, ((Syntax.InternalSyntax.MemberAccessExpressionSyntax)this.Green).operatorToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>SimpleNameSyntax node representing the member being accessed.</summary> public SimpleNameSyntax Name => GetRed(ref this.name, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.expression)!, 2 => GetRed(ref this.name, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.expression, 2 => this.name, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitMemberAccessExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitMemberAccessExpression(this); public MemberAccessExpressionSyntax Update(ExpressionSyntax expression, SyntaxToken operatorToken, SimpleNameSyntax name) { if (expression != this.Expression || operatorToken != this.OperatorToken || name != this.Name) { var newNode = SyntaxFactory.MemberAccessExpression(this.Kind(), expression, operatorToken, name); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public MemberAccessExpressionSyntax WithExpression(ExpressionSyntax expression) => Update(expression, this.OperatorToken, this.Name); public MemberAccessExpressionSyntax WithOperatorToken(SyntaxToken operatorToken) => Update(this.Expression, operatorToken, this.Name); public MemberAccessExpressionSyntax WithName(SimpleNameSyntax name) => Update(this.Expression, this.OperatorToken, name); } /// <summary>Class which represents the syntax node for conditional access expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ConditionalAccessExpression"/></description></item> /// </list> /// </remarks> public sealed partial class ConditionalAccessExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? expression; private ExpressionSyntax? whenNotNull; internal ConditionalAccessExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>ExpressionSyntax node representing the object conditionally accessed.</summary> public ExpressionSyntax Expression => GetRedAtZero(ref this.expression)!; /// <summary>SyntaxToken representing the question mark.</summary> public SyntaxToken OperatorToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ConditionalAccessExpressionSyntax)this.Green).operatorToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>ExpressionSyntax node representing the access expression to be executed when the object is not null.</summary> public ExpressionSyntax WhenNotNull => GetRed(ref this.whenNotNull, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.expression)!, 2 => GetRed(ref this.whenNotNull, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.expression, 2 => this.whenNotNull, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitConditionalAccessExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitConditionalAccessExpression(this); public ConditionalAccessExpressionSyntax Update(ExpressionSyntax expression, SyntaxToken operatorToken, ExpressionSyntax whenNotNull) { if (expression != this.Expression || operatorToken != this.OperatorToken || whenNotNull != this.WhenNotNull) { var newNode = SyntaxFactory.ConditionalAccessExpression(expression, operatorToken, whenNotNull); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ConditionalAccessExpressionSyntax WithExpression(ExpressionSyntax expression) => Update(expression, this.OperatorToken, this.WhenNotNull); public ConditionalAccessExpressionSyntax WithOperatorToken(SyntaxToken operatorToken) => Update(this.Expression, operatorToken, this.WhenNotNull); public ConditionalAccessExpressionSyntax WithWhenNotNull(ExpressionSyntax whenNotNull) => Update(this.Expression, this.OperatorToken, whenNotNull); } /// <summary>Class which represents the syntax node for member binding expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.MemberBindingExpression"/></description></item> /// </list> /// </remarks> public sealed partial class MemberBindingExpressionSyntax : ExpressionSyntax { private SimpleNameSyntax? name; internal MemberBindingExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing dot.</summary> public SyntaxToken OperatorToken => new SyntaxToken(this, ((Syntax.InternalSyntax.MemberBindingExpressionSyntax)this.Green).operatorToken, Position, 0); /// <summary>SimpleNameSyntax node representing the member being bound to.</summary> public SimpleNameSyntax Name => GetRed(ref this.name, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.name, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.name : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitMemberBindingExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitMemberBindingExpression(this); public MemberBindingExpressionSyntax Update(SyntaxToken operatorToken, SimpleNameSyntax name) { if (operatorToken != this.OperatorToken || name != this.Name) { var newNode = SyntaxFactory.MemberBindingExpression(operatorToken, name); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public MemberBindingExpressionSyntax WithOperatorToken(SyntaxToken operatorToken) => Update(operatorToken, this.Name); public MemberBindingExpressionSyntax WithName(SimpleNameSyntax name) => Update(this.OperatorToken, name); } /// <summary>Class which represents the syntax node for element binding expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ElementBindingExpression"/></description></item> /// </list> /// </remarks> public sealed partial class ElementBindingExpressionSyntax : ExpressionSyntax { private BracketedArgumentListSyntax? argumentList; internal ElementBindingExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>BracketedArgumentListSyntax node representing the list of arguments of the element binding expression.</summary> public BracketedArgumentListSyntax ArgumentList => GetRedAtZero(ref this.argumentList)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.argumentList)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.argumentList : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitElementBindingExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitElementBindingExpression(this); public ElementBindingExpressionSyntax Update(BracketedArgumentListSyntax argumentList) { if (argumentList != this.ArgumentList) { var newNode = SyntaxFactory.ElementBindingExpression(argumentList); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ElementBindingExpressionSyntax WithArgumentList(BracketedArgumentListSyntax argumentList) => Update(argumentList); public ElementBindingExpressionSyntax AddArgumentListArguments(params ArgumentSyntax[] items) => WithArgumentList(this.ArgumentList.WithArguments(this.ArgumentList.Arguments.AddRange(items))); } /// <summary>Class which represents the syntax node for a range expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.RangeExpression"/></description></item> /// </list> /// </remarks> public sealed partial class RangeExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? leftOperand; private ExpressionSyntax? rightOperand; internal RangeExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>ExpressionSyntax node representing the expression on the left of the range operator.</summary> public ExpressionSyntax? LeftOperand => GetRedAtZero(ref this.leftOperand); /// <summary>SyntaxToken representing the operator of the range expression.</summary> public SyntaxToken OperatorToken => new SyntaxToken(this, ((Syntax.InternalSyntax.RangeExpressionSyntax)this.Green).operatorToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>ExpressionSyntax node representing the expression on the right of the range operator.</summary> public ExpressionSyntax? RightOperand => GetRed(ref this.rightOperand, 2); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.leftOperand), 2 => GetRed(ref this.rightOperand, 2), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.leftOperand, 2 => this.rightOperand, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitRangeExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitRangeExpression(this); public RangeExpressionSyntax Update(ExpressionSyntax? leftOperand, SyntaxToken operatorToken, ExpressionSyntax? rightOperand) { if (leftOperand != this.LeftOperand || operatorToken != this.OperatorToken || rightOperand != this.RightOperand) { var newNode = SyntaxFactory.RangeExpression(leftOperand, operatorToken, rightOperand); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public RangeExpressionSyntax WithLeftOperand(ExpressionSyntax? leftOperand) => Update(leftOperand, this.OperatorToken, this.RightOperand); public RangeExpressionSyntax WithOperatorToken(SyntaxToken operatorToken) => Update(this.LeftOperand, operatorToken, this.RightOperand); public RangeExpressionSyntax WithRightOperand(ExpressionSyntax? rightOperand) => Update(this.LeftOperand, this.OperatorToken, rightOperand); } /// <summary>Class which represents the syntax node for implicit element access expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ImplicitElementAccess"/></description></item> /// </list> /// </remarks> public sealed partial class ImplicitElementAccessSyntax : ExpressionSyntax { private BracketedArgumentListSyntax? argumentList; internal ImplicitElementAccessSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>BracketedArgumentListSyntax node representing the list of arguments of the implicit element access expression.</summary> public BracketedArgumentListSyntax ArgumentList => GetRedAtZero(ref this.argumentList)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.argumentList)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.argumentList : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitImplicitElementAccess(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitImplicitElementAccess(this); public ImplicitElementAccessSyntax Update(BracketedArgumentListSyntax argumentList) { if (argumentList != this.ArgumentList) { var newNode = SyntaxFactory.ImplicitElementAccess(argumentList); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ImplicitElementAccessSyntax WithArgumentList(BracketedArgumentListSyntax argumentList) => Update(argumentList); public ImplicitElementAccessSyntax AddArgumentListArguments(params ArgumentSyntax[] items) => WithArgumentList(this.ArgumentList.WithArguments(this.ArgumentList.Arguments.AddRange(items))); } /// <summary>Class which represents an expression that has a binary operator.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.AddExpression"/></description></item> /// <item><description><see cref="SyntaxKind.SubtractExpression"/></description></item> /// <item><description><see cref="SyntaxKind.MultiplyExpression"/></description></item> /// <item><description><see cref="SyntaxKind.DivideExpression"/></description></item> /// <item><description><see cref="SyntaxKind.ModuloExpression"/></description></item> /// <item><description><see cref="SyntaxKind.LeftShiftExpression"/></description></item> /// <item><description><see cref="SyntaxKind.RightShiftExpression"/></description></item> /// <item><description><see cref="SyntaxKind.LogicalOrExpression"/></description></item> /// <item><description><see cref="SyntaxKind.LogicalAndExpression"/></description></item> /// <item><description><see cref="SyntaxKind.BitwiseOrExpression"/></description></item> /// <item><description><see cref="SyntaxKind.BitwiseAndExpression"/></description></item> /// <item><description><see cref="SyntaxKind.ExclusiveOrExpression"/></description></item> /// <item><description><see cref="SyntaxKind.EqualsExpression"/></description></item> /// <item><description><see cref="SyntaxKind.NotEqualsExpression"/></description></item> /// <item><description><see cref="SyntaxKind.LessThanExpression"/></description></item> /// <item><description><see cref="SyntaxKind.LessThanOrEqualExpression"/></description></item> /// <item><description><see cref="SyntaxKind.GreaterThanExpression"/></description></item> /// <item><description><see cref="SyntaxKind.GreaterThanOrEqualExpression"/></description></item> /// <item><description><see cref="SyntaxKind.IsExpression"/></description></item> /// <item><description><see cref="SyntaxKind.AsExpression"/></description></item> /// <item><description><see cref="SyntaxKind.CoalesceExpression"/></description></item> /// </list> /// </remarks> public sealed partial class BinaryExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? left; private ExpressionSyntax? right; internal BinaryExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>ExpressionSyntax node representing the expression on the left of the binary operator.</summary> public ExpressionSyntax Left => GetRedAtZero(ref this.left)!; /// <summary>SyntaxToken representing the operator of the binary expression.</summary> public SyntaxToken OperatorToken => new SyntaxToken(this, ((Syntax.InternalSyntax.BinaryExpressionSyntax)this.Green).operatorToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>ExpressionSyntax node representing the expression on the right of the binary operator.</summary> public ExpressionSyntax Right => GetRed(ref this.right, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.left)!, 2 => GetRed(ref this.right, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.left, 2 => this.right, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitBinaryExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitBinaryExpression(this); public BinaryExpressionSyntax Update(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) { if (left != this.Left || operatorToken != this.OperatorToken || right != this.Right) { var newNode = SyntaxFactory.BinaryExpression(this.Kind(), left, operatorToken, right); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public BinaryExpressionSyntax WithLeft(ExpressionSyntax left) => Update(left, this.OperatorToken, this.Right); public BinaryExpressionSyntax WithOperatorToken(SyntaxToken operatorToken) => Update(this.Left, operatorToken, this.Right); public BinaryExpressionSyntax WithRight(ExpressionSyntax right) => Update(this.Left, this.OperatorToken, right); } /// <summary>Class which represents an expression that has an assignment operator.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.SimpleAssignmentExpression"/></description></item> /// <item><description><see cref="SyntaxKind.AddAssignmentExpression"/></description></item> /// <item><description><see cref="SyntaxKind.SubtractAssignmentExpression"/></description></item> /// <item><description><see cref="SyntaxKind.MultiplyAssignmentExpression"/></description></item> /// <item><description><see cref="SyntaxKind.DivideAssignmentExpression"/></description></item> /// <item><description><see cref="SyntaxKind.ModuloAssignmentExpression"/></description></item> /// <item><description><see cref="SyntaxKind.AndAssignmentExpression"/></description></item> /// <item><description><see cref="SyntaxKind.ExclusiveOrAssignmentExpression"/></description></item> /// <item><description><see cref="SyntaxKind.OrAssignmentExpression"/></description></item> /// <item><description><see cref="SyntaxKind.LeftShiftAssignmentExpression"/></description></item> /// <item><description><see cref="SyntaxKind.RightShiftAssignmentExpression"/></description></item> /// <item><description><see cref="SyntaxKind.CoalesceAssignmentExpression"/></description></item> /// </list> /// </remarks> public sealed partial class AssignmentExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? left; private ExpressionSyntax? right; internal AssignmentExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>ExpressionSyntax node representing the expression on the left of the assignment operator.</summary> public ExpressionSyntax Left => GetRedAtZero(ref this.left)!; /// <summary>SyntaxToken representing the operator of the assignment expression.</summary> public SyntaxToken OperatorToken => new SyntaxToken(this, ((Syntax.InternalSyntax.AssignmentExpressionSyntax)this.Green).operatorToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>ExpressionSyntax node representing the expression on the right of the assignment operator.</summary> public ExpressionSyntax Right => GetRed(ref this.right, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.left)!, 2 => GetRed(ref this.right, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.left, 2 => this.right, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitAssignmentExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitAssignmentExpression(this); public AssignmentExpressionSyntax Update(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) { if (left != this.Left || operatorToken != this.OperatorToken || right != this.Right) { var newNode = SyntaxFactory.AssignmentExpression(this.Kind(), left, operatorToken, right); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public AssignmentExpressionSyntax WithLeft(ExpressionSyntax left) => Update(left, this.OperatorToken, this.Right); public AssignmentExpressionSyntax WithOperatorToken(SyntaxToken operatorToken) => Update(this.Left, operatorToken, this.Right); public AssignmentExpressionSyntax WithRight(ExpressionSyntax right) => Update(this.Left, this.OperatorToken, right); } /// <summary>Class which represents the syntax node for conditional expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ConditionalExpression"/></description></item> /// </list> /// </remarks> public sealed partial class ConditionalExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? condition; private ExpressionSyntax? whenTrue; private ExpressionSyntax? whenFalse; internal ConditionalExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>ExpressionSyntax node representing the condition of the conditional expression.</summary> public ExpressionSyntax Condition => GetRedAtZero(ref this.condition)!; /// <summary>SyntaxToken representing the question mark.</summary> public SyntaxToken QuestionToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ConditionalExpressionSyntax)this.Green).questionToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>ExpressionSyntax node representing the expression to be executed when the condition is true.</summary> public ExpressionSyntax WhenTrue => GetRed(ref this.whenTrue, 2)!; /// <summary>SyntaxToken representing the colon.</summary> public SyntaxToken ColonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ConditionalExpressionSyntax)this.Green).colonToken, GetChildPosition(3), GetChildIndex(3)); /// <summary>ExpressionSyntax node representing the expression to be executed when the condition is false.</summary> public ExpressionSyntax WhenFalse => GetRed(ref this.whenFalse, 4)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.condition)!, 2 => GetRed(ref this.whenTrue, 2)!, 4 => GetRed(ref this.whenFalse, 4)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.condition, 2 => this.whenTrue, 4 => this.whenFalse, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitConditionalExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitConditionalExpression(this); public ConditionalExpressionSyntax Update(ExpressionSyntax condition, SyntaxToken questionToken, ExpressionSyntax whenTrue, SyntaxToken colonToken, ExpressionSyntax whenFalse) { if (condition != this.Condition || questionToken != this.QuestionToken || whenTrue != this.WhenTrue || colonToken != this.ColonToken || whenFalse != this.WhenFalse) { var newNode = SyntaxFactory.ConditionalExpression(condition, questionToken, whenTrue, colonToken, whenFalse); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ConditionalExpressionSyntax WithCondition(ExpressionSyntax condition) => Update(condition, this.QuestionToken, this.WhenTrue, this.ColonToken, this.WhenFalse); public ConditionalExpressionSyntax WithQuestionToken(SyntaxToken questionToken) => Update(this.Condition, questionToken, this.WhenTrue, this.ColonToken, this.WhenFalse); public ConditionalExpressionSyntax WithWhenTrue(ExpressionSyntax whenTrue) => Update(this.Condition, this.QuestionToken, whenTrue, this.ColonToken, this.WhenFalse); public ConditionalExpressionSyntax WithColonToken(SyntaxToken colonToken) => Update(this.Condition, this.QuestionToken, this.WhenTrue, colonToken, this.WhenFalse); public ConditionalExpressionSyntax WithWhenFalse(ExpressionSyntax whenFalse) => Update(this.Condition, this.QuestionToken, this.WhenTrue, this.ColonToken, whenFalse); } /// <summary>Provides the base class from which the classes that represent instance expression syntax nodes are derived. This is an abstract class.</summary> public abstract partial class InstanceExpressionSyntax : ExpressionSyntax { internal InstanceExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } } /// <summary>Class which represents the syntax node for a this expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ThisExpression"/></description></item> /// </list> /// </remarks> public sealed partial class ThisExpressionSyntax : InstanceExpressionSyntax { internal ThisExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the this keyword.</summary> public SyntaxToken Token => new SyntaxToken(this, ((Syntax.InternalSyntax.ThisExpressionSyntax)this.Green).token, Position, 0); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitThisExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitThisExpression(this); public ThisExpressionSyntax Update(SyntaxToken token) { if (token != this.Token) { var newNode = SyntaxFactory.ThisExpression(token); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ThisExpressionSyntax WithToken(SyntaxToken token) => Update(token); } /// <summary>Class which represents the syntax node for a base expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.BaseExpression"/></description></item> /// </list> /// </remarks> public sealed partial class BaseExpressionSyntax : InstanceExpressionSyntax { internal BaseExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the base keyword.</summary> public SyntaxToken Token => new SyntaxToken(this, ((Syntax.InternalSyntax.BaseExpressionSyntax)this.Green).token, Position, 0); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitBaseExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitBaseExpression(this); public BaseExpressionSyntax Update(SyntaxToken token) { if (token != this.Token) { var newNode = SyntaxFactory.BaseExpression(token); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public BaseExpressionSyntax WithToken(SyntaxToken token) => Update(token); } /// <summary>Class which represents the syntax node for a literal expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ArgListExpression"/></description></item> /// <item><description><see cref="SyntaxKind.NumericLiteralExpression"/></description></item> /// <item><description><see cref="SyntaxKind.StringLiteralExpression"/></description></item> /// <item><description><see cref="SyntaxKind.CharacterLiteralExpression"/></description></item> /// <item><description><see cref="SyntaxKind.TrueLiteralExpression"/></description></item> /// <item><description><see cref="SyntaxKind.FalseLiteralExpression"/></description></item> /// <item><description><see cref="SyntaxKind.NullLiteralExpression"/></description></item> /// <item><description><see cref="SyntaxKind.DefaultLiteralExpression"/></description></item> /// </list> /// </remarks> public sealed partial class LiteralExpressionSyntax : ExpressionSyntax { internal LiteralExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the keyword corresponding to the kind of the literal expression.</summary> public SyntaxToken Token => new SyntaxToken(this, ((Syntax.InternalSyntax.LiteralExpressionSyntax)this.Green).token, Position, 0); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitLiteralExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitLiteralExpression(this); public LiteralExpressionSyntax Update(SyntaxToken token) { if (token != this.Token) { var newNode = SyntaxFactory.LiteralExpression(this.Kind(), token); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public LiteralExpressionSyntax WithToken(SyntaxToken token) => Update(token); } /// <summary>Class which represents the syntax node for MakeRef expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.MakeRefExpression"/></description></item> /// </list> /// </remarks> public sealed partial class MakeRefExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? expression; internal MakeRefExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the MakeRefKeyword.</summary> public SyntaxToken Keyword => new SyntaxToken(this, ((Syntax.InternalSyntax.MakeRefExpressionSyntax)this.Green).keyword, Position, 0); /// <summary>SyntaxToken representing open parenthesis.</summary> public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.MakeRefExpressionSyntax)this.Green).openParenToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>Argument of the primary function.</summary> public ExpressionSyntax Expression => GetRed(ref this.expression, 2)!; /// <summary>SyntaxToken representing close parenthesis.</summary> public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.MakeRefExpressionSyntax)this.Green).closeParenToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => index == 2 ? GetRed(ref this.expression, 2)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 2 ? this.expression : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitMakeRefExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitMakeRefExpression(this); public MakeRefExpressionSyntax Update(SyntaxToken keyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken) { if (keyword != this.Keyword || openParenToken != this.OpenParenToken || expression != this.Expression || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.MakeRefExpression(keyword, openParenToken, expression, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public MakeRefExpressionSyntax WithKeyword(SyntaxToken keyword) => Update(keyword, this.OpenParenToken, this.Expression, this.CloseParenToken); public MakeRefExpressionSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.Keyword, openParenToken, this.Expression, this.CloseParenToken); public MakeRefExpressionSyntax WithExpression(ExpressionSyntax expression) => Update(this.Keyword, this.OpenParenToken, expression, this.CloseParenToken); public MakeRefExpressionSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.Keyword, this.OpenParenToken, this.Expression, closeParenToken); } /// <summary>Class which represents the syntax node for RefType expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.RefTypeExpression"/></description></item> /// </list> /// </remarks> public sealed partial class RefTypeExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? expression; internal RefTypeExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the RefTypeKeyword.</summary> public SyntaxToken Keyword => new SyntaxToken(this, ((Syntax.InternalSyntax.RefTypeExpressionSyntax)this.Green).keyword, Position, 0); /// <summary>SyntaxToken representing open parenthesis.</summary> public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.RefTypeExpressionSyntax)this.Green).openParenToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>Argument of the primary function.</summary> public ExpressionSyntax Expression => GetRed(ref this.expression, 2)!; /// <summary>SyntaxToken representing close parenthesis.</summary> public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.RefTypeExpressionSyntax)this.Green).closeParenToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => index == 2 ? GetRed(ref this.expression, 2)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 2 ? this.expression : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitRefTypeExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitRefTypeExpression(this); public RefTypeExpressionSyntax Update(SyntaxToken keyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken) { if (keyword != this.Keyword || openParenToken != this.OpenParenToken || expression != this.Expression || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.RefTypeExpression(keyword, openParenToken, expression, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public RefTypeExpressionSyntax WithKeyword(SyntaxToken keyword) => Update(keyword, this.OpenParenToken, this.Expression, this.CloseParenToken); public RefTypeExpressionSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.Keyword, openParenToken, this.Expression, this.CloseParenToken); public RefTypeExpressionSyntax WithExpression(ExpressionSyntax expression) => Update(this.Keyword, this.OpenParenToken, expression, this.CloseParenToken); public RefTypeExpressionSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.Keyword, this.OpenParenToken, this.Expression, closeParenToken); } /// <summary>Class which represents the syntax node for RefValue expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.RefValueExpression"/></description></item> /// </list> /// </remarks> public sealed partial class RefValueExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? expression; private TypeSyntax? type; internal RefValueExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the RefValueKeyword.</summary> public SyntaxToken Keyword => new SyntaxToken(this, ((Syntax.InternalSyntax.RefValueExpressionSyntax)this.Green).keyword, Position, 0); /// <summary>SyntaxToken representing open parenthesis.</summary> public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.RefValueExpressionSyntax)this.Green).openParenToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>Typed reference expression.</summary> public ExpressionSyntax Expression => GetRed(ref this.expression, 2)!; /// <summary>Comma separating the arguments.</summary> public SyntaxToken Comma => new SyntaxToken(this, ((Syntax.InternalSyntax.RefValueExpressionSyntax)this.Green).comma, GetChildPosition(3), GetChildIndex(3)); /// <summary>The type of the value.</summary> public TypeSyntax Type => GetRed(ref this.type, 4)!; /// <summary>SyntaxToken representing close parenthesis.</summary> public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.RefValueExpressionSyntax)this.Green).closeParenToken, GetChildPosition(5), GetChildIndex(5)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 2 => GetRed(ref this.expression, 2)!, 4 => GetRed(ref this.type, 4)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 2 => this.expression, 4 => this.type, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitRefValueExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitRefValueExpression(this); public RefValueExpressionSyntax Update(SyntaxToken keyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken comma, TypeSyntax type, SyntaxToken closeParenToken) { if (keyword != this.Keyword || openParenToken != this.OpenParenToken || expression != this.Expression || comma != this.Comma || type != this.Type || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.RefValueExpression(keyword, openParenToken, expression, comma, type, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public RefValueExpressionSyntax WithKeyword(SyntaxToken keyword) => Update(keyword, this.OpenParenToken, this.Expression, this.Comma, this.Type, this.CloseParenToken); public RefValueExpressionSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.Keyword, openParenToken, this.Expression, this.Comma, this.Type, this.CloseParenToken); public RefValueExpressionSyntax WithExpression(ExpressionSyntax expression) => Update(this.Keyword, this.OpenParenToken, expression, this.Comma, this.Type, this.CloseParenToken); public RefValueExpressionSyntax WithComma(SyntaxToken comma) => Update(this.Keyword, this.OpenParenToken, this.Expression, comma, this.Type, this.CloseParenToken); public RefValueExpressionSyntax WithType(TypeSyntax type) => Update(this.Keyword, this.OpenParenToken, this.Expression, this.Comma, type, this.CloseParenToken); public RefValueExpressionSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.Keyword, this.OpenParenToken, this.Expression, this.Comma, this.Type, closeParenToken); } /// <summary>Class which represents the syntax node for Checked or Unchecked expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.CheckedExpression"/></description></item> /// <item><description><see cref="SyntaxKind.UncheckedExpression"/></description></item> /// </list> /// </remarks> public sealed partial class CheckedExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? expression; internal CheckedExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the checked or unchecked keyword.</summary> public SyntaxToken Keyword => new SyntaxToken(this, ((Syntax.InternalSyntax.CheckedExpressionSyntax)this.Green).keyword, Position, 0); /// <summary>SyntaxToken representing open parenthesis.</summary> public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.CheckedExpressionSyntax)this.Green).openParenToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>Argument of the primary function.</summary> public ExpressionSyntax Expression => GetRed(ref this.expression, 2)!; /// <summary>SyntaxToken representing close parenthesis.</summary> public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.CheckedExpressionSyntax)this.Green).closeParenToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => index == 2 ? GetRed(ref this.expression, 2)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 2 ? this.expression : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitCheckedExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitCheckedExpression(this); public CheckedExpressionSyntax Update(SyntaxToken keyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken) { if (keyword != this.Keyword || openParenToken != this.OpenParenToken || expression != this.Expression || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.CheckedExpression(this.Kind(), keyword, openParenToken, expression, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public CheckedExpressionSyntax WithKeyword(SyntaxToken keyword) => Update(keyword, this.OpenParenToken, this.Expression, this.CloseParenToken); public CheckedExpressionSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.Keyword, openParenToken, this.Expression, this.CloseParenToken); public CheckedExpressionSyntax WithExpression(ExpressionSyntax expression) => Update(this.Keyword, this.OpenParenToken, expression, this.CloseParenToken); public CheckedExpressionSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.Keyword, this.OpenParenToken, this.Expression, closeParenToken); } /// <summary>Class which represents the syntax node for Default expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.DefaultExpression"/></description></item> /// </list> /// </remarks> public sealed partial class DefaultExpressionSyntax : ExpressionSyntax { private TypeSyntax? type; internal DefaultExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the DefaultKeyword.</summary> public SyntaxToken Keyword => new SyntaxToken(this, ((Syntax.InternalSyntax.DefaultExpressionSyntax)this.Green).keyword, Position, 0); /// <summary>SyntaxToken representing open parenthesis.</summary> public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.DefaultExpressionSyntax)this.Green).openParenToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>Argument of the primary function.</summary> public TypeSyntax Type => GetRed(ref this.type, 2)!; /// <summary>SyntaxToken representing close parenthesis.</summary> public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.DefaultExpressionSyntax)this.Green).closeParenToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => index == 2 ? GetRed(ref this.type, 2)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 2 ? this.type : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitDefaultExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitDefaultExpression(this); public DefaultExpressionSyntax Update(SyntaxToken keyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken closeParenToken) { if (keyword != this.Keyword || openParenToken != this.OpenParenToken || type != this.Type || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.DefaultExpression(keyword, openParenToken, type, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public DefaultExpressionSyntax WithKeyword(SyntaxToken keyword) => Update(keyword, this.OpenParenToken, this.Type, this.CloseParenToken); public DefaultExpressionSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.Keyword, openParenToken, this.Type, this.CloseParenToken); public DefaultExpressionSyntax WithType(TypeSyntax type) => Update(this.Keyword, this.OpenParenToken, type, this.CloseParenToken); public DefaultExpressionSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.Keyword, this.OpenParenToken, this.Type, closeParenToken); } /// <summary>Class which represents the syntax node for TypeOf expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.TypeOfExpression"/></description></item> /// </list> /// </remarks> public sealed partial class TypeOfExpressionSyntax : ExpressionSyntax { private TypeSyntax? type; internal TypeOfExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the TypeOfKeyword.</summary> public SyntaxToken Keyword => new SyntaxToken(this, ((Syntax.InternalSyntax.TypeOfExpressionSyntax)this.Green).keyword, Position, 0); /// <summary>SyntaxToken representing open parenthesis.</summary> public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.TypeOfExpressionSyntax)this.Green).openParenToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>The expression to return type of.</summary> public TypeSyntax Type => GetRed(ref this.type, 2)!; /// <summary>SyntaxToken representing close parenthesis.</summary> public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.TypeOfExpressionSyntax)this.Green).closeParenToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => index == 2 ? GetRed(ref this.type, 2)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 2 ? this.type : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitTypeOfExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitTypeOfExpression(this); public TypeOfExpressionSyntax Update(SyntaxToken keyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken closeParenToken) { if (keyword != this.Keyword || openParenToken != this.OpenParenToken || type != this.Type || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.TypeOfExpression(keyword, openParenToken, type, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public TypeOfExpressionSyntax WithKeyword(SyntaxToken keyword) => Update(keyword, this.OpenParenToken, this.Type, this.CloseParenToken); public TypeOfExpressionSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.Keyword, openParenToken, this.Type, this.CloseParenToken); public TypeOfExpressionSyntax WithType(TypeSyntax type) => Update(this.Keyword, this.OpenParenToken, type, this.CloseParenToken); public TypeOfExpressionSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.Keyword, this.OpenParenToken, this.Type, closeParenToken); } /// <summary>Class which represents the syntax node for SizeOf expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.SizeOfExpression"/></description></item> /// </list> /// </remarks> public sealed partial class SizeOfExpressionSyntax : ExpressionSyntax { private TypeSyntax? type; internal SizeOfExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the SizeOfKeyword.</summary> public SyntaxToken Keyword => new SyntaxToken(this, ((Syntax.InternalSyntax.SizeOfExpressionSyntax)this.Green).keyword, Position, 0); /// <summary>SyntaxToken representing open parenthesis.</summary> public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.SizeOfExpressionSyntax)this.Green).openParenToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>Argument of the primary function.</summary> public TypeSyntax Type => GetRed(ref this.type, 2)!; /// <summary>SyntaxToken representing close parenthesis.</summary> public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.SizeOfExpressionSyntax)this.Green).closeParenToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => index == 2 ? GetRed(ref this.type, 2)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 2 ? this.type : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitSizeOfExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitSizeOfExpression(this); public SizeOfExpressionSyntax Update(SyntaxToken keyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken closeParenToken) { if (keyword != this.Keyword || openParenToken != this.OpenParenToken || type != this.Type || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.SizeOfExpression(keyword, openParenToken, type, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public SizeOfExpressionSyntax WithKeyword(SyntaxToken keyword) => Update(keyword, this.OpenParenToken, this.Type, this.CloseParenToken); public SizeOfExpressionSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.Keyword, openParenToken, this.Type, this.CloseParenToken); public SizeOfExpressionSyntax WithType(TypeSyntax type) => Update(this.Keyword, this.OpenParenToken, type, this.CloseParenToken); public SizeOfExpressionSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.Keyword, this.OpenParenToken, this.Type, closeParenToken); } /// <summary>Class which represents the syntax node for invocation expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.InvocationExpression"/></description></item> /// </list> /// </remarks> public sealed partial class InvocationExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? expression; private ArgumentListSyntax? argumentList; internal InvocationExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>ExpressionSyntax node representing the expression part of the invocation.</summary> public ExpressionSyntax Expression => GetRedAtZero(ref this.expression)!; /// <summary>ArgumentListSyntax node representing the list of arguments of the invocation expression.</summary> public ArgumentListSyntax ArgumentList => GetRed(ref this.argumentList, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.expression)!, 1 => GetRed(ref this.argumentList, 1)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.expression, 1 => this.argumentList, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitInvocationExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitInvocationExpression(this); public InvocationExpressionSyntax Update(ExpressionSyntax expression, ArgumentListSyntax argumentList) { if (expression != this.Expression || argumentList != this.ArgumentList) { var newNode = SyntaxFactory.InvocationExpression(expression, argumentList); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public InvocationExpressionSyntax WithExpression(ExpressionSyntax expression) => Update(expression, this.ArgumentList); public InvocationExpressionSyntax WithArgumentList(ArgumentListSyntax argumentList) => Update(this.Expression, argumentList); public InvocationExpressionSyntax AddArgumentListArguments(params ArgumentSyntax[] items) => WithArgumentList(this.ArgumentList.WithArguments(this.ArgumentList.Arguments.AddRange(items))); } /// <summary>Class which represents the syntax node for element access expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ElementAccessExpression"/></description></item> /// </list> /// </remarks> public sealed partial class ElementAccessExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? expression; private BracketedArgumentListSyntax? argumentList; internal ElementAccessExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>ExpressionSyntax node representing the expression which is accessing the element.</summary> public ExpressionSyntax Expression => GetRedAtZero(ref this.expression)!; /// <summary>BracketedArgumentListSyntax node representing the list of arguments of the element access expression.</summary> public BracketedArgumentListSyntax ArgumentList => GetRed(ref this.argumentList, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.expression)!, 1 => GetRed(ref this.argumentList, 1)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.expression, 1 => this.argumentList, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitElementAccessExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitElementAccessExpression(this); public ElementAccessExpressionSyntax Update(ExpressionSyntax expression, BracketedArgumentListSyntax argumentList) { if (expression != this.Expression || argumentList != this.ArgumentList) { var newNode = SyntaxFactory.ElementAccessExpression(expression, argumentList); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ElementAccessExpressionSyntax WithExpression(ExpressionSyntax expression) => Update(expression, this.ArgumentList); public ElementAccessExpressionSyntax WithArgumentList(BracketedArgumentListSyntax argumentList) => Update(this.Expression, argumentList); public ElementAccessExpressionSyntax AddArgumentListArguments(params ArgumentSyntax[] items) => WithArgumentList(this.ArgumentList.WithArguments(this.ArgumentList.Arguments.AddRange(items))); } /// <summary>Provides the base class from which the classes that represent argument list syntax nodes are derived. This is an abstract class.</summary> public abstract partial class BaseArgumentListSyntax : CSharpSyntaxNode { internal BaseArgumentListSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SeparatedSyntaxList of ArgumentSyntax nodes representing the list of arguments.</summary> public abstract SeparatedSyntaxList<ArgumentSyntax> Arguments { get; } public BaseArgumentListSyntax WithArguments(SeparatedSyntaxList<ArgumentSyntax> arguments) => WithArgumentsCore(arguments); internal abstract BaseArgumentListSyntax WithArgumentsCore(SeparatedSyntaxList<ArgumentSyntax> arguments); public BaseArgumentListSyntax AddArguments(params ArgumentSyntax[] items) => AddArgumentsCore(items); internal abstract BaseArgumentListSyntax AddArgumentsCore(params ArgumentSyntax[] items); } /// <summary>Class which represents the syntax node for the list of arguments.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ArgumentList"/></description></item> /// </list> /// </remarks> public sealed partial class ArgumentListSyntax : BaseArgumentListSyntax { private SyntaxNode? arguments; internal ArgumentListSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing open parenthesis.</summary> public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ArgumentListSyntax)this.Green).openParenToken, Position, 0); /// <summary>SeparatedSyntaxList of ArgumentSyntax representing the list of arguments.</summary> public override SeparatedSyntaxList<ArgumentSyntax> Arguments { get { var red = GetRed(ref this.arguments, 1); return red != null ? new SeparatedSyntaxList<ArgumentSyntax>(red, GetChildIndex(1)) : default; } } /// <summary>SyntaxToken representing close parenthesis.</summary> public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ArgumentListSyntax)this.Green).closeParenToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.arguments, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.arguments : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitArgumentList(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitArgumentList(this); public ArgumentListSyntax Update(SyntaxToken openParenToken, SeparatedSyntaxList<ArgumentSyntax> arguments, SyntaxToken closeParenToken) { if (openParenToken != this.OpenParenToken || arguments != this.Arguments || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.ArgumentList(openParenToken, arguments, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ArgumentListSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(openParenToken, this.Arguments, this.CloseParenToken); internal override BaseArgumentListSyntax WithArgumentsCore(SeparatedSyntaxList<ArgumentSyntax> arguments) => WithArguments(arguments); public new ArgumentListSyntax WithArguments(SeparatedSyntaxList<ArgumentSyntax> arguments) => Update(this.OpenParenToken, arguments, this.CloseParenToken); public ArgumentListSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.OpenParenToken, this.Arguments, closeParenToken); internal override BaseArgumentListSyntax AddArgumentsCore(params ArgumentSyntax[] items) => AddArguments(items); public new ArgumentListSyntax AddArguments(params ArgumentSyntax[] items) => WithArguments(this.Arguments.AddRange(items)); } /// <summary>Class which represents the syntax node for bracketed argument list.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.BracketedArgumentList"/></description></item> /// </list> /// </remarks> public sealed partial class BracketedArgumentListSyntax : BaseArgumentListSyntax { private SyntaxNode? arguments; internal BracketedArgumentListSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing open bracket.</summary> public SyntaxToken OpenBracketToken => new SyntaxToken(this, ((Syntax.InternalSyntax.BracketedArgumentListSyntax)this.Green).openBracketToken, Position, 0); /// <summary>SeparatedSyntaxList of ArgumentSyntax representing the list of arguments.</summary> public override SeparatedSyntaxList<ArgumentSyntax> Arguments { get { var red = GetRed(ref this.arguments, 1); return red != null ? new SeparatedSyntaxList<ArgumentSyntax>(red, GetChildIndex(1)) : default; } } /// <summary>SyntaxToken representing close bracket.</summary> public SyntaxToken CloseBracketToken => new SyntaxToken(this, ((Syntax.InternalSyntax.BracketedArgumentListSyntax)this.Green).closeBracketToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.arguments, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.arguments : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitBracketedArgumentList(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitBracketedArgumentList(this); public BracketedArgumentListSyntax Update(SyntaxToken openBracketToken, SeparatedSyntaxList<ArgumentSyntax> arguments, SyntaxToken closeBracketToken) { if (openBracketToken != this.OpenBracketToken || arguments != this.Arguments || closeBracketToken != this.CloseBracketToken) { var newNode = SyntaxFactory.BracketedArgumentList(openBracketToken, arguments, closeBracketToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public BracketedArgumentListSyntax WithOpenBracketToken(SyntaxToken openBracketToken) => Update(openBracketToken, this.Arguments, this.CloseBracketToken); internal override BaseArgumentListSyntax WithArgumentsCore(SeparatedSyntaxList<ArgumentSyntax> arguments) => WithArguments(arguments); public new BracketedArgumentListSyntax WithArguments(SeparatedSyntaxList<ArgumentSyntax> arguments) => Update(this.OpenBracketToken, arguments, this.CloseBracketToken); public BracketedArgumentListSyntax WithCloseBracketToken(SyntaxToken closeBracketToken) => Update(this.OpenBracketToken, this.Arguments, closeBracketToken); internal override BaseArgumentListSyntax AddArgumentsCore(params ArgumentSyntax[] items) => AddArguments(items); public new BracketedArgumentListSyntax AddArguments(params ArgumentSyntax[] items) => WithArguments(this.Arguments.AddRange(items)); } /// <summary>Class which represents the syntax node for argument.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.Argument"/></description></item> /// </list> /// </remarks> public sealed partial class ArgumentSyntax : CSharpSyntaxNode { private NameColonSyntax? nameColon; private ExpressionSyntax? expression; internal ArgumentSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>NameColonSyntax node representing the optional name arguments.</summary> public NameColonSyntax? NameColon => GetRedAtZero(ref this.nameColon); /// <summary>SyntaxToken representing the optional ref or out keyword.</summary> public SyntaxToken RefKindKeyword { get { var slot = ((Syntax.InternalSyntax.ArgumentSyntax)this.Green).refKindKeyword; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } /// <summary>ExpressionSyntax node representing the argument.</summary> public ExpressionSyntax Expression => GetRed(ref this.expression, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.nameColon), 2 => GetRed(ref this.expression, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.nameColon, 2 => this.expression, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitArgument(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitArgument(this); public ArgumentSyntax Update(NameColonSyntax? nameColon, SyntaxToken refKindKeyword, ExpressionSyntax expression) { if (nameColon != this.NameColon || refKindKeyword != this.RefKindKeyword || expression != this.Expression) { var newNode = SyntaxFactory.Argument(nameColon, refKindKeyword, expression); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ArgumentSyntax WithNameColon(NameColonSyntax? nameColon) => Update(nameColon, this.RefKindKeyword, this.Expression); public ArgumentSyntax WithRefKindKeyword(SyntaxToken refKindKeyword) => Update(this.NameColon, refKindKeyword, this.Expression); public ArgumentSyntax WithExpression(ExpressionSyntax expression) => Update(this.NameColon, this.RefKindKeyword, expression); } public abstract partial class BaseExpressionColonSyntax : CSharpSyntaxNode { internal BaseExpressionColonSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public abstract ExpressionSyntax Expression { get; } public BaseExpressionColonSyntax WithExpression(ExpressionSyntax expression) => WithExpressionCore(expression); internal abstract BaseExpressionColonSyntax WithExpressionCore(ExpressionSyntax expression); public abstract SyntaxToken ColonToken { get; } public BaseExpressionColonSyntax WithColonToken(SyntaxToken colonToken) => WithColonTokenCore(colonToken); internal abstract BaseExpressionColonSyntax WithColonTokenCore(SyntaxToken colonToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ExpressionColon"/></description></item> /// </list> /// </remarks> public sealed partial class ExpressionColonSyntax : BaseExpressionColonSyntax { private ExpressionSyntax? expression; internal ExpressionColonSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override ExpressionSyntax Expression => GetRedAtZero(ref this.expression)!; public override SyntaxToken ColonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ExpressionColonSyntax)this.Green).colonToken, GetChildPosition(1), GetChildIndex(1)); internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.expression)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.expression : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitExpressionColon(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitExpressionColon(this); public ExpressionColonSyntax Update(ExpressionSyntax expression, SyntaxToken colonToken) { if (expression != this.Expression || colonToken != this.ColonToken) { var newNode = SyntaxFactory.ExpressionColon(expression, colonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override BaseExpressionColonSyntax WithExpressionCore(ExpressionSyntax expression) => WithExpression(expression); public new ExpressionColonSyntax WithExpression(ExpressionSyntax expression) => Update(expression, this.ColonToken); internal override BaseExpressionColonSyntax WithColonTokenCore(SyntaxToken colonToken) => WithColonToken(colonToken); public new ExpressionColonSyntax WithColonToken(SyntaxToken colonToken) => Update(this.Expression, colonToken); } /// <summary>Class which represents the syntax node for name colon syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.NameColon"/></description></item> /// </list> /// </remarks> public sealed partial class NameColonSyntax : BaseExpressionColonSyntax { private IdentifierNameSyntax? name; internal NameColonSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>IdentifierNameSyntax representing the identifier name.</summary> public IdentifierNameSyntax Name => GetRedAtZero(ref this.name)!; /// <summary>SyntaxToken representing colon.</summary> public override SyntaxToken ColonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.NameColonSyntax)this.Green).colonToken, GetChildPosition(1), GetChildIndex(1)); internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.name)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.name : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitNameColon(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitNameColon(this); public NameColonSyntax Update(IdentifierNameSyntax name, SyntaxToken colonToken) { if (name != this.Name || colonToken != this.ColonToken) { var newNode = SyntaxFactory.NameColon(name, colonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public NameColonSyntax WithName(IdentifierNameSyntax name) => Update(name, this.ColonToken); internal override BaseExpressionColonSyntax WithColonTokenCore(SyntaxToken colonToken) => WithColonToken(colonToken); public new NameColonSyntax WithColonToken(SyntaxToken colonToken) => Update(this.Name, colonToken); } /// <summary>Class which represents the syntax node for the variable declaration in an out var declaration or a deconstruction declaration.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.DeclarationExpression"/></description></item> /// </list> /// </remarks> public sealed partial class DeclarationExpressionSyntax : ExpressionSyntax { private TypeSyntax? type; private VariableDesignationSyntax? designation; internal DeclarationExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public TypeSyntax Type => GetRedAtZero(ref this.type)!; /// <summary>Declaration representing the variable declared in an out parameter or deconstruction.</summary> public VariableDesignationSyntax Designation => GetRed(ref this.designation, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.type)!, 1 => GetRed(ref this.designation, 1)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.type, 1 => this.designation, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitDeclarationExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitDeclarationExpression(this); public DeclarationExpressionSyntax Update(TypeSyntax type, VariableDesignationSyntax designation) { if (type != this.Type || designation != this.Designation) { var newNode = SyntaxFactory.DeclarationExpression(type, designation); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public DeclarationExpressionSyntax WithType(TypeSyntax type) => Update(type, this.Designation); public DeclarationExpressionSyntax WithDesignation(VariableDesignationSyntax designation) => Update(this.Type, designation); } /// <summary>Class which represents the syntax node for cast expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.CastExpression"/></description></item> /// </list> /// </remarks> public sealed partial class CastExpressionSyntax : ExpressionSyntax { private TypeSyntax? type; private ExpressionSyntax? expression; internal CastExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the open parenthesis.</summary> public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.CastExpressionSyntax)this.Green).openParenToken, Position, 0); /// <summary>TypeSyntax node representing the type to which the expression is being cast.</summary> public TypeSyntax Type => GetRed(ref this.type, 1)!; /// <summary>SyntaxToken representing the close parenthesis.</summary> public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.CastExpressionSyntax)this.Green).closeParenToken, GetChildPosition(2), GetChildIndex(2)); /// <summary>ExpressionSyntax node representing the expression that is being casted.</summary> public ExpressionSyntax Expression => GetRed(ref this.expression, 3)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 1 => GetRed(ref this.type, 1)!, 3 => GetRed(ref this.expression, 3)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 1 => this.type, 3 => this.expression, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitCastExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitCastExpression(this); public CastExpressionSyntax Update(SyntaxToken openParenToken, TypeSyntax type, SyntaxToken closeParenToken, ExpressionSyntax expression) { if (openParenToken != this.OpenParenToken || type != this.Type || closeParenToken != this.CloseParenToken || expression != this.Expression) { var newNode = SyntaxFactory.CastExpression(openParenToken, type, closeParenToken, expression); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public CastExpressionSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(openParenToken, this.Type, this.CloseParenToken, this.Expression); public CastExpressionSyntax WithType(TypeSyntax type) => Update(this.OpenParenToken, type, this.CloseParenToken, this.Expression); public CastExpressionSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.OpenParenToken, this.Type, closeParenToken, this.Expression); public CastExpressionSyntax WithExpression(ExpressionSyntax expression) => Update(this.OpenParenToken, this.Type, this.CloseParenToken, expression); } /// <summary>Provides the base class from which the classes that represent anonymous function expressions are derived.</summary> public abstract partial class AnonymousFunctionExpressionSyntax : ExpressionSyntax { internal AnonymousFunctionExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public abstract SyntaxTokenList Modifiers { get; } public AnonymousFunctionExpressionSyntax WithModifiers(SyntaxTokenList modifiers) => WithModifiersCore(modifiers); internal abstract AnonymousFunctionExpressionSyntax WithModifiersCore(SyntaxTokenList modifiers); public AnonymousFunctionExpressionSyntax AddModifiers(params SyntaxToken[] items) => AddModifiersCore(items); internal abstract AnonymousFunctionExpressionSyntax AddModifiersCore(params SyntaxToken[] items); /// <summary> /// BlockSyntax node representing the body of the anonymous function. /// Only one of Block or ExpressionBody will be non-null. /// </summary> public abstract BlockSyntax? Block { get; } public AnonymousFunctionExpressionSyntax WithBlock(BlockSyntax? block) => WithBlockCore(block); internal abstract AnonymousFunctionExpressionSyntax WithBlockCore(BlockSyntax? block); public AnonymousFunctionExpressionSyntax AddBlockAttributeLists(params AttributeListSyntax[] items) => AddBlockAttributeListsCore(items); internal abstract AnonymousFunctionExpressionSyntax AddBlockAttributeListsCore(params AttributeListSyntax[] items); public AnonymousFunctionExpressionSyntax AddBlockStatements(params StatementSyntax[] items) => AddBlockStatementsCore(items); internal abstract AnonymousFunctionExpressionSyntax AddBlockStatementsCore(params StatementSyntax[] items); /// <summary> /// ExpressionSyntax node representing the body of the anonymous function. /// Only one of Block or ExpressionBody will be non-null. /// </summary> public abstract ExpressionSyntax? ExpressionBody { get; } public AnonymousFunctionExpressionSyntax WithExpressionBody(ExpressionSyntax? expressionBody) => WithExpressionBodyCore(expressionBody); internal abstract AnonymousFunctionExpressionSyntax WithExpressionBodyCore(ExpressionSyntax? expressionBody); } /// <summary>Class which represents the syntax node for anonymous method expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.AnonymousMethodExpression"/></description></item> /// </list> /// </remarks> public sealed partial class AnonymousMethodExpressionSyntax : AnonymousFunctionExpressionSyntax { private ParameterListSyntax? parameterList; private BlockSyntax? block; private ExpressionSyntax? expressionBody; internal AnonymousMethodExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(0); return slot != null ? new SyntaxTokenList(this, slot, Position, 0) : default; } } /// <summary>SyntaxToken representing the delegate keyword.</summary> public SyntaxToken DelegateKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.AnonymousMethodExpressionSyntax)this.Green).delegateKeyword, GetChildPosition(1), GetChildIndex(1)); /// <summary>List of parameters of the anonymous method expression, or null if there no parameters are specified.</summary> public ParameterListSyntax? ParameterList => GetRed(ref this.parameterList, 2); /// <summary> /// BlockSyntax node representing the body of the anonymous function. /// This will never be null. /// </summary> public override BlockSyntax Block => GetRed(ref this.block, 3)!; /// <summary> /// Inherited from AnonymousFunctionExpressionSyntax, but not used for /// AnonymousMethodExpressionSyntax. This will always be null. /// </summary> public override ExpressionSyntax? ExpressionBody => GetRed(ref this.expressionBody, 4); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 2 => GetRed(ref this.parameterList, 2), 3 => GetRed(ref this.block, 3)!, 4 => GetRed(ref this.expressionBody, 4), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 2 => this.parameterList, 3 => this.block, 4 => this.expressionBody, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitAnonymousMethodExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitAnonymousMethodExpression(this); public AnonymousMethodExpressionSyntax Update(SyntaxTokenList modifiers, SyntaxToken delegateKeyword, ParameterListSyntax? parameterList, BlockSyntax block, ExpressionSyntax? expressionBody) { if (modifiers != this.Modifiers || delegateKeyword != this.DelegateKeyword || parameterList != this.ParameterList || block != this.Block || expressionBody != this.ExpressionBody) { var newNode = SyntaxFactory.AnonymousMethodExpression(modifiers, delegateKeyword, parameterList, block, expressionBody); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override AnonymousFunctionExpressionSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new AnonymousMethodExpressionSyntax WithModifiers(SyntaxTokenList modifiers) => Update(modifiers, this.DelegateKeyword, this.ParameterList, this.Block, this.ExpressionBody); public AnonymousMethodExpressionSyntax WithDelegateKeyword(SyntaxToken delegateKeyword) => Update(this.Modifiers, delegateKeyword, this.ParameterList, this.Block, this.ExpressionBody); public AnonymousMethodExpressionSyntax WithParameterList(ParameterListSyntax? parameterList) => Update(this.Modifiers, this.DelegateKeyword, parameterList, this.Block, this.ExpressionBody); internal override AnonymousFunctionExpressionSyntax WithBlockCore(BlockSyntax? block) => WithBlock(block ?? throw new ArgumentNullException(nameof(block))); public new AnonymousMethodExpressionSyntax WithBlock(BlockSyntax block) => Update(this.Modifiers, this.DelegateKeyword, this.ParameterList, block, this.ExpressionBody); internal override AnonymousFunctionExpressionSyntax WithExpressionBodyCore(ExpressionSyntax? expressionBody) => WithExpressionBody(expressionBody); public new AnonymousMethodExpressionSyntax WithExpressionBody(ExpressionSyntax? expressionBody) => Update(this.Modifiers, this.DelegateKeyword, this.ParameterList, this.Block, expressionBody); internal override AnonymousFunctionExpressionSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new AnonymousMethodExpressionSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); public AnonymousMethodExpressionSyntax AddParameterListParameters(params ParameterSyntax[] items) { var parameterList = this.ParameterList ?? SyntaxFactory.ParameterList(); return WithParameterList(parameterList.WithParameters(parameterList.Parameters.AddRange(items))); } internal override AnonymousFunctionExpressionSyntax AddBlockAttributeListsCore(params AttributeListSyntax[] items) => AddBlockAttributeLists(items); public new AnonymousMethodExpressionSyntax AddBlockAttributeLists(params AttributeListSyntax[] items) => WithBlock(this.Block.WithAttributeLists(this.Block.AttributeLists.AddRange(items))); internal override AnonymousFunctionExpressionSyntax AddBlockStatementsCore(params StatementSyntax[] items) => AddBlockStatements(items); public new AnonymousMethodExpressionSyntax AddBlockStatements(params StatementSyntax[] items) => WithBlock(this.Block.WithStatements(this.Block.Statements.AddRange(items))); } /// <summary>Provides the base class from which the classes that represent lambda expressions are derived.</summary> public abstract partial class LambdaExpressionSyntax : AnonymousFunctionExpressionSyntax { internal LambdaExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public abstract SyntaxList<AttributeListSyntax> AttributeLists { get; } public LambdaExpressionSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeListsCore(attributeLists); internal abstract LambdaExpressionSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists); public LambdaExpressionSyntax AddAttributeLists(params AttributeListSyntax[] items) => AddAttributeListsCore(items); internal abstract LambdaExpressionSyntax AddAttributeListsCore(params AttributeListSyntax[] items); /// <summary>SyntaxToken representing equals greater than.</summary> public abstract SyntaxToken ArrowToken { get; } public LambdaExpressionSyntax WithArrowToken(SyntaxToken arrowToken) => WithArrowTokenCore(arrowToken); internal abstract LambdaExpressionSyntax WithArrowTokenCore(SyntaxToken arrowToken); public new LambdaExpressionSyntax WithModifiers(SyntaxTokenList modifiers) => (LambdaExpressionSyntax)WithModifiersCore(modifiers); public new LambdaExpressionSyntax WithBlock(BlockSyntax? block) => (LambdaExpressionSyntax)WithBlockCore(block); public new LambdaExpressionSyntax WithExpressionBody(ExpressionSyntax? expressionBody) => (LambdaExpressionSyntax)WithExpressionBodyCore(expressionBody); public new LambdaExpressionSyntax AddModifiers(params SyntaxToken[] items) => (LambdaExpressionSyntax)AddModifiersCore(items); public new AnonymousFunctionExpressionSyntax AddBlockAttributeLists(params AttributeListSyntax[] items) => AddBlockAttributeListsCore(items); public new AnonymousFunctionExpressionSyntax AddBlockStatements(params StatementSyntax[] items) => AddBlockStatementsCore(items); } /// <summary>Class which represents the syntax node for a simple lambda expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.SimpleLambdaExpression"/></description></item> /// </list> /// </remarks> public sealed partial class SimpleLambdaExpressionSyntax : LambdaExpressionSyntax { private SyntaxNode? attributeLists; private ParameterSyntax? parameter; private BlockSyntax? block; private ExpressionSyntax? expressionBody; internal SimpleLambdaExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } /// <summary>ParameterSyntax node representing the parameter of the lambda expression.</summary> public ParameterSyntax Parameter => GetRed(ref this.parameter, 2)!; /// <summary>SyntaxToken representing equals greater than.</summary> public override SyntaxToken ArrowToken => new SyntaxToken(this, ((Syntax.InternalSyntax.SimpleLambdaExpressionSyntax)this.Green).arrowToken, GetChildPosition(3), GetChildIndex(3)); /// <summary> /// BlockSyntax node representing the body of the lambda. /// Only one of Block or ExpressionBody will be non-null. /// </summary> public override BlockSyntax? Block => GetRed(ref this.block, 4); /// <summary> /// ExpressionSyntax node representing the body of the lambda. /// Only one of Block or ExpressionBody will be non-null. /// </summary> public override ExpressionSyntax? ExpressionBody => GetRed(ref this.expressionBody, 5); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.parameter, 2)!, 4 => GetRed(ref this.block, 4), 5 => GetRed(ref this.expressionBody, 5), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.parameter, 4 => this.block, 5 => this.expressionBody, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitSimpleLambdaExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitSimpleLambdaExpression(this); public SimpleLambdaExpressionSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, ParameterSyntax parameter, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || parameter != this.Parameter || arrowToken != this.ArrowToken || block != this.Block || expressionBody != this.ExpressionBody) { var newNode = SyntaxFactory.SimpleLambdaExpression(attributeLists, modifiers, parameter, arrowToken, block, expressionBody); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override LambdaExpressionSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new SimpleLambdaExpressionSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.Parameter, this.ArrowToken, this.Block, this.ExpressionBody); internal override AnonymousFunctionExpressionSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new SimpleLambdaExpressionSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.Parameter, this.ArrowToken, this.Block, this.ExpressionBody); public SimpleLambdaExpressionSyntax WithParameter(ParameterSyntax parameter) => Update(this.AttributeLists, this.Modifiers, parameter, this.ArrowToken, this.Block, this.ExpressionBody); internal override LambdaExpressionSyntax WithArrowTokenCore(SyntaxToken arrowToken) => WithArrowToken(arrowToken); public new SimpleLambdaExpressionSyntax WithArrowToken(SyntaxToken arrowToken) => Update(this.AttributeLists, this.Modifiers, this.Parameter, arrowToken, this.Block, this.ExpressionBody); internal override AnonymousFunctionExpressionSyntax WithBlockCore(BlockSyntax? block) => WithBlock(block); public new SimpleLambdaExpressionSyntax WithBlock(BlockSyntax? block) => Update(this.AttributeLists, this.Modifiers, this.Parameter, this.ArrowToken, block, this.ExpressionBody); internal override AnonymousFunctionExpressionSyntax WithExpressionBodyCore(ExpressionSyntax? expressionBody) => WithExpressionBody(expressionBody); public new SimpleLambdaExpressionSyntax WithExpressionBody(ExpressionSyntax? expressionBody) => Update(this.AttributeLists, this.Modifiers, this.Parameter, this.ArrowToken, this.Block, expressionBody); internal override LambdaExpressionSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new SimpleLambdaExpressionSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override AnonymousFunctionExpressionSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new SimpleLambdaExpressionSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); public SimpleLambdaExpressionSyntax AddParameterAttributeLists(params AttributeListSyntax[] items) => WithParameter(this.Parameter.WithAttributeLists(this.Parameter.AttributeLists.AddRange(items))); public SimpleLambdaExpressionSyntax AddParameterModifiers(params SyntaxToken[] items) => WithParameter(this.Parameter.WithModifiers(this.Parameter.Modifiers.AddRange(items))); internal override AnonymousFunctionExpressionSyntax AddBlockAttributeListsCore(params AttributeListSyntax[] items) => AddBlockAttributeLists(items); public new SimpleLambdaExpressionSyntax AddBlockAttributeLists(params AttributeListSyntax[] items) { var block = this.Block ?? SyntaxFactory.Block(); return WithBlock(block.WithAttributeLists(block.AttributeLists.AddRange(items))); } internal override AnonymousFunctionExpressionSyntax AddBlockStatementsCore(params StatementSyntax[] items) => AddBlockStatements(items); public new SimpleLambdaExpressionSyntax AddBlockStatements(params StatementSyntax[] items) { var block = this.Block ?? SyntaxFactory.Block(); return WithBlock(block.WithStatements(block.Statements.AddRange(items))); } } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.RefExpression"/></description></item> /// </list> /// </remarks> public sealed partial class RefExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? expression; internal RefExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken RefKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.RefExpressionSyntax)this.Green).refKeyword, Position, 0); public ExpressionSyntax Expression => GetRed(ref this.expression, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.expression, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.expression : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitRefExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitRefExpression(this); public RefExpressionSyntax Update(SyntaxToken refKeyword, ExpressionSyntax expression) { if (refKeyword != this.RefKeyword || expression != this.Expression) { var newNode = SyntaxFactory.RefExpression(refKeyword, expression); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public RefExpressionSyntax WithRefKeyword(SyntaxToken refKeyword) => Update(refKeyword, this.Expression); public RefExpressionSyntax WithExpression(ExpressionSyntax expression) => Update(this.RefKeyword, expression); } /// <summary>Class which represents the syntax node for parenthesized lambda expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ParenthesizedLambdaExpression"/></description></item> /// </list> /// </remarks> public sealed partial class ParenthesizedLambdaExpressionSyntax : LambdaExpressionSyntax { private SyntaxNode? attributeLists; private TypeSyntax? returnType; private ParameterListSyntax? parameterList; private BlockSyntax? block; private ExpressionSyntax? expressionBody; internal ParenthesizedLambdaExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public TypeSyntax? ReturnType => GetRed(ref this.returnType, 2); /// <summary>ParameterListSyntax node representing the list of parameters for the lambda expression.</summary> public ParameterListSyntax ParameterList => GetRed(ref this.parameterList, 3)!; /// <summary>SyntaxToken representing equals greater than.</summary> public override SyntaxToken ArrowToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ParenthesizedLambdaExpressionSyntax)this.Green).arrowToken, GetChildPosition(4), GetChildIndex(4)); /// <summary> /// BlockSyntax node representing the body of the lambda. /// Only one of Block or ExpressionBody will be non-null. /// </summary> public override BlockSyntax? Block => GetRed(ref this.block, 5); /// <summary> /// ExpressionSyntax node representing the body of the lambda. /// Only one of Block or ExpressionBody will be non-null. /// </summary> public override ExpressionSyntax? ExpressionBody => GetRed(ref this.expressionBody, 6); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.returnType, 2), 3 => GetRed(ref this.parameterList, 3)!, 5 => GetRed(ref this.block, 5), 6 => GetRed(ref this.expressionBody, 6), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.returnType, 3 => this.parameterList, 5 => this.block, 6 => this.expressionBody, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitParenthesizedLambdaExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitParenthesizedLambdaExpression(this); public ParenthesizedLambdaExpressionSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, TypeSyntax? returnType, ParameterListSyntax parameterList, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || returnType != this.ReturnType || parameterList != this.ParameterList || arrowToken != this.ArrowToken || block != this.Block || expressionBody != this.ExpressionBody) { var newNode = SyntaxFactory.ParenthesizedLambdaExpression(attributeLists, modifiers, returnType, parameterList, arrowToken, block, expressionBody); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override LambdaExpressionSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new ParenthesizedLambdaExpressionSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.ReturnType, this.ParameterList, this.ArrowToken, this.Block, this.ExpressionBody); internal override AnonymousFunctionExpressionSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new ParenthesizedLambdaExpressionSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.ReturnType, this.ParameterList, this.ArrowToken, this.Block, this.ExpressionBody); public ParenthesizedLambdaExpressionSyntax WithReturnType(TypeSyntax? returnType) => Update(this.AttributeLists, this.Modifiers, returnType, this.ParameterList, this.ArrowToken, this.Block, this.ExpressionBody); public ParenthesizedLambdaExpressionSyntax WithParameterList(ParameterListSyntax parameterList) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, parameterList, this.ArrowToken, this.Block, this.ExpressionBody); internal override LambdaExpressionSyntax WithArrowTokenCore(SyntaxToken arrowToken) => WithArrowToken(arrowToken); public new ParenthesizedLambdaExpressionSyntax WithArrowToken(SyntaxToken arrowToken) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.ParameterList, arrowToken, this.Block, this.ExpressionBody); internal override AnonymousFunctionExpressionSyntax WithBlockCore(BlockSyntax? block) => WithBlock(block); public new ParenthesizedLambdaExpressionSyntax WithBlock(BlockSyntax? block) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.ParameterList, this.ArrowToken, block, this.ExpressionBody); internal override AnonymousFunctionExpressionSyntax WithExpressionBodyCore(ExpressionSyntax? expressionBody) => WithExpressionBody(expressionBody); public new ParenthesizedLambdaExpressionSyntax WithExpressionBody(ExpressionSyntax? expressionBody) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.ParameterList, this.ArrowToken, this.Block, expressionBody); internal override LambdaExpressionSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new ParenthesizedLambdaExpressionSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override AnonymousFunctionExpressionSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new ParenthesizedLambdaExpressionSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); public ParenthesizedLambdaExpressionSyntax AddParameterListParameters(params ParameterSyntax[] items) => WithParameterList(this.ParameterList.WithParameters(this.ParameterList.Parameters.AddRange(items))); internal override AnonymousFunctionExpressionSyntax AddBlockAttributeListsCore(params AttributeListSyntax[] items) => AddBlockAttributeLists(items); public new ParenthesizedLambdaExpressionSyntax AddBlockAttributeLists(params AttributeListSyntax[] items) { var block = this.Block ?? SyntaxFactory.Block(); return WithBlock(block.WithAttributeLists(block.AttributeLists.AddRange(items))); } internal override AnonymousFunctionExpressionSyntax AddBlockStatementsCore(params StatementSyntax[] items) => AddBlockStatements(items); public new ParenthesizedLambdaExpressionSyntax AddBlockStatements(params StatementSyntax[] items) { var block = this.Block ?? SyntaxFactory.Block(); return WithBlock(block.WithStatements(block.Statements.AddRange(items))); } } /// <summary>Class which represents the syntax node for initializer expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ObjectInitializerExpression"/></description></item> /// <item><description><see cref="SyntaxKind.CollectionInitializerExpression"/></description></item> /// <item><description><see cref="SyntaxKind.ArrayInitializerExpression"/></description></item> /// <item><description><see cref="SyntaxKind.ComplexElementInitializerExpression"/></description></item> /// <item><description><see cref="SyntaxKind.WithInitializerExpression"/></description></item> /// </list> /// </remarks> public sealed partial class InitializerExpressionSyntax : ExpressionSyntax { private SyntaxNode? expressions; internal InitializerExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the open brace.</summary> public SyntaxToken OpenBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.InitializerExpressionSyntax)this.Green).openBraceToken, Position, 0); /// <summary>SeparatedSyntaxList of ExpressionSyntax representing the list of expressions in the initializer expression.</summary> public SeparatedSyntaxList<ExpressionSyntax> Expressions { get { var red = GetRed(ref this.expressions, 1); return red != null ? new SeparatedSyntaxList<ExpressionSyntax>(red, GetChildIndex(1)) : default; } } /// <summary>SyntaxToken representing the close brace.</summary> public SyntaxToken CloseBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.InitializerExpressionSyntax)this.Green).closeBraceToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.expressions, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.expressions : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitInitializerExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitInitializerExpression(this); public InitializerExpressionSyntax Update(SyntaxToken openBraceToken, SeparatedSyntaxList<ExpressionSyntax> expressions, SyntaxToken closeBraceToken) { if (openBraceToken != this.OpenBraceToken || expressions != this.Expressions || closeBraceToken != this.CloseBraceToken) { var newNode = SyntaxFactory.InitializerExpression(this.Kind(), openBraceToken, expressions, closeBraceToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public InitializerExpressionSyntax WithOpenBraceToken(SyntaxToken openBraceToken) => Update(openBraceToken, this.Expressions, this.CloseBraceToken); public InitializerExpressionSyntax WithExpressions(SeparatedSyntaxList<ExpressionSyntax> expressions) => Update(this.OpenBraceToken, expressions, this.CloseBraceToken); public InitializerExpressionSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) => Update(this.OpenBraceToken, this.Expressions, closeBraceToken); public InitializerExpressionSyntax AddExpressions(params ExpressionSyntax[] items) => WithExpressions(this.Expressions.AddRange(items)); } public abstract partial class BaseObjectCreationExpressionSyntax : ExpressionSyntax { internal BaseObjectCreationExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the new keyword.</summary> public abstract SyntaxToken NewKeyword { get; } public BaseObjectCreationExpressionSyntax WithNewKeyword(SyntaxToken newKeyword) => WithNewKeywordCore(newKeyword); internal abstract BaseObjectCreationExpressionSyntax WithNewKeywordCore(SyntaxToken newKeyword); /// <summary>ArgumentListSyntax representing the list of arguments passed as part of the object creation expression.</summary> public abstract ArgumentListSyntax? ArgumentList { get; } public BaseObjectCreationExpressionSyntax WithArgumentList(ArgumentListSyntax? argumentList) => WithArgumentListCore(argumentList); internal abstract BaseObjectCreationExpressionSyntax WithArgumentListCore(ArgumentListSyntax? argumentList); public BaseObjectCreationExpressionSyntax AddArgumentListArguments(params ArgumentSyntax[] items) => AddArgumentListArgumentsCore(items); internal abstract BaseObjectCreationExpressionSyntax AddArgumentListArgumentsCore(params ArgumentSyntax[] items); /// <summary>InitializerExpressionSyntax representing the initializer expression for the object being created.</summary> public abstract InitializerExpressionSyntax? Initializer { get; } public BaseObjectCreationExpressionSyntax WithInitializer(InitializerExpressionSyntax? initializer) => WithInitializerCore(initializer); internal abstract BaseObjectCreationExpressionSyntax WithInitializerCore(InitializerExpressionSyntax? initializer); } /// <summary>Class which represents the syntax node for implicit object creation expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ImplicitObjectCreationExpression"/></description></item> /// </list> /// </remarks> public sealed partial class ImplicitObjectCreationExpressionSyntax : BaseObjectCreationExpressionSyntax { private ArgumentListSyntax? argumentList; private InitializerExpressionSyntax? initializer; internal ImplicitObjectCreationExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the new keyword.</summary> public override SyntaxToken NewKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ImplicitObjectCreationExpressionSyntax)this.Green).newKeyword, Position, 0); /// <summary>ArgumentListSyntax representing the list of arguments passed as part of the object creation expression.</summary> public override ArgumentListSyntax ArgumentList => GetRed(ref this.argumentList, 1)!; /// <summary>InitializerExpressionSyntax representing the initializer expression for the object being created.</summary> public override InitializerExpressionSyntax? Initializer => GetRed(ref this.initializer, 2); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 1 => GetRed(ref this.argumentList, 1)!, 2 => GetRed(ref this.initializer, 2), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 1 => this.argumentList, 2 => this.initializer, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitImplicitObjectCreationExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitImplicitObjectCreationExpression(this); public ImplicitObjectCreationExpressionSyntax Update(SyntaxToken newKeyword, ArgumentListSyntax argumentList, InitializerExpressionSyntax? initializer) { if (newKeyword != this.NewKeyword || argumentList != this.ArgumentList || initializer != this.Initializer) { var newNode = SyntaxFactory.ImplicitObjectCreationExpression(newKeyword, argumentList, initializer); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override BaseObjectCreationExpressionSyntax WithNewKeywordCore(SyntaxToken newKeyword) => WithNewKeyword(newKeyword); public new ImplicitObjectCreationExpressionSyntax WithNewKeyword(SyntaxToken newKeyword) => Update(newKeyword, this.ArgumentList, this.Initializer); internal override BaseObjectCreationExpressionSyntax WithArgumentListCore(ArgumentListSyntax? argumentList) => WithArgumentList(argumentList ?? throw new ArgumentNullException(nameof(argumentList))); public new ImplicitObjectCreationExpressionSyntax WithArgumentList(ArgumentListSyntax argumentList) => Update(this.NewKeyword, argumentList, this.Initializer); internal override BaseObjectCreationExpressionSyntax WithInitializerCore(InitializerExpressionSyntax? initializer) => WithInitializer(initializer); public new ImplicitObjectCreationExpressionSyntax WithInitializer(InitializerExpressionSyntax? initializer) => Update(this.NewKeyword, this.ArgumentList, initializer); internal override BaseObjectCreationExpressionSyntax AddArgumentListArgumentsCore(params ArgumentSyntax[] items) => AddArgumentListArguments(items); public new ImplicitObjectCreationExpressionSyntax AddArgumentListArguments(params ArgumentSyntax[] items) => WithArgumentList(this.ArgumentList.WithArguments(this.ArgumentList.Arguments.AddRange(items))); } /// <summary>Class which represents the syntax node for object creation expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ObjectCreationExpression"/></description></item> /// </list> /// </remarks> public sealed partial class ObjectCreationExpressionSyntax : BaseObjectCreationExpressionSyntax { private TypeSyntax? type; private ArgumentListSyntax? argumentList; private InitializerExpressionSyntax? initializer; internal ObjectCreationExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the new keyword.</summary> public override SyntaxToken NewKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ObjectCreationExpressionSyntax)this.Green).newKeyword, Position, 0); /// <summary>TypeSyntax representing the type of the object being created.</summary> public TypeSyntax Type => GetRed(ref this.type, 1)!; /// <summary>ArgumentListSyntax representing the list of arguments passed as part of the object creation expression.</summary> public override ArgumentListSyntax? ArgumentList => GetRed(ref this.argumentList, 2); /// <summary>InitializerExpressionSyntax representing the initializer expression for the object being created.</summary> public override InitializerExpressionSyntax? Initializer => GetRed(ref this.initializer, 3); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 1 => GetRed(ref this.type, 1)!, 2 => GetRed(ref this.argumentList, 2), 3 => GetRed(ref this.initializer, 3), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 1 => this.type, 2 => this.argumentList, 3 => this.initializer, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitObjectCreationExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitObjectCreationExpression(this); public ObjectCreationExpressionSyntax Update(SyntaxToken newKeyword, TypeSyntax type, ArgumentListSyntax? argumentList, InitializerExpressionSyntax? initializer) { if (newKeyword != this.NewKeyword || type != this.Type || argumentList != this.ArgumentList || initializer != this.Initializer) { var newNode = SyntaxFactory.ObjectCreationExpression(newKeyword, type, argumentList, initializer); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override BaseObjectCreationExpressionSyntax WithNewKeywordCore(SyntaxToken newKeyword) => WithNewKeyword(newKeyword); public new ObjectCreationExpressionSyntax WithNewKeyword(SyntaxToken newKeyword) => Update(newKeyword, this.Type, this.ArgumentList, this.Initializer); public ObjectCreationExpressionSyntax WithType(TypeSyntax type) => Update(this.NewKeyword, type, this.ArgumentList, this.Initializer); internal override BaseObjectCreationExpressionSyntax WithArgumentListCore(ArgumentListSyntax? argumentList) => WithArgumentList(argumentList); public new ObjectCreationExpressionSyntax WithArgumentList(ArgumentListSyntax? argumentList) => Update(this.NewKeyword, this.Type, argumentList, this.Initializer); internal override BaseObjectCreationExpressionSyntax WithInitializerCore(InitializerExpressionSyntax? initializer) => WithInitializer(initializer); public new ObjectCreationExpressionSyntax WithInitializer(InitializerExpressionSyntax? initializer) => Update(this.NewKeyword, this.Type, this.ArgumentList, initializer); internal override BaseObjectCreationExpressionSyntax AddArgumentListArgumentsCore(params ArgumentSyntax[] items) => AddArgumentListArguments(items); public new ObjectCreationExpressionSyntax AddArgumentListArguments(params ArgumentSyntax[] items) { var argumentList = this.ArgumentList ?? SyntaxFactory.ArgumentList(); return WithArgumentList(argumentList.WithArguments(argumentList.Arguments.AddRange(items))); } } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.WithExpression"/></description></item> /// </list> /// </remarks> public sealed partial class WithExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? expression; private InitializerExpressionSyntax? initializer; internal WithExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public ExpressionSyntax Expression => GetRedAtZero(ref this.expression)!; public SyntaxToken WithKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.WithExpressionSyntax)this.Green).withKeyword, GetChildPosition(1), GetChildIndex(1)); /// <summary>InitializerExpressionSyntax representing the initializer expression for the with expression.</summary> public InitializerExpressionSyntax Initializer => GetRed(ref this.initializer, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.expression)!, 2 => GetRed(ref this.initializer, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.expression, 2 => this.initializer, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitWithExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitWithExpression(this); public WithExpressionSyntax Update(ExpressionSyntax expression, SyntaxToken withKeyword, InitializerExpressionSyntax initializer) { if (expression != this.Expression || withKeyword != this.WithKeyword || initializer != this.Initializer) { var newNode = SyntaxFactory.WithExpression(expression, withKeyword, initializer); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public WithExpressionSyntax WithExpression(ExpressionSyntax expression) => Update(expression, this.WithKeyword, this.Initializer); public WithExpressionSyntax WithWithKeyword(SyntaxToken withKeyword) => Update(this.Expression, withKeyword, this.Initializer); public WithExpressionSyntax WithInitializer(InitializerExpressionSyntax initializer) => Update(this.Expression, this.WithKeyword, initializer); public WithExpressionSyntax AddInitializerExpressions(params ExpressionSyntax[] items) => WithInitializer(this.Initializer.WithExpressions(this.Initializer.Expressions.AddRange(items))); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.AnonymousObjectMemberDeclarator"/></description></item> /// </list> /// </remarks> public sealed partial class AnonymousObjectMemberDeclaratorSyntax : CSharpSyntaxNode { private NameEqualsSyntax? nameEquals; private ExpressionSyntax? expression; internal AnonymousObjectMemberDeclaratorSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>NameEqualsSyntax representing the optional name of the member being initialized.</summary> public NameEqualsSyntax? NameEquals => GetRedAtZero(ref this.nameEquals); /// <summary>ExpressionSyntax representing the value the member is initialized with.</summary> public ExpressionSyntax Expression => GetRed(ref this.expression, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.nameEquals), 1 => GetRed(ref this.expression, 1)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.nameEquals, 1 => this.expression, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitAnonymousObjectMemberDeclarator(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitAnonymousObjectMemberDeclarator(this); public AnonymousObjectMemberDeclaratorSyntax Update(NameEqualsSyntax? nameEquals, ExpressionSyntax expression) { if (nameEquals != this.NameEquals || expression != this.Expression) { var newNode = SyntaxFactory.AnonymousObjectMemberDeclarator(nameEquals, expression); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public AnonymousObjectMemberDeclaratorSyntax WithNameEquals(NameEqualsSyntax? nameEquals) => Update(nameEquals, this.Expression); public AnonymousObjectMemberDeclaratorSyntax WithExpression(ExpressionSyntax expression) => Update(this.NameEquals, expression); } /// <summary>Class which represents the syntax node for anonymous object creation expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.AnonymousObjectCreationExpression"/></description></item> /// </list> /// </remarks> public sealed partial class AnonymousObjectCreationExpressionSyntax : ExpressionSyntax { private SyntaxNode? initializers; internal AnonymousObjectCreationExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the new keyword.</summary> public SyntaxToken NewKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.AnonymousObjectCreationExpressionSyntax)this.Green).newKeyword, Position, 0); /// <summary>SyntaxToken representing the open brace.</summary> public SyntaxToken OpenBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.AnonymousObjectCreationExpressionSyntax)this.Green).openBraceToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>SeparatedSyntaxList of AnonymousObjectMemberDeclaratorSyntax representing the list of object member initializers.</summary> public SeparatedSyntaxList<AnonymousObjectMemberDeclaratorSyntax> Initializers { get { var red = GetRed(ref this.initializers, 2); return red != null ? new SeparatedSyntaxList<AnonymousObjectMemberDeclaratorSyntax>(red, GetChildIndex(2)) : default; } } /// <summary>SyntaxToken representing the close brace.</summary> public SyntaxToken CloseBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.AnonymousObjectCreationExpressionSyntax)this.Green).closeBraceToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => index == 2 ? GetRed(ref this.initializers, 2)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 2 ? this.initializers : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitAnonymousObjectCreationExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitAnonymousObjectCreationExpression(this); public AnonymousObjectCreationExpressionSyntax Update(SyntaxToken newKeyword, SyntaxToken openBraceToken, SeparatedSyntaxList<AnonymousObjectMemberDeclaratorSyntax> initializers, SyntaxToken closeBraceToken) { if (newKeyword != this.NewKeyword || openBraceToken != this.OpenBraceToken || initializers != this.Initializers || closeBraceToken != this.CloseBraceToken) { var newNode = SyntaxFactory.AnonymousObjectCreationExpression(newKeyword, openBraceToken, initializers, closeBraceToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public AnonymousObjectCreationExpressionSyntax WithNewKeyword(SyntaxToken newKeyword) => Update(newKeyword, this.OpenBraceToken, this.Initializers, this.CloseBraceToken); public AnonymousObjectCreationExpressionSyntax WithOpenBraceToken(SyntaxToken openBraceToken) => Update(this.NewKeyword, openBraceToken, this.Initializers, this.CloseBraceToken); public AnonymousObjectCreationExpressionSyntax WithInitializers(SeparatedSyntaxList<AnonymousObjectMemberDeclaratorSyntax> initializers) => Update(this.NewKeyword, this.OpenBraceToken, initializers, this.CloseBraceToken); public AnonymousObjectCreationExpressionSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) => Update(this.NewKeyword, this.OpenBraceToken, this.Initializers, closeBraceToken); public AnonymousObjectCreationExpressionSyntax AddInitializers(params AnonymousObjectMemberDeclaratorSyntax[] items) => WithInitializers(this.Initializers.AddRange(items)); } /// <summary>Class which represents the syntax node for array creation expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ArrayCreationExpression"/></description></item> /// </list> /// </remarks> public sealed partial class ArrayCreationExpressionSyntax : ExpressionSyntax { private ArrayTypeSyntax? type; private InitializerExpressionSyntax? initializer; internal ArrayCreationExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the new keyword.</summary> public SyntaxToken NewKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ArrayCreationExpressionSyntax)this.Green).newKeyword, Position, 0); /// <summary>ArrayTypeSyntax node representing the type of the array.</summary> public ArrayTypeSyntax Type => GetRed(ref this.type, 1)!; /// <summary>InitializerExpressionSyntax node representing the initializer of the array creation expression.</summary> public InitializerExpressionSyntax? Initializer => GetRed(ref this.initializer, 2); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 1 => GetRed(ref this.type, 1)!, 2 => GetRed(ref this.initializer, 2), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 1 => this.type, 2 => this.initializer, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitArrayCreationExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitArrayCreationExpression(this); public ArrayCreationExpressionSyntax Update(SyntaxToken newKeyword, ArrayTypeSyntax type, InitializerExpressionSyntax? initializer) { if (newKeyword != this.NewKeyword || type != this.Type || initializer != this.Initializer) { var newNode = SyntaxFactory.ArrayCreationExpression(newKeyword, type, initializer); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ArrayCreationExpressionSyntax WithNewKeyword(SyntaxToken newKeyword) => Update(newKeyword, this.Type, this.Initializer); public ArrayCreationExpressionSyntax WithType(ArrayTypeSyntax type) => Update(this.NewKeyword, type, this.Initializer); public ArrayCreationExpressionSyntax WithInitializer(InitializerExpressionSyntax? initializer) => Update(this.NewKeyword, this.Type, initializer); public ArrayCreationExpressionSyntax AddTypeRankSpecifiers(params ArrayRankSpecifierSyntax[] items) => WithType(this.Type.WithRankSpecifiers(this.Type.RankSpecifiers.AddRange(items))); } /// <summary>Class which represents the syntax node for implicit array creation expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ImplicitArrayCreationExpression"/></description></item> /// </list> /// </remarks> public sealed partial class ImplicitArrayCreationExpressionSyntax : ExpressionSyntax { private InitializerExpressionSyntax? initializer; internal ImplicitArrayCreationExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the new keyword.</summary> public SyntaxToken NewKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ImplicitArrayCreationExpressionSyntax)this.Green).newKeyword, Position, 0); /// <summary>SyntaxToken representing the open bracket.</summary> public SyntaxToken OpenBracketToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ImplicitArrayCreationExpressionSyntax)this.Green).openBracketToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>SyntaxList of SyntaxToken representing the commas in the implicit array creation expression.</summary> public SyntaxTokenList Commas { get { var slot = this.Green.GetSlot(2); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(2), GetChildIndex(2)) : default; } } /// <summary>SyntaxToken representing the close bracket.</summary> public SyntaxToken CloseBracketToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ImplicitArrayCreationExpressionSyntax)this.Green).closeBracketToken, GetChildPosition(3), GetChildIndex(3)); /// <summary>InitializerExpressionSyntax representing the initializer expression of the implicit array creation expression.</summary> public InitializerExpressionSyntax Initializer => GetRed(ref this.initializer, 4)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 4 ? GetRed(ref this.initializer, 4)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 4 ? this.initializer : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitImplicitArrayCreationExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitImplicitArrayCreationExpression(this); public ImplicitArrayCreationExpressionSyntax Update(SyntaxToken newKeyword, SyntaxToken openBracketToken, SyntaxTokenList commas, SyntaxToken closeBracketToken, InitializerExpressionSyntax initializer) { if (newKeyword != this.NewKeyword || openBracketToken != this.OpenBracketToken || commas != this.Commas || closeBracketToken != this.CloseBracketToken || initializer != this.Initializer) { var newNode = SyntaxFactory.ImplicitArrayCreationExpression(newKeyword, openBracketToken, commas, closeBracketToken, initializer); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ImplicitArrayCreationExpressionSyntax WithNewKeyword(SyntaxToken newKeyword) => Update(newKeyword, this.OpenBracketToken, this.Commas, this.CloseBracketToken, this.Initializer); public ImplicitArrayCreationExpressionSyntax WithOpenBracketToken(SyntaxToken openBracketToken) => Update(this.NewKeyword, openBracketToken, this.Commas, this.CloseBracketToken, this.Initializer); public ImplicitArrayCreationExpressionSyntax WithCommas(SyntaxTokenList commas) => Update(this.NewKeyword, this.OpenBracketToken, commas, this.CloseBracketToken, this.Initializer); public ImplicitArrayCreationExpressionSyntax WithCloseBracketToken(SyntaxToken closeBracketToken) => Update(this.NewKeyword, this.OpenBracketToken, this.Commas, closeBracketToken, this.Initializer); public ImplicitArrayCreationExpressionSyntax WithInitializer(InitializerExpressionSyntax initializer) => Update(this.NewKeyword, this.OpenBracketToken, this.Commas, this.CloseBracketToken, initializer); public ImplicitArrayCreationExpressionSyntax AddCommas(params SyntaxToken[] items) => WithCommas(this.Commas.AddRange(items)); public ImplicitArrayCreationExpressionSyntax AddInitializerExpressions(params ExpressionSyntax[] items) => WithInitializer(this.Initializer.WithExpressions(this.Initializer.Expressions.AddRange(items))); } /// <summary>Class which represents the syntax node for stackalloc array creation expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.StackAllocArrayCreationExpression"/></description></item> /// </list> /// </remarks> public sealed partial class StackAllocArrayCreationExpressionSyntax : ExpressionSyntax { private TypeSyntax? type; private InitializerExpressionSyntax? initializer; internal StackAllocArrayCreationExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the stackalloc keyword.</summary> public SyntaxToken StackAllocKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.StackAllocArrayCreationExpressionSyntax)this.Green).stackAllocKeyword, Position, 0); /// <summary>TypeSyntax node representing the type of the stackalloc array.</summary> public TypeSyntax Type => GetRed(ref this.type, 1)!; /// <summary>InitializerExpressionSyntax node representing the initializer of the stackalloc array creation expression.</summary> public InitializerExpressionSyntax? Initializer => GetRed(ref this.initializer, 2); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 1 => GetRed(ref this.type, 1)!, 2 => GetRed(ref this.initializer, 2), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 1 => this.type, 2 => this.initializer, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitStackAllocArrayCreationExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitStackAllocArrayCreationExpression(this); public StackAllocArrayCreationExpressionSyntax Update(SyntaxToken stackAllocKeyword, TypeSyntax type, InitializerExpressionSyntax? initializer) { if (stackAllocKeyword != this.StackAllocKeyword || type != this.Type || initializer != this.Initializer) { var newNode = SyntaxFactory.StackAllocArrayCreationExpression(stackAllocKeyword, type, initializer); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public StackAllocArrayCreationExpressionSyntax WithStackAllocKeyword(SyntaxToken stackAllocKeyword) => Update(stackAllocKeyword, this.Type, this.Initializer); public StackAllocArrayCreationExpressionSyntax WithType(TypeSyntax type) => Update(this.StackAllocKeyword, type, this.Initializer); public StackAllocArrayCreationExpressionSyntax WithInitializer(InitializerExpressionSyntax? initializer) => Update(this.StackAllocKeyword, this.Type, initializer); } /// <summary>Class which represents the syntax node for implicit stackalloc array creation expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ImplicitStackAllocArrayCreationExpression"/></description></item> /// </list> /// </remarks> public sealed partial class ImplicitStackAllocArrayCreationExpressionSyntax : ExpressionSyntax { private InitializerExpressionSyntax? initializer; internal ImplicitStackAllocArrayCreationExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the stackalloc keyword.</summary> public SyntaxToken StackAllocKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ImplicitStackAllocArrayCreationExpressionSyntax)this.Green).stackAllocKeyword, Position, 0); /// <summary>SyntaxToken representing the open bracket.</summary> public SyntaxToken OpenBracketToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ImplicitStackAllocArrayCreationExpressionSyntax)this.Green).openBracketToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>SyntaxToken representing the close bracket.</summary> public SyntaxToken CloseBracketToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ImplicitStackAllocArrayCreationExpressionSyntax)this.Green).closeBracketToken, GetChildPosition(2), GetChildIndex(2)); /// <summary>InitializerExpressionSyntax representing the initializer expression of the implicit stackalloc array creation expression.</summary> public InitializerExpressionSyntax Initializer => GetRed(ref this.initializer, 3)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 3 ? GetRed(ref this.initializer, 3)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 3 ? this.initializer : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitImplicitStackAllocArrayCreationExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitImplicitStackAllocArrayCreationExpression(this); public ImplicitStackAllocArrayCreationExpressionSyntax Update(SyntaxToken stackAllocKeyword, SyntaxToken openBracketToken, SyntaxToken closeBracketToken, InitializerExpressionSyntax initializer) { if (stackAllocKeyword != this.StackAllocKeyword || openBracketToken != this.OpenBracketToken || closeBracketToken != this.CloseBracketToken || initializer != this.Initializer) { var newNode = SyntaxFactory.ImplicitStackAllocArrayCreationExpression(stackAllocKeyword, openBracketToken, closeBracketToken, initializer); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ImplicitStackAllocArrayCreationExpressionSyntax WithStackAllocKeyword(SyntaxToken stackAllocKeyword) => Update(stackAllocKeyword, this.OpenBracketToken, this.CloseBracketToken, this.Initializer); public ImplicitStackAllocArrayCreationExpressionSyntax WithOpenBracketToken(SyntaxToken openBracketToken) => Update(this.StackAllocKeyword, openBracketToken, this.CloseBracketToken, this.Initializer); public ImplicitStackAllocArrayCreationExpressionSyntax WithCloseBracketToken(SyntaxToken closeBracketToken) => Update(this.StackAllocKeyword, this.OpenBracketToken, closeBracketToken, this.Initializer); public ImplicitStackAllocArrayCreationExpressionSyntax WithInitializer(InitializerExpressionSyntax initializer) => Update(this.StackAllocKeyword, this.OpenBracketToken, this.CloseBracketToken, initializer); public ImplicitStackAllocArrayCreationExpressionSyntax AddInitializerExpressions(params ExpressionSyntax[] items) => WithInitializer(this.Initializer.WithExpressions(this.Initializer.Expressions.AddRange(items))); } public abstract partial class QueryClauseSyntax : CSharpSyntaxNode { internal QueryClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } } public abstract partial class SelectOrGroupClauseSyntax : CSharpSyntaxNode { internal SelectOrGroupClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.QueryExpression"/></description></item> /// </list> /// </remarks> public sealed partial class QueryExpressionSyntax : ExpressionSyntax { private FromClauseSyntax? fromClause; private QueryBodySyntax? body; internal QueryExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public FromClauseSyntax FromClause => GetRedAtZero(ref this.fromClause)!; public QueryBodySyntax Body => GetRed(ref this.body, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.fromClause)!, 1 => GetRed(ref this.body, 1)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.fromClause, 1 => this.body, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitQueryExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitQueryExpression(this); public QueryExpressionSyntax Update(FromClauseSyntax fromClause, QueryBodySyntax body) { if (fromClause != this.FromClause || body != this.Body) { var newNode = SyntaxFactory.QueryExpression(fromClause, body); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public QueryExpressionSyntax WithFromClause(FromClauseSyntax fromClause) => Update(fromClause, this.Body); public QueryExpressionSyntax WithBody(QueryBodySyntax body) => Update(this.FromClause, body); public QueryExpressionSyntax AddBodyClauses(params QueryClauseSyntax[] items) => WithBody(this.Body.WithClauses(this.Body.Clauses.AddRange(items))); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.QueryBody"/></description></item> /// </list> /// </remarks> public sealed partial class QueryBodySyntax : CSharpSyntaxNode { private SyntaxNode? clauses; private SelectOrGroupClauseSyntax? selectOrGroup; private QueryContinuationSyntax? continuation; internal QueryBodySyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxList<QueryClauseSyntax> Clauses => new SyntaxList<QueryClauseSyntax>(GetRed(ref this.clauses, 0)); public SelectOrGroupClauseSyntax SelectOrGroup => GetRed(ref this.selectOrGroup, 1)!; public QueryContinuationSyntax? Continuation => GetRed(ref this.continuation, 2); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.clauses)!, 1 => GetRed(ref this.selectOrGroup, 1)!, 2 => GetRed(ref this.continuation, 2), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.clauses, 1 => this.selectOrGroup, 2 => this.continuation, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitQueryBody(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitQueryBody(this); public QueryBodySyntax Update(SyntaxList<QueryClauseSyntax> clauses, SelectOrGroupClauseSyntax selectOrGroup, QueryContinuationSyntax? continuation) { if (clauses != this.Clauses || selectOrGroup != this.SelectOrGroup || continuation != this.Continuation) { var newNode = SyntaxFactory.QueryBody(clauses, selectOrGroup, continuation); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public QueryBodySyntax WithClauses(SyntaxList<QueryClauseSyntax> clauses) => Update(clauses, this.SelectOrGroup, this.Continuation); public QueryBodySyntax WithSelectOrGroup(SelectOrGroupClauseSyntax selectOrGroup) => Update(this.Clauses, selectOrGroup, this.Continuation); public QueryBodySyntax WithContinuation(QueryContinuationSyntax? continuation) => Update(this.Clauses, this.SelectOrGroup, continuation); public QueryBodySyntax AddClauses(params QueryClauseSyntax[] items) => WithClauses(this.Clauses.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.FromClause"/></description></item> /// </list> /// </remarks> public sealed partial class FromClauseSyntax : QueryClauseSyntax { private TypeSyntax? type; private ExpressionSyntax? expression; internal FromClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken FromKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.FromClauseSyntax)this.Green).fromKeyword, Position, 0); public TypeSyntax? Type => GetRed(ref this.type, 1); /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.FromClauseSyntax)this.Green).identifier, GetChildPosition(2), GetChildIndex(2)); public SyntaxToken InKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.FromClauseSyntax)this.Green).inKeyword, GetChildPosition(3), GetChildIndex(3)); public ExpressionSyntax Expression => GetRed(ref this.expression, 4)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 1 => GetRed(ref this.type, 1), 4 => GetRed(ref this.expression, 4)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 1 => this.type, 4 => this.expression, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitFromClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitFromClause(this); public FromClauseSyntax Update(SyntaxToken fromKeyword, TypeSyntax? type, SyntaxToken identifier, SyntaxToken inKeyword, ExpressionSyntax expression) { if (fromKeyword != this.FromKeyword || type != this.Type || identifier != this.Identifier || inKeyword != this.InKeyword || expression != this.Expression) { var newNode = SyntaxFactory.FromClause(fromKeyword, type, identifier, inKeyword, expression); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public FromClauseSyntax WithFromKeyword(SyntaxToken fromKeyword) => Update(fromKeyword, this.Type, this.Identifier, this.InKeyword, this.Expression); public FromClauseSyntax WithType(TypeSyntax? type) => Update(this.FromKeyword, type, this.Identifier, this.InKeyword, this.Expression); public FromClauseSyntax WithIdentifier(SyntaxToken identifier) => Update(this.FromKeyword, this.Type, identifier, this.InKeyword, this.Expression); public FromClauseSyntax WithInKeyword(SyntaxToken inKeyword) => Update(this.FromKeyword, this.Type, this.Identifier, inKeyword, this.Expression); public FromClauseSyntax WithExpression(ExpressionSyntax expression) => Update(this.FromKeyword, this.Type, this.Identifier, this.InKeyword, expression); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.LetClause"/></description></item> /// </list> /// </remarks> public sealed partial class LetClauseSyntax : QueryClauseSyntax { private ExpressionSyntax? expression; internal LetClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken LetKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.LetClauseSyntax)this.Green).letKeyword, Position, 0); /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.LetClauseSyntax)this.Green).identifier, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken EqualsToken => new SyntaxToken(this, ((Syntax.InternalSyntax.LetClauseSyntax)this.Green).equalsToken, GetChildPosition(2), GetChildIndex(2)); public ExpressionSyntax Expression => GetRed(ref this.expression, 3)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 3 ? GetRed(ref this.expression, 3)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 3 ? this.expression : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitLetClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitLetClause(this); public LetClauseSyntax Update(SyntaxToken letKeyword, SyntaxToken identifier, SyntaxToken equalsToken, ExpressionSyntax expression) { if (letKeyword != this.LetKeyword || identifier != this.Identifier || equalsToken != this.EqualsToken || expression != this.Expression) { var newNode = SyntaxFactory.LetClause(letKeyword, identifier, equalsToken, expression); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public LetClauseSyntax WithLetKeyword(SyntaxToken letKeyword) => Update(letKeyword, this.Identifier, this.EqualsToken, this.Expression); public LetClauseSyntax WithIdentifier(SyntaxToken identifier) => Update(this.LetKeyword, identifier, this.EqualsToken, this.Expression); public LetClauseSyntax WithEqualsToken(SyntaxToken equalsToken) => Update(this.LetKeyword, this.Identifier, equalsToken, this.Expression); public LetClauseSyntax WithExpression(ExpressionSyntax expression) => Update(this.LetKeyword, this.Identifier, this.EqualsToken, expression); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.JoinClause"/></description></item> /// </list> /// </remarks> public sealed partial class JoinClauseSyntax : QueryClauseSyntax { private TypeSyntax? type; private ExpressionSyntax? inExpression; private ExpressionSyntax? leftExpression; private ExpressionSyntax? rightExpression; private JoinIntoClauseSyntax? into; internal JoinClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken JoinKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.JoinClauseSyntax)this.Green).joinKeyword, Position, 0); public TypeSyntax? Type => GetRed(ref this.type, 1); /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.JoinClauseSyntax)this.Green).identifier, GetChildPosition(2), GetChildIndex(2)); public SyntaxToken InKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.JoinClauseSyntax)this.Green).inKeyword, GetChildPosition(3), GetChildIndex(3)); public ExpressionSyntax InExpression => GetRed(ref this.inExpression, 4)!; public SyntaxToken OnKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.JoinClauseSyntax)this.Green).onKeyword, GetChildPosition(5), GetChildIndex(5)); public ExpressionSyntax LeftExpression => GetRed(ref this.leftExpression, 6)!; public SyntaxToken EqualsKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.JoinClauseSyntax)this.Green).equalsKeyword, GetChildPosition(7), GetChildIndex(7)); public ExpressionSyntax RightExpression => GetRed(ref this.rightExpression, 8)!; public JoinIntoClauseSyntax? Into => GetRed(ref this.into, 9); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 1 => GetRed(ref this.type, 1), 4 => GetRed(ref this.inExpression, 4)!, 6 => GetRed(ref this.leftExpression, 6)!, 8 => GetRed(ref this.rightExpression, 8)!, 9 => GetRed(ref this.into, 9), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 1 => this.type, 4 => this.inExpression, 6 => this.leftExpression, 8 => this.rightExpression, 9 => this.into, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitJoinClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitJoinClause(this); public JoinClauseSyntax Update(SyntaxToken joinKeyword, TypeSyntax? type, SyntaxToken identifier, SyntaxToken inKeyword, ExpressionSyntax inExpression, SyntaxToken onKeyword, ExpressionSyntax leftExpression, SyntaxToken equalsKeyword, ExpressionSyntax rightExpression, JoinIntoClauseSyntax? into) { if (joinKeyword != this.JoinKeyword || type != this.Type || identifier != this.Identifier || inKeyword != this.InKeyword || inExpression != this.InExpression || onKeyword != this.OnKeyword || leftExpression != this.LeftExpression || equalsKeyword != this.EqualsKeyword || rightExpression != this.RightExpression || into != this.Into) { var newNode = SyntaxFactory.JoinClause(joinKeyword, type, identifier, inKeyword, inExpression, onKeyword, leftExpression, equalsKeyword, rightExpression, into); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public JoinClauseSyntax WithJoinKeyword(SyntaxToken joinKeyword) => Update(joinKeyword, this.Type, this.Identifier, this.InKeyword, this.InExpression, this.OnKeyword, this.LeftExpression, this.EqualsKeyword, this.RightExpression, this.Into); public JoinClauseSyntax WithType(TypeSyntax? type) => Update(this.JoinKeyword, type, this.Identifier, this.InKeyword, this.InExpression, this.OnKeyword, this.LeftExpression, this.EqualsKeyword, this.RightExpression, this.Into); public JoinClauseSyntax WithIdentifier(SyntaxToken identifier) => Update(this.JoinKeyword, this.Type, identifier, this.InKeyword, this.InExpression, this.OnKeyword, this.LeftExpression, this.EqualsKeyword, this.RightExpression, this.Into); public JoinClauseSyntax WithInKeyword(SyntaxToken inKeyword) => Update(this.JoinKeyword, this.Type, this.Identifier, inKeyword, this.InExpression, this.OnKeyword, this.LeftExpression, this.EqualsKeyword, this.RightExpression, this.Into); public JoinClauseSyntax WithInExpression(ExpressionSyntax inExpression) => Update(this.JoinKeyword, this.Type, this.Identifier, this.InKeyword, inExpression, this.OnKeyword, this.LeftExpression, this.EqualsKeyword, this.RightExpression, this.Into); public JoinClauseSyntax WithOnKeyword(SyntaxToken onKeyword) => Update(this.JoinKeyword, this.Type, this.Identifier, this.InKeyword, this.InExpression, onKeyword, this.LeftExpression, this.EqualsKeyword, this.RightExpression, this.Into); public JoinClauseSyntax WithLeftExpression(ExpressionSyntax leftExpression) => Update(this.JoinKeyword, this.Type, this.Identifier, this.InKeyword, this.InExpression, this.OnKeyword, leftExpression, this.EqualsKeyword, this.RightExpression, this.Into); public JoinClauseSyntax WithEqualsKeyword(SyntaxToken equalsKeyword) => Update(this.JoinKeyword, this.Type, this.Identifier, this.InKeyword, this.InExpression, this.OnKeyword, this.LeftExpression, equalsKeyword, this.RightExpression, this.Into); public JoinClauseSyntax WithRightExpression(ExpressionSyntax rightExpression) => Update(this.JoinKeyword, this.Type, this.Identifier, this.InKeyword, this.InExpression, this.OnKeyword, this.LeftExpression, this.EqualsKeyword, rightExpression, this.Into); public JoinClauseSyntax WithInto(JoinIntoClauseSyntax? into) => Update(this.JoinKeyword, this.Type, this.Identifier, this.InKeyword, this.InExpression, this.OnKeyword, this.LeftExpression, this.EqualsKeyword, this.RightExpression, into); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.JoinIntoClause"/></description></item> /// </list> /// </remarks> public sealed partial class JoinIntoClauseSyntax : CSharpSyntaxNode { internal JoinIntoClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken IntoKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.JoinIntoClauseSyntax)this.Green).intoKeyword, Position, 0); /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.JoinIntoClauseSyntax)this.Green).identifier, GetChildPosition(1), GetChildIndex(1)); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitJoinIntoClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitJoinIntoClause(this); public JoinIntoClauseSyntax Update(SyntaxToken intoKeyword, SyntaxToken identifier) { if (intoKeyword != this.IntoKeyword || identifier != this.Identifier) { var newNode = SyntaxFactory.JoinIntoClause(intoKeyword, identifier); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public JoinIntoClauseSyntax WithIntoKeyword(SyntaxToken intoKeyword) => Update(intoKeyword, this.Identifier); public JoinIntoClauseSyntax WithIdentifier(SyntaxToken identifier) => Update(this.IntoKeyword, identifier); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.WhereClause"/></description></item> /// </list> /// </remarks> public sealed partial class WhereClauseSyntax : QueryClauseSyntax { private ExpressionSyntax? condition; internal WhereClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken WhereKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.WhereClauseSyntax)this.Green).whereKeyword, Position, 0); public ExpressionSyntax Condition => GetRed(ref this.condition, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.condition, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.condition : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitWhereClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitWhereClause(this); public WhereClauseSyntax Update(SyntaxToken whereKeyword, ExpressionSyntax condition) { if (whereKeyword != this.WhereKeyword || condition != this.Condition) { var newNode = SyntaxFactory.WhereClause(whereKeyword, condition); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public WhereClauseSyntax WithWhereKeyword(SyntaxToken whereKeyword) => Update(whereKeyword, this.Condition); public WhereClauseSyntax WithCondition(ExpressionSyntax condition) => Update(this.WhereKeyword, condition); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.OrderByClause"/></description></item> /// </list> /// </remarks> public sealed partial class OrderByClauseSyntax : QueryClauseSyntax { private SyntaxNode? orderings; internal OrderByClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken OrderByKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.OrderByClauseSyntax)this.Green).orderByKeyword, Position, 0); public SeparatedSyntaxList<OrderingSyntax> Orderings { get { var red = GetRed(ref this.orderings, 1); return red != null ? new SeparatedSyntaxList<OrderingSyntax>(red, GetChildIndex(1)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.orderings, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.orderings : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitOrderByClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitOrderByClause(this); public OrderByClauseSyntax Update(SyntaxToken orderByKeyword, SeparatedSyntaxList<OrderingSyntax> orderings) { if (orderByKeyword != this.OrderByKeyword || orderings != this.Orderings) { var newNode = SyntaxFactory.OrderByClause(orderByKeyword, orderings); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public OrderByClauseSyntax WithOrderByKeyword(SyntaxToken orderByKeyword) => Update(orderByKeyword, this.Orderings); public OrderByClauseSyntax WithOrderings(SeparatedSyntaxList<OrderingSyntax> orderings) => Update(this.OrderByKeyword, orderings); public OrderByClauseSyntax AddOrderings(params OrderingSyntax[] items) => WithOrderings(this.Orderings.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.AscendingOrdering"/></description></item> /// <item><description><see cref="SyntaxKind.DescendingOrdering"/></description></item> /// </list> /// </remarks> public sealed partial class OrderingSyntax : CSharpSyntaxNode { private ExpressionSyntax? expression; internal OrderingSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public ExpressionSyntax Expression => GetRedAtZero(ref this.expression)!; public SyntaxToken AscendingOrDescendingKeyword { get { var slot = ((Syntax.InternalSyntax.OrderingSyntax)this.Green).ascendingOrDescendingKeyword; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.expression)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.expression : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitOrdering(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitOrdering(this); public OrderingSyntax Update(ExpressionSyntax expression, SyntaxToken ascendingOrDescendingKeyword) { if (expression != this.Expression || ascendingOrDescendingKeyword != this.AscendingOrDescendingKeyword) { var newNode = SyntaxFactory.Ordering(this.Kind(), expression, ascendingOrDescendingKeyword); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public OrderingSyntax WithExpression(ExpressionSyntax expression) => Update(expression, this.AscendingOrDescendingKeyword); public OrderingSyntax WithAscendingOrDescendingKeyword(SyntaxToken ascendingOrDescendingKeyword) => Update(this.Expression, ascendingOrDescendingKeyword); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.SelectClause"/></description></item> /// </list> /// </remarks> public sealed partial class SelectClauseSyntax : SelectOrGroupClauseSyntax { private ExpressionSyntax? expression; internal SelectClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken SelectKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.SelectClauseSyntax)this.Green).selectKeyword, Position, 0); public ExpressionSyntax Expression => GetRed(ref this.expression, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.expression, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.expression : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitSelectClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitSelectClause(this); public SelectClauseSyntax Update(SyntaxToken selectKeyword, ExpressionSyntax expression) { if (selectKeyword != this.SelectKeyword || expression != this.Expression) { var newNode = SyntaxFactory.SelectClause(selectKeyword, expression); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public SelectClauseSyntax WithSelectKeyword(SyntaxToken selectKeyword) => Update(selectKeyword, this.Expression); public SelectClauseSyntax WithExpression(ExpressionSyntax expression) => Update(this.SelectKeyword, expression); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.GroupClause"/></description></item> /// </list> /// </remarks> public sealed partial class GroupClauseSyntax : SelectOrGroupClauseSyntax { private ExpressionSyntax? groupExpression; private ExpressionSyntax? byExpression; internal GroupClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken GroupKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.GroupClauseSyntax)this.Green).groupKeyword, Position, 0); public ExpressionSyntax GroupExpression => GetRed(ref this.groupExpression, 1)!; public SyntaxToken ByKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.GroupClauseSyntax)this.Green).byKeyword, GetChildPosition(2), GetChildIndex(2)); public ExpressionSyntax ByExpression => GetRed(ref this.byExpression, 3)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 1 => GetRed(ref this.groupExpression, 1)!, 3 => GetRed(ref this.byExpression, 3)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 1 => this.groupExpression, 3 => this.byExpression, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitGroupClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitGroupClause(this); public GroupClauseSyntax Update(SyntaxToken groupKeyword, ExpressionSyntax groupExpression, SyntaxToken byKeyword, ExpressionSyntax byExpression) { if (groupKeyword != this.GroupKeyword || groupExpression != this.GroupExpression || byKeyword != this.ByKeyword || byExpression != this.ByExpression) { var newNode = SyntaxFactory.GroupClause(groupKeyword, groupExpression, byKeyword, byExpression); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public GroupClauseSyntax WithGroupKeyword(SyntaxToken groupKeyword) => Update(groupKeyword, this.GroupExpression, this.ByKeyword, this.ByExpression); public GroupClauseSyntax WithGroupExpression(ExpressionSyntax groupExpression) => Update(this.GroupKeyword, groupExpression, this.ByKeyword, this.ByExpression); public GroupClauseSyntax WithByKeyword(SyntaxToken byKeyword) => Update(this.GroupKeyword, this.GroupExpression, byKeyword, this.ByExpression); public GroupClauseSyntax WithByExpression(ExpressionSyntax byExpression) => Update(this.GroupKeyword, this.GroupExpression, this.ByKeyword, byExpression); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.QueryContinuation"/></description></item> /// </list> /// </remarks> public sealed partial class QueryContinuationSyntax : CSharpSyntaxNode { private QueryBodySyntax? body; internal QueryContinuationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken IntoKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.QueryContinuationSyntax)this.Green).intoKeyword, Position, 0); /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.QueryContinuationSyntax)this.Green).identifier, GetChildPosition(1), GetChildIndex(1)); public QueryBodySyntax Body => GetRed(ref this.body, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 2 ? GetRed(ref this.body, 2)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 2 ? this.body : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitQueryContinuation(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitQueryContinuation(this); public QueryContinuationSyntax Update(SyntaxToken intoKeyword, SyntaxToken identifier, QueryBodySyntax body) { if (intoKeyword != this.IntoKeyword || identifier != this.Identifier || body != this.Body) { var newNode = SyntaxFactory.QueryContinuation(intoKeyword, identifier, body); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public QueryContinuationSyntax WithIntoKeyword(SyntaxToken intoKeyword) => Update(intoKeyword, this.Identifier, this.Body); public QueryContinuationSyntax WithIdentifier(SyntaxToken identifier) => Update(this.IntoKeyword, identifier, this.Body); public QueryContinuationSyntax WithBody(QueryBodySyntax body) => Update(this.IntoKeyword, this.Identifier, body); public QueryContinuationSyntax AddBodyClauses(params QueryClauseSyntax[] items) => WithBody(this.Body.WithClauses(this.Body.Clauses.AddRange(items))); } /// <summary>Class which represents a placeholder in an array size list.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.OmittedArraySizeExpression"/></description></item> /// </list> /// </remarks> public sealed partial class OmittedArraySizeExpressionSyntax : ExpressionSyntax { internal OmittedArraySizeExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the omitted array size expression.</summary> public SyntaxToken OmittedArraySizeExpressionToken => new SyntaxToken(this, ((Syntax.InternalSyntax.OmittedArraySizeExpressionSyntax)this.Green).omittedArraySizeExpressionToken, Position, 0); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitOmittedArraySizeExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitOmittedArraySizeExpression(this); public OmittedArraySizeExpressionSyntax Update(SyntaxToken omittedArraySizeExpressionToken) { if (omittedArraySizeExpressionToken != this.OmittedArraySizeExpressionToken) { var newNode = SyntaxFactory.OmittedArraySizeExpression(omittedArraySizeExpressionToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public OmittedArraySizeExpressionSyntax WithOmittedArraySizeExpressionToken(SyntaxToken omittedArraySizeExpressionToken) => Update(omittedArraySizeExpressionToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.InterpolatedStringExpression"/></description></item> /// </list> /// </remarks> public sealed partial class InterpolatedStringExpressionSyntax : ExpressionSyntax { private SyntaxNode? contents; internal InterpolatedStringExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>The first part of an interpolated string, $" or $@"</summary> public SyntaxToken StringStartToken => new SyntaxToken(this, ((Syntax.InternalSyntax.InterpolatedStringExpressionSyntax)this.Green).stringStartToken, Position, 0); /// <summary>List of parts of the interpolated string, each one is either a literal part or an interpolation.</summary> public SyntaxList<InterpolatedStringContentSyntax> Contents => new SyntaxList<InterpolatedStringContentSyntax>(GetRed(ref this.contents, 1)); /// <summary>The closing quote of the interpolated string.</summary> public SyntaxToken StringEndToken => new SyntaxToken(this, ((Syntax.InternalSyntax.InterpolatedStringExpressionSyntax)this.Green).stringEndToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.contents, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.contents : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitInterpolatedStringExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitInterpolatedStringExpression(this); public InterpolatedStringExpressionSyntax Update(SyntaxToken stringStartToken, SyntaxList<InterpolatedStringContentSyntax> contents, SyntaxToken stringEndToken) { if (stringStartToken != this.StringStartToken || contents != this.Contents || stringEndToken != this.StringEndToken) { var newNode = SyntaxFactory.InterpolatedStringExpression(stringStartToken, contents, stringEndToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public InterpolatedStringExpressionSyntax WithStringStartToken(SyntaxToken stringStartToken) => Update(stringStartToken, this.Contents, this.StringEndToken); public InterpolatedStringExpressionSyntax WithContents(SyntaxList<InterpolatedStringContentSyntax> contents) => Update(this.StringStartToken, contents, this.StringEndToken); public InterpolatedStringExpressionSyntax WithStringEndToken(SyntaxToken stringEndToken) => Update(this.StringStartToken, this.Contents, stringEndToken); public InterpolatedStringExpressionSyntax AddContents(params InterpolatedStringContentSyntax[] items) => WithContents(this.Contents.AddRange(items)); } /// <summary>Class which represents a simple pattern-matching expression using the "is" keyword.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.IsPatternExpression"/></description></item> /// </list> /// </remarks> public sealed partial class IsPatternExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? expression; private PatternSyntax? pattern; internal IsPatternExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>ExpressionSyntax node representing the expression on the left of the "is" operator.</summary> public ExpressionSyntax Expression => GetRedAtZero(ref this.expression)!; public SyntaxToken IsKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.IsPatternExpressionSyntax)this.Green).isKeyword, GetChildPosition(1), GetChildIndex(1)); /// <summary>PatternSyntax node representing the pattern on the right of the "is" operator.</summary> public PatternSyntax Pattern => GetRed(ref this.pattern, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.expression)!, 2 => GetRed(ref this.pattern, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.expression, 2 => this.pattern, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitIsPatternExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitIsPatternExpression(this); public IsPatternExpressionSyntax Update(ExpressionSyntax expression, SyntaxToken isKeyword, PatternSyntax pattern) { if (expression != this.Expression || isKeyword != this.IsKeyword || pattern != this.Pattern) { var newNode = SyntaxFactory.IsPatternExpression(expression, isKeyword, pattern); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public IsPatternExpressionSyntax WithExpression(ExpressionSyntax expression) => Update(expression, this.IsKeyword, this.Pattern); public IsPatternExpressionSyntax WithIsKeyword(SyntaxToken isKeyword) => Update(this.Expression, isKeyword, this.Pattern); public IsPatternExpressionSyntax WithPattern(PatternSyntax pattern) => Update(this.Expression, this.IsKeyword, pattern); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ThrowExpression"/></description></item> /// </list> /// </remarks> public sealed partial class ThrowExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? expression; internal ThrowExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken ThrowKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ThrowExpressionSyntax)this.Green).throwKeyword, Position, 0); public ExpressionSyntax Expression => GetRed(ref this.expression, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.expression, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.expression : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitThrowExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitThrowExpression(this); public ThrowExpressionSyntax Update(SyntaxToken throwKeyword, ExpressionSyntax expression) { if (throwKeyword != this.ThrowKeyword || expression != this.Expression) { var newNode = SyntaxFactory.ThrowExpression(throwKeyword, expression); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ThrowExpressionSyntax WithThrowKeyword(SyntaxToken throwKeyword) => Update(throwKeyword, this.Expression); public ThrowExpressionSyntax WithExpression(ExpressionSyntax expression) => Update(this.ThrowKeyword, expression); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.WhenClause"/></description></item> /// </list> /// </remarks> public sealed partial class WhenClauseSyntax : CSharpSyntaxNode { private ExpressionSyntax? condition; internal WhenClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken WhenKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.WhenClauseSyntax)this.Green).whenKeyword, Position, 0); public ExpressionSyntax Condition => GetRed(ref this.condition, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.condition, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.condition : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitWhenClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitWhenClause(this); public WhenClauseSyntax Update(SyntaxToken whenKeyword, ExpressionSyntax condition) { if (whenKeyword != this.WhenKeyword || condition != this.Condition) { var newNode = SyntaxFactory.WhenClause(whenKeyword, condition); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public WhenClauseSyntax WithWhenKeyword(SyntaxToken whenKeyword) => Update(whenKeyword, this.Condition); public WhenClauseSyntax WithCondition(ExpressionSyntax condition) => Update(this.WhenKeyword, condition); } public abstract partial class PatternSyntax : ExpressionOrPatternSyntax { internal PatternSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.DiscardPattern"/></description></item> /// </list> /// </remarks> public sealed partial class DiscardPatternSyntax : PatternSyntax { internal DiscardPatternSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken UnderscoreToken => new SyntaxToken(this, ((Syntax.InternalSyntax.DiscardPatternSyntax)this.Green).underscoreToken, Position, 0); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitDiscardPattern(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitDiscardPattern(this); public DiscardPatternSyntax Update(SyntaxToken underscoreToken) { if (underscoreToken != this.UnderscoreToken) { var newNode = SyntaxFactory.DiscardPattern(underscoreToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public DiscardPatternSyntax WithUnderscoreToken(SyntaxToken underscoreToken) => Update(underscoreToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.DeclarationPattern"/></description></item> /// </list> /// </remarks> public sealed partial class DeclarationPatternSyntax : PatternSyntax { private TypeSyntax? type; private VariableDesignationSyntax? designation; internal DeclarationPatternSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public TypeSyntax Type => GetRedAtZero(ref this.type)!; public VariableDesignationSyntax Designation => GetRed(ref this.designation, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.type)!, 1 => GetRed(ref this.designation, 1)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.type, 1 => this.designation, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitDeclarationPattern(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitDeclarationPattern(this); public DeclarationPatternSyntax Update(TypeSyntax type, VariableDesignationSyntax designation) { if (type != this.Type || designation != this.Designation) { var newNode = SyntaxFactory.DeclarationPattern(type, designation); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public DeclarationPatternSyntax WithType(TypeSyntax type) => Update(type, this.Designation); public DeclarationPatternSyntax WithDesignation(VariableDesignationSyntax designation) => Update(this.Type, designation); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.VarPattern"/></description></item> /// </list> /// </remarks> public sealed partial class VarPatternSyntax : PatternSyntax { private VariableDesignationSyntax? designation; internal VarPatternSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken VarKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.VarPatternSyntax)this.Green).varKeyword, Position, 0); public VariableDesignationSyntax Designation => GetRed(ref this.designation, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.designation, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.designation : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitVarPattern(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitVarPattern(this); public VarPatternSyntax Update(SyntaxToken varKeyword, VariableDesignationSyntax designation) { if (varKeyword != this.VarKeyword || designation != this.Designation) { var newNode = SyntaxFactory.VarPattern(varKeyword, designation); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public VarPatternSyntax WithVarKeyword(SyntaxToken varKeyword) => Update(varKeyword, this.Designation); public VarPatternSyntax WithDesignation(VariableDesignationSyntax designation) => Update(this.VarKeyword, designation); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.RecursivePattern"/></description></item> /// </list> /// </remarks> public sealed partial class RecursivePatternSyntax : PatternSyntax { private TypeSyntax? type; private PositionalPatternClauseSyntax? positionalPatternClause; private PropertyPatternClauseSyntax? propertyPatternClause; private VariableDesignationSyntax? designation; internal RecursivePatternSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public TypeSyntax? Type => GetRedAtZero(ref this.type); public PositionalPatternClauseSyntax? PositionalPatternClause => GetRed(ref this.positionalPatternClause, 1); public PropertyPatternClauseSyntax? PropertyPatternClause => GetRed(ref this.propertyPatternClause, 2); public VariableDesignationSyntax? Designation => GetRed(ref this.designation, 3); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.type), 1 => GetRed(ref this.positionalPatternClause, 1), 2 => GetRed(ref this.propertyPatternClause, 2), 3 => GetRed(ref this.designation, 3), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.type, 1 => this.positionalPatternClause, 2 => this.propertyPatternClause, 3 => this.designation, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitRecursivePattern(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitRecursivePattern(this); public RecursivePatternSyntax Update(TypeSyntax? type, PositionalPatternClauseSyntax? positionalPatternClause, PropertyPatternClauseSyntax? propertyPatternClause, VariableDesignationSyntax? designation) { if (type != this.Type || positionalPatternClause != this.PositionalPatternClause || propertyPatternClause != this.PropertyPatternClause || designation != this.Designation) { var newNode = SyntaxFactory.RecursivePattern(type, positionalPatternClause, propertyPatternClause, designation); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public RecursivePatternSyntax WithType(TypeSyntax? type) => Update(type, this.PositionalPatternClause, this.PropertyPatternClause, this.Designation); public RecursivePatternSyntax WithPositionalPatternClause(PositionalPatternClauseSyntax? positionalPatternClause) => Update(this.Type, positionalPatternClause, this.PropertyPatternClause, this.Designation); public RecursivePatternSyntax WithPropertyPatternClause(PropertyPatternClauseSyntax? propertyPatternClause) => Update(this.Type, this.PositionalPatternClause, propertyPatternClause, this.Designation); public RecursivePatternSyntax WithDesignation(VariableDesignationSyntax? designation) => Update(this.Type, this.PositionalPatternClause, this.PropertyPatternClause, designation); public RecursivePatternSyntax AddPositionalPatternClauseSubpatterns(params SubpatternSyntax[] items) { var positionalPatternClause = this.PositionalPatternClause ?? SyntaxFactory.PositionalPatternClause(); return WithPositionalPatternClause(positionalPatternClause.WithSubpatterns(positionalPatternClause.Subpatterns.AddRange(items))); } public RecursivePatternSyntax AddPropertyPatternClauseSubpatterns(params SubpatternSyntax[] items) { var propertyPatternClause = this.PropertyPatternClause ?? SyntaxFactory.PropertyPatternClause(); return WithPropertyPatternClause(propertyPatternClause.WithSubpatterns(propertyPatternClause.Subpatterns.AddRange(items))); } } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.PositionalPatternClause"/></description></item> /// </list> /// </remarks> public sealed partial class PositionalPatternClauseSyntax : CSharpSyntaxNode { private SyntaxNode? subpatterns; internal PositionalPatternClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.PositionalPatternClauseSyntax)this.Green).openParenToken, Position, 0); public SeparatedSyntaxList<SubpatternSyntax> Subpatterns { get { var red = GetRed(ref this.subpatterns, 1); return red != null ? new SeparatedSyntaxList<SubpatternSyntax>(red, GetChildIndex(1)) : default; } } public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.PositionalPatternClauseSyntax)this.Green).closeParenToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.subpatterns, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.subpatterns : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitPositionalPatternClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitPositionalPatternClause(this); public PositionalPatternClauseSyntax Update(SyntaxToken openParenToken, SeparatedSyntaxList<SubpatternSyntax> subpatterns, SyntaxToken closeParenToken) { if (openParenToken != this.OpenParenToken || subpatterns != this.Subpatterns || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.PositionalPatternClause(openParenToken, subpatterns, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public PositionalPatternClauseSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(openParenToken, this.Subpatterns, this.CloseParenToken); public PositionalPatternClauseSyntax WithSubpatterns(SeparatedSyntaxList<SubpatternSyntax> subpatterns) => Update(this.OpenParenToken, subpatterns, this.CloseParenToken); public PositionalPatternClauseSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.OpenParenToken, this.Subpatterns, closeParenToken); public PositionalPatternClauseSyntax AddSubpatterns(params SubpatternSyntax[] items) => WithSubpatterns(this.Subpatterns.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.PropertyPatternClause"/></description></item> /// </list> /// </remarks> public sealed partial class PropertyPatternClauseSyntax : CSharpSyntaxNode { private SyntaxNode? subpatterns; internal PropertyPatternClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken OpenBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.PropertyPatternClauseSyntax)this.Green).openBraceToken, Position, 0); public SeparatedSyntaxList<SubpatternSyntax> Subpatterns { get { var red = GetRed(ref this.subpatterns, 1); return red != null ? new SeparatedSyntaxList<SubpatternSyntax>(red, GetChildIndex(1)) : default; } } public SyntaxToken CloseBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.PropertyPatternClauseSyntax)this.Green).closeBraceToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.subpatterns, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.subpatterns : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitPropertyPatternClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitPropertyPatternClause(this); public PropertyPatternClauseSyntax Update(SyntaxToken openBraceToken, SeparatedSyntaxList<SubpatternSyntax> subpatterns, SyntaxToken closeBraceToken) { if (openBraceToken != this.OpenBraceToken || subpatterns != this.Subpatterns || closeBraceToken != this.CloseBraceToken) { var newNode = SyntaxFactory.PropertyPatternClause(openBraceToken, subpatterns, closeBraceToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public PropertyPatternClauseSyntax WithOpenBraceToken(SyntaxToken openBraceToken) => Update(openBraceToken, this.Subpatterns, this.CloseBraceToken); public PropertyPatternClauseSyntax WithSubpatterns(SeparatedSyntaxList<SubpatternSyntax> subpatterns) => Update(this.OpenBraceToken, subpatterns, this.CloseBraceToken); public PropertyPatternClauseSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) => Update(this.OpenBraceToken, this.Subpatterns, closeBraceToken); public PropertyPatternClauseSyntax AddSubpatterns(params SubpatternSyntax[] items) => WithSubpatterns(this.Subpatterns.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.Subpattern"/></description></item> /// </list> /// </remarks> public sealed partial class SubpatternSyntax : CSharpSyntaxNode { private BaseExpressionColonSyntax? expressionColon; private PatternSyntax? pattern; internal SubpatternSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public BaseExpressionColonSyntax? ExpressionColon => GetRedAtZero(ref this.expressionColon); public PatternSyntax Pattern => GetRed(ref this.pattern, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.expressionColon), 1 => GetRed(ref this.pattern, 1)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.expressionColon, 1 => this.pattern, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitSubpattern(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitSubpattern(this); public SubpatternSyntax Update(BaseExpressionColonSyntax? expressionColon, PatternSyntax pattern) { if (expressionColon != this.ExpressionColon || pattern != this.Pattern) { var newNode = SyntaxFactory.Subpattern(expressionColon, pattern); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public SubpatternSyntax WithExpressionColon(BaseExpressionColonSyntax? expressionColon) => Update(expressionColon, this.Pattern); public SubpatternSyntax WithPattern(PatternSyntax pattern) => Update(this.ExpressionColon, pattern); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ConstantPattern"/></description></item> /// </list> /// </remarks> public sealed partial class ConstantPatternSyntax : PatternSyntax { private ExpressionSyntax? expression; internal ConstantPatternSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>ExpressionSyntax node representing the constant expression.</summary> public ExpressionSyntax Expression => GetRedAtZero(ref this.expression)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.expression)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.expression : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitConstantPattern(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitConstantPattern(this); public ConstantPatternSyntax Update(ExpressionSyntax expression) { if (expression != this.Expression) { var newNode = SyntaxFactory.ConstantPattern(expression); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ConstantPatternSyntax WithExpression(ExpressionSyntax expression) => Update(expression); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ParenthesizedPattern"/></description></item> /// </list> /// </remarks> public sealed partial class ParenthesizedPatternSyntax : PatternSyntax { private PatternSyntax? pattern; internal ParenthesizedPatternSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ParenthesizedPatternSyntax)this.Green).openParenToken, Position, 0); public PatternSyntax Pattern => GetRed(ref this.pattern, 1)!; public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ParenthesizedPatternSyntax)this.Green).closeParenToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.pattern, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.pattern : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitParenthesizedPattern(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitParenthesizedPattern(this); public ParenthesizedPatternSyntax Update(SyntaxToken openParenToken, PatternSyntax pattern, SyntaxToken closeParenToken) { if (openParenToken != this.OpenParenToken || pattern != this.Pattern || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.ParenthesizedPattern(openParenToken, pattern, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ParenthesizedPatternSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(openParenToken, this.Pattern, this.CloseParenToken); public ParenthesizedPatternSyntax WithPattern(PatternSyntax pattern) => Update(this.OpenParenToken, pattern, this.CloseParenToken); public ParenthesizedPatternSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.OpenParenToken, this.Pattern, closeParenToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.RelationalPattern"/></description></item> /// </list> /// </remarks> public sealed partial class RelationalPatternSyntax : PatternSyntax { private ExpressionSyntax? expression; internal RelationalPatternSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the operator of the relational pattern.</summary> public SyntaxToken OperatorToken => new SyntaxToken(this, ((Syntax.InternalSyntax.RelationalPatternSyntax)this.Green).operatorToken, Position, 0); public ExpressionSyntax Expression => GetRed(ref this.expression, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.expression, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.expression : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitRelationalPattern(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitRelationalPattern(this); public RelationalPatternSyntax Update(SyntaxToken operatorToken, ExpressionSyntax expression) { if (operatorToken != this.OperatorToken || expression != this.Expression) { var newNode = SyntaxFactory.RelationalPattern(operatorToken, expression); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public RelationalPatternSyntax WithOperatorToken(SyntaxToken operatorToken) => Update(operatorToken, this.Expression); public RelationalPatternSyntax WithExpression(ExpressionSyntax expression) => Update(this.OperatorToken, expression); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.TypePattern"/></description></item> /// </list> /// </remarks> public sealed partial class TypePatternSyntax : PatternSyntax { private TypeSyntax? type; internal TypePatternSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>The type for the type pattern.</summary> public TypeSyntax Type => GetRedAtZero(ref this.type)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.type)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.type : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitTypePattern(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitTypePattern(this); public TypePatternSyntax Update(TypeSyntax type) { if (type != this.Type) { var newNode = SyntaxFactory.TypePattern(type); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public TypePatternSyntax WithType(TypeSyntax type) => Update(type); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.OrPattern"/></description></item> /// <item><description><see cref="SyntaxKind.AndPattern"/></description></item> /// </list> /// </remarks> public sealed partial class BinaryPatternSyntax : PatternSyntax { private PatternSyntax? left; private PatternSyntax? right; internal BinaryPatternSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public PatternSyntax Left => GetRedAtZero(ref this.left)!; public SyntaxToken OperatorToken => new SyntaxToken(this, ((Syntax.InternalSyntax.BinaryPatternSyntax)this.Green).operatorToken, GetChildPosition(1), GetChildIndex(1)); public PatternSyntax Right => GetRed(ref this.right, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.left)!, 2 => GetRed(ref this.right, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.left, 2 => this.right, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitBinaryPattern(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitBinaryPattern(this); public BinaryPatternSyntax Update(PatternSyntax left, SyntaxToken operatorToken, PatternSyntax right) { if (left != this.Left || operatorToken != this.OperatorToken || right != this.Right) { var newNode = SyntaxFactory.BinaryPattern(this.Kind(), left, operatorToken, right); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public BinaryPatternSyntax WithLeft(PatternSyntax left) => Update(left, this.OperatorToken, this.Right); public BinaryPatternSyntax WithOperatorToken(SyntaxToken operatorToken) => Update(this.Left, operatorToken, this.Right); public BinaryPatternSyntax WithRight(PatternSyntax right) => Update(this.Left, this.OperatorToken, right); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.NotPattern"/></description></item> /// </list> /// </remarks> public sealed partial class UnaryPatternSyntax : PatternSyntax { private PatternSyntax? pattern; internal UnaryPatternSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken OperatorToken => new SyntaxToken(this, ((Syntax.InternalSyntax.UnaryPatternSyntax)this.Green).operatorToken, Position, 0); public PatternSyntax Pattern => GetRed(ref this.pattern, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.pattern, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.pattern : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitUnaryPattern(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitUnaryPattern(this); public UnaryPatternSyntax Update(SyntaxToken operatorToken, PatternSyntax pattern) { if (operatorToken != this.OperatorToken || pattern != this.Pattern) { var newNode = SyntaxFactory.UnaryPattern(operatorToken, pattern); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public UnaryPatternSyntax WithOperatorToken(SyntaxToken operatorToken) => Update(operatorToken, this.Pattern); public UnaryPatternSyntax WithPattern(PatternSyntax pattern) => Update(this.OperatorToken, pattern); } public abstract partial class InterpolatedStringContentSyntax : CSharpSyntaxNode { internal InterpolatedStringContentSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.InterpolatedStringText"/></description></item> /// </list> /// </remarks> public sealed partial class InterpolatedStringTextSyntax : InterpolatedStringContentSyntax { internal InterpolatedStringTextSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>The text contents of a part of the interpolated string.</summary> public SyntaxToken TextToken => new SyntaxToken(this, ((Syntax.InternalSyntax.InterpolatedStringTextSyntax)this.Green).textToken, Position, 0); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitInterpolatedStringText(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitInterpolatedStringText(this); public InterpolatedStringTextSyntax Update(SyntaxToken textToken) { if (textToken != this.TextToken) { var newNode = SyntaxFactory.InterpolatedStringText(textToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public InterpolatedStringTextSyntax WithTextToken(SyntaxToken textToken) => Update(textToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.Interpolation"/></description></item> /// </list> /// </remarks> public sealed partial class InterpolationSyntax : InterpolatedStringContentSyntax { private ExpressionSyntax? expression; private InterpolationAlignmentClauseSyntax? alignmentClause; private InterpolationFormatClauseSyntax? formatClause; internal InterpolationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken OpenBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.InterpolationSyntax)this.Green).openBraceToken, Position, 0); public ExpressionSyntax Expression => GetRed(ref this.expression, 1)!; public InterpolationAlignmentClauseSyntax? AlignmentClause => GetRed(ref this.alignmentClause, 2); public InterpolationFormatClauseSyntax? FormatClause => GetRed(ref this.formatClause, 3); public SyntaxToken CloseBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.InterpolationSyntax)this.Green).closeBraceToken, GetChildPosition(4), GetChildIndex(4)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 1 => GetRed(ref this.expression, 1)!, 2 => GetRed(ref this.alignmentClause, 2), 3 => GetRed(ref this.formatClause, 3), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 1 => this.expression, 2 => this.alignmentClause, 3 => this.formatClause, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitInterpolation(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitInterpolation(this); public InterpolationSyntax Update(SyntaxToken openBraceToken, ExpressionSyntax expression, InterpolationAlignmentClauseSyntax? alignmentClause, InterpolationFormatClauseSyntax? formatClause, SyntaxToken closeBraceToken) { if (openBraceToken != this.OpenBraceToken || expression != this.Expression || alignmentClause != this.AlignmentClause || formatClause != this.FormatClause || closeBraceToken != this.CloseBraceToken) { var newNode = SyntaxFactory.Interpolation(openBraceToken, expression, alignmentClause, formatClause, closeBraceToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public InterpolationSyntax WithOpenBraceToken(SyntaxToken openBraceToken) => Update(openBraceToken, this.Expression, this.AlignmentClause, this.FormatClause, this.CloseBraceToken); public InterpolationSyntax WithExpression(ExpressionSyntax expression) => Update(this.OpenBraceToken, expression, this.AlignmentClause, this.FormatClause, this.CloseBraceToken); public InterpolationSyntax WithAlignmentClause(InterpolationAlignmentClauseSyntax? alignmentClause) => Update(this.OpenBraceToken, this.Expression, alignmentClause, this.FormatClause, this.CloseBraceToken); public InterpolationSyntax WithFormatClause(InterpolationFormatClauseSyntax? formatClause) => Update(this.OpenBraceToken, this.Expression, this.AlignmentClause, formatClause, this.CloseBraceToken); public InterpolationSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) => Update(this.OpenBraceToken, this.Expression, this.AlignmentClause, this.FormatClause, closeBraceToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.InterpolationAlignmentClause"/></description></item> /// </list> /// </remarks> public sealed partial class InterpolationAlignmentClauseSyntax : CSharpSyntaxNode { private ExpressionSyntax? value; internal InterpolationAlignmentClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken CommaToken => new SyntaxToken(this, ((Syntax.InternalSyntax.InterpolationAlignmentClauseSyntax)this.Green).commaToken, Position, 0); public ExpressionSyntax Value => GetRed(ref this.value, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.value, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.value : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitInterpolationAlignmentClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitInterpolationAlignmentClause(this); public InterpolationAlignmentClauseSyntax Update(SyntaxToken commaToken, ExpressionSyntax value) { if (commaToken != this.CommaToken || value != this.Value) { var newNode = SyntaxFactory.InterpolationAlignmentClause(commaToken, value); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public InterpolationAlignmentClauseSyntax WithCommaToken(SyntaxToken commaToken) => Update(commaToken, this.Value); public InterpolationAlignmentClauseSyntax WithValue(ExpressionSyntax value) => Update(this.CommaToken, value); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.InterpolationFormatClause"/></description></item> /// </list> /// </remarks> public sealed partial class InterpolationFormatClauseSyntax : CSharpSyntaxNode { internal InterpolationFormatClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken ColonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.InterpolationFormatClauseSyntax)this.Green).colonToken, Position, 0); /// <summary>The text contents of the format specifier for an interpolation.</summary> public SyntaxToken FormatStringToken => new SyntaxToken(this, ((Syntax.InternalSyntax.InterpolationFormatClauseSyntax)this.Green).formatStringToken, GetChildPosition(1), GetChildIndex(1)); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitInterpolationFormatClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitInterpolationFormatClause(this); public InterpolationFormatClauseSyntax Update(SyntaxToken colonToken, SyntaxToken formatStringToken) { if (colonToken != this.ColonToken || formatStringToken != this.FormatStringToken) { var newNode = SyntaxFactory.InterpolationFormatClause(colonToken, formatStringToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public InterpolationFormatClauseSyntax WithColonToken(SyntaxToken colonToken) => Update(colonToken, this.FormatStringToken); public InterpolationFormatClauseSyntax WithFormatStringToken(SyntaxToken formatStringToken) => Update(this.ColonToken, formatStringToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.GlobalStatement"/></description></item> /// </list> /// </remarks> public sealed partial class GlobalStatementSyntax : MemberDeclarationSyntax { private SyntaxNode? attributeLists; private StatementSyntax? statement; internal GlobalStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public StatementSyntax Statement => GetRed(ref this.statement, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.statement, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.statement, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitGlobalStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitGlobalStatement(this); public GlobalStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, StatementSyntax statement) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || statement != this.Statement) { var newNode = SyntaxFactory.GlobalStatement(attributeLists, modifiers, statement); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new GlobalStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.Statement); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new GlobalStatementSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.Statement); public GlobalStatementSyntax WithStatement(StatementSyntax statement) => Update(this.AttributeLists, this.Modifiers, statement); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new GlobalStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new GlobalStatementSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); } /// <summary>Represents the base class for all statements syntax classes.</summary> public abstract partial class StatementSyntax : CSharpSyntaxNode { internal StatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public abstract SyntaxList<AttributeListSyntax> AttributeLists { get; } public StatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeListsCore(attributeLists); internal abstract StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists); public StatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => AddAttributeListsCore(items); internal abstract StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.Block"/></description></item> /// </list> /// </remarks> public sealed partial class BlockSyntax : StatementSyntax { private SyntaxNode? attributeLists; private SyntaxNode? statements; internal BlockSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxToken OpenBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.BlockSyntax)this.Green).openBraceToken, GetChildPosition(1), GetChildIndex(1)); public SyntaxList<StatementSyntax> Statements => new SyntaxList<StatementSyntax>(GetRed(ref this.statements, 2)); public SyntaxToken CloseBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.BlockSyntax)this.Green).closeBraceToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.statements, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.statements, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitBlock(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitBlock(this); public BlockSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken openBraceToken, SyntaxList<StatementSyntax> statements, SyntaxToken closeBraceToken) { if (attributeLists != this.AttributeLists || openBraceToken != this.OpenBraceToken || statements != this.Statements || closeBraceToken != this.CloseBraceToken) { var newNode = SyntaxFactory.Block(attributeLists, openBraceToken, statements, closeBraceToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new BlockSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.OpenBraceToken, this.Statements, this.CloseBraceToken); public BlockSyntax WithOpenBraceToken(SyntaxToken openBraceToken) => Update(this.AttributeLists, openBraceToken, this.Statements, this.CloseBraceToken); public BlockSyntax WithStatements(SyntaxList<StatementSyntax> statements) => Update(this.AttributeLists, this.OpenBraceToken, statements, this.CloseBraceToken); public BlockSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) => Update(this.AttributeLists, this.OpenBraceToken, this.Statements, closeBraceToken); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new BlockSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); public BlockSyntax AddStatements(params StatementSyntax[] items) => WithStatements(this.Statements.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.LocalFunctionStatement"/></description></item> /// </list> /// </remarks> public sealed partial class LocalFunctionStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private TypeSyntax? returnType; private TypeParameterListSyntax? typeParameterList; private ParameterListSyntax? parameterList; private SyntaxNode? constraintClauses; private BlockSyntax? body; private ArrowExpressionClauseSyntax? expressionBody; internal LocalFunctionStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public TypeSyntax ReturnType => GetRed(ref this.returnType, 2)!; /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.LocalFunctionStatementSyntax)this.Green).identifier, GetChildPosition(3), GetChildIndex(3)); public TypeParameterListSyntax? TypeParameterList => GetRed(ref this.typeParameterList, 4); public ParameterListSyntax ParameterList => GetRed(ref this.parameterList, 5)!; public SyntaxList<TypeParameterConstraintClauseSyntax> ConstraintClauses => new SyntaxList<TypeParameterConstraintClauseSyntax>(GetRed(ref this.constraintClauses, 6)); public BlockSyntax? Body => GetRed(ref this.body, 7); public ArrowExpressionClauseSyntax? ExpressionBody => GetRed(ref this.expressionBody, 8); /// <summary>Gets the optional semicolon token.</summary> public SyntaxToken SemicolonToken { get { var slot = ((Syntax.InternalSyntax.LocalFunctionStatementSyntax)this.Green).semicolonToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(9), GetChildIndex(9)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.returnType, 2)!, 4 => GetRed(ref this.typeParameterList, 4), 5 => GetRed(ref this.parameterList, 5)!, 6 => GetRed(ref this.constraintClauses, 6)!, 7 => GetRed(ref this.body, 7), 8 => GetRed(ref this.expressionBody, 8), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.returnType, 4 => this.typeParameterList, 5 => this.parameterList, 6 => this.constraintClauses, 7 => this.body, 8 => this.expressionBody, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitLocalFunctionStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitLocalFunctionStatement(this); public LocalFunctionStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, TypeSyntax returnType, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax parameterList, SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || returnType != this.ReturnType || identifier != this.Identifier || typeParameterList != this.TypeParameterList || parameterList != this.ParameterList || constraintClauses != this.ConstraintClauses || body != this.Body || expressionBody != this.ExpressionBody || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.LocalFunctionStatement(attributeLists, modifiers, returnType, identifier, typeParameterList, parameterList, constraintClauses, body, expressionBody, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new LocalFunctionStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.ReturnType, this.Identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, this.Body, this.ExpressionBody, this.SemicolonToken); public LocalFunctionStatementSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.ReturnType, this.Identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, this.Body, this.ExpressionBody, this.SemicolonToken); public LocalFunctionStatementSyntax WithReturnType(TypeSyntax returnType) => Update(this.AttributeLists, this.Modifiers, returnType, this.Identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, this.Body, this.ExpressionBody, this.SemicolonToken); public LocalFunctionStatementSyntax WithIdentifier(SyntaxToken identifier) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, this.Body, this.ExpressionBody, this.SemicolonToken); public LocalFunctionStatementSyntax WithTypeParameterList(TypeParameterListSyntax? typeParameterList) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.Identifier, typeParameterList, this.ParameterList, this.ConstraintClauses, this.Body, this.ExpressionBody, this.SemicolonToken); public LocalFunctionStatementSyntax WithParameterList(ParameterListSyntax parameterList) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.Identifier, this.TypeParameterList, parameterList, this.ConstraintClauses, this.Body, this.ExpressionBody, this.SemicolonToken); public LocalFunctionStatementSyntax WithConstraintClauses(SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.Identifier, this.TypeParameterList, this.ParameterList, constraintClauses, this.Body, this.ExpressionBody, this.SemicolonToken); public LocalFunctionStatementSyntax WithBody(BlockSyntax? body) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.Identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, body, this.ExpressionBody, this.SemicolonToken); public LocalFunctionStatementSyntax WithExpressionBody(ArrowExpressionClauseSyntax? expressionBody) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.Identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, this.Body, expressionBody, this.SemicolonToken); public LocalFunctionStatementSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.Identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, this.Body, this.ExpressionBody, semicolonToken); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new LocalFunctionStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); public LocalFunctionStatementSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); public LocalFunctionStatementSyntax AddTypeParameterListParameters(params TypeParameterSyntax[] items) { var typeParameterList = this.TypeParameterList ?? SyntaxFactory.TypeParameterList(); return WithTypeParameterList(typeParameterList.WithParameters(typeParameterList.Parameters.AddRange(items))); } public LocalFunctionStatementSyntax AddParameterListParameters(params ParameterSyntax[] items) => WithParameterList(this.ParameterList.WithParameters(this.ParameterList.Parameters.AddRange(items))); public LocalFunctionStatementSyntax AddConstraintClauses(params TypeParameterConstraintClauseSyntax[] items) => WithConstraintClauses(this.ConstraintClauses.AddRange(items)); public LocalFunctionStatementSyntax AddBodyAttributeLists(params AttributeListSyntax[] items) { var body = this.Body ?? SyntaxFactory.Block(); return WithBody(body.WithAttributeLists(body.AttributeLists.AddRange(items))); } public LocalFunctionStatementSyntax AddBodyStatements(params StatementSyntax[] items) { var body = this.Body ?? SyntaxFactory.Block(); return WithBody(body.WithStatements(body.Statements.AddRange(items))); } } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.LocalDeclarationStatement"/></description></item> /// </list> /// </remarks> public sealed partial class LocalDeclarationStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private VariableDeclarationSyntax? declaration; internal LocalDeclarationStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxToken AwaitKeyword { get { var slot = ((Syntax.InternalSyntax.LocalDeclarationStatementSyntax)this.Green).awaitKeyword; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public SyntaxToken UsingKeyword { get { var slot = ((Syntax.InternalSyntax.LocalDeclarationStatementSyntax)this.Green).usingKeyword; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(2), GetChildIndex(2)) : default; } } /// <summary>Gets the modifier list.</summary> public SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(3); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(3), GetChildIndex(3)) : default; } } public VariableDeclarationSyntax Declaration => GetRed(ref this.declaration, 4)!; public SyntaxToken SemicolonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.LocalDeclarationStatementSyntax)this.Green).semicolonToken, GetChildPosition(5), GetChildIndex(5)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 4 => GetRed(ref this.declaration, 4)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 4 => this.declaration, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitLocalDeclarationStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitLocalDeclarationStatement(this); public LocalDeclarationStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken awaitKeyword, SyntaxToken usingKeyword, SyntaxTokenList modifiers, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || awaitKeyword != this.AwaitKeyword || usingKeyword != this.UsingKeyword || modifiers != this.Modifiers || declaration != this.Declaration || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.LocalDeclarationStatement(attributeLists, awaitKeyword, usingKeyword, modifiers, declaration, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new LocalDeclarationStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.AwaitKeyword, this.UsingKeyword, this.Modifiers, this.Declaration, this.SemicolonToken); public LocalDeclarationStatementSyntax WithAwaitKeyword(SyntaxToken awaitKeyword) => Update(this.AttributeLists, awaitKeyword, this.UsingKeyword, this.Modifiers, this.Declaration, this.SemicolonToken); public LocalDeclarationStatementSyntax WithUsingKeyword(SyntaxToken usingKeyword) => Update(this.AttributeLists, this.AwaitKeyword, usingKeyword, this.Modifiers, this.Declaration, this.SemicolonToken); public LocalDeclarationStatementSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, this.AwaitKeyword, this.UsingKeyword, modifiers, this.Declaration, this.SemicolonToken); public LocalDeclarationStatementSyntax WithDeclaration(VariableDeclarationSyntax declaration) => Update(this.AttributeLists, this.AwaitKeyword, this.UsingKeyword, this.Modifiers, declaration, this.SemicolonToken); public LocalDeclarationStatementSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.AwaitKeyword, this.UsingKeyword, this.Modifiers, this.Declaration, semicolonToken); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new LocalDeclarationStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); public LocalDeclarationStatementSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); public LocalDeclarationStatementSyntax AddDeclarationVariables(params VariableDeclaratorSyntax[] items) => WithDeclaration(this.Declaration.WithVariables(this.Declaration.Variables.AddRange(items))); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.VariableDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class VariableDeclarationSyntax : CSharpSyntaxNode { private TypeSyntax? type; private SyntaxNode? variables; internal VariableDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public TypeSyntax Type => GetRedAtZero(ref this.type)!; public SeparatedSyntaxList<VariableDeclaratorSyntax> Variables { get { var red = GetRed(ref this.variables, 1); return red != null ? new SeparatedSyntaxList<VariableDeclaratorSyntax>(red, GetChildIndex(1)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.type)!, 1 => GetRed(ref this.variables, 1)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.type, 1 => this.variables, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitVariableDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitVariableDeclaration(this); public VariableDeclarationSyntax Update(TypeSyntax type, SeparatedSyntaxList<VariableDeclaratorSyntax> variables) { if (type != this.Type || variables != this.Variables) { var newNode = SyntaxFactory.VariableDeclaration(type, variables); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public VariableDeclarationSyntax WithType(TypeSyntax type) => Update(type, this.Variables); public VariableDeclarationSyntax WithVariables(SeparatedSyntaxList<VariableDeclaratorSyntax> variables) => Update(this.Type, variables); public VariableDeclarationSyntax AddVariables(params VariableDeclaratorSyntax[] items) => WithVariables(this.Variables.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.VariableDeclarator"/></description></item> /// </list> /// </remarks> public sealed partial class VariableDeclaratorSyntax : CSharpSyntaxNode { private BracketedArgumentListSyntax? argumentList; private EqualsValueClauseSyntax? initializer; internal VariableDeclaratorSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.VariableDeclaratorSyntax)this.Green).identifier, Position, 0); public BracketedArgumentListSyntax? ArgumentList => GetRed(ref this.argumentList, 1); public EqualsValueClauseSyntax? Initializer => GetRed(ref this.initializer, 2); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 1 => GetRed(ref this.argumentList, 1), 2 => GetRed(ref this.initializer, 2), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 1 => this.argumentList, 2 => this.initializer, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitVariableDeclarator(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitVariableDeclarator(this); public VariableDeclaratorSyntax Update(SyntaxToken identifier, BracketedArgumentListSyntax? argumentList, EqualsValueClauseSyntax? initializer) { if (identifier != this.Identifier || argumentList != this.ArgumentList || initializer != this.Initializer) { var newNode = SyntaxFactory.VariableDeclarator(identifier, argumentList, initializer); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public VariableDeclaratorSyntax WithIdentifier(SyntaxToken identifier) => Update(identifier, this.ArgumentList, this.Initializer); public VariableDeclaratorSyntax WithArgumentList(BracketedArgumentListSyntax? argumentList) => Update(this.Identifier, argumentList, this.Initializer); public VariableDeclaratorSyntax WithInitializer(EqualsValueClauseSyntax? initializer) => Update(this.Identifier, this.ArgumentList, initializer); public VariableDeclaratorSyntax AddArgumentListArguments(params ArgumentSyntax[] items) { var argumentList = this.ArgumentList ?? SyntaxFactory.BracketedArgumentList(); return WithArgumentList(argumentList.WithArguments(argumentList.Arguments.AddRange(items))); } } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.EqualsValueClause"/></description></item> /// </list> /// </remarks> public sealed partial class EqualsValueClauseSyntax : CSharpSyntaxNode { private ExpressionSyntax? value; internal EqualsValueClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken EqualsToken => new SyntaxToken(this, ((Syntax.InternalSyntax.EqualsValueClauseSyntax)this.Green).equalsToken, Position, 0); public ExpressionSyntax Value => GetRed(ref this.value, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.value, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.value : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitEqualsValueClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitEqualsValueClause(this); public EqualsValueClauseSyntax Update(SyntaxToken equalsToken, ExpressionSyntax value) { if (equalsToken != this.EqualsToken || value != this.Value) { var newNode = SyntaxFactory.EqualsValueClause(equalsToken, value); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public EqualsValueClauseSyntax WithEqualsToken(SyntaxToken equalsToken) => Update(equalsToken, this.Value); public EqualsValueClauseSyntax WithValue(ExpressionSyntax value) => Update(this.EqualsToken, value); } public abstract partial class VariableDesignationSyntax : CSharpSyntaxNode { internal VariableDesignationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.SingleVariableDesignation"/></description></item> /// </list> /// </remarks> public sealed partial class SingleVariableDesignationSyntax : VariableDesignationSyntax { internal SingleVariableDesignationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.SingleVariableDesignationSyntax)this.Green).identifier, Position, 0); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitSingleVariableDesignation(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitSingleVariableDesignation(this); public SingleVariableDesignationSyntax Update(SyntaxToken identifier) { if (identifier != this.Identifier) { var newNode = SyntaxFactory.SingleVariableDesignation(identifier); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public SingleVariableDesignationSyntax WithIdentifier(SyntaxToken identifier) => Update(identifier); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.DiscardDesignation"/></description></item> /// </list> /// </remarks> public sealed partial class DiscardDesignationSyntax : VariableDesignationSyntax { internal DiscardDesignationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken UnderscoreToken => new SyntaxToken(this, ((Syntax.InternalSyntax.DiscardDesignationSyntax)this.Green).underscoreToken, Position, 0); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitDiscardDesignation(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitDiscardDesignation(this); public DiscardDesignationSyntax Update(SyntaxToken underscoreToken) { if (underscoreToken != this.UnderscoreToken) { var newNode = SyntaxFactory.DiscardDesignation(underscoreToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public DiscardDesignationSyntax WithUnderscoreToken(SyntaxToken underscoreToken) => Update(underscoreToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ParenthesizedVariableDesignation"/></description></item> /// </list> /// </remarks> public sealed partial class ParenthesizedVariableDesignationSyntax : VariableDesignationSyntax { private SyntaxNode? variables; internal ParenthesizedVariableDesignationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ParenthesizedVariableDesignationSyntax)this.Green).openParenToken, Position, 0); public SeparatedSyntaxList<VariableDesignationSyntax> Variables { get { var red = GetRed(ref this.variables, 1); return red != null ? new SeparatedSyntaxList<VariableDesignationSyntax>(red, GetChildIndex(1)) : default; } } public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ParenthesizedVariableDesignationSyntax)this.Green).closeParenToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.variables, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.variables : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitParenthesizedVariableDesignation(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitParenthesizedVariableDesignation(this); public ParenthesizedVariableDesignationSyntax Update(SyntaxToken openParenToken, SeparatedSyntaxList<VariableDesignationSyntax> variables, SyntaxToken closeParenToken) { if (openParenToken != this.OpenParenToken || variables != this.Variables || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.ParenthesizedVariableDesignation(openParenToken, variables, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ParenthesizedVariableDesignationSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(openParenToken, this.Variables, this.CloseParenToken); public ParenthesizedVariableDesignationSyntax WithVariables(SeparatedSyntaxList<VariableDesignationSyntax> variables) => Update(this.OpenParenToken, variables, this.CloseParenToken); public ParenthesizedVariableDesignationSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.OpenParenToken, this.Variables, closeParenToken); public ParenthesizedVariableDesignationSyntax AddVariables(params VariableDesignationSyntax[] items) => WithVariables(this.Variables.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ExpressionStatement"/></description></item> /// </list> /// </remarks> public sealed partial class ExpressionStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private ExpressionSyntax? expression; internal ExpressionStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public ExpressionSyntax Expression => GetRed(ref this.expression, 1)!; public SyntaxToken SemicolonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ExpressionStatementSyntax)this.Green).semicolonToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 1 => GetRed(ref this.expression, 1)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 1 => this.expression, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitExpressionStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitExpressionStatement(this); public ExpressionStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, ExpressionSyntax expression, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || expression != this.Expression || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.ExpressionStatement(attributeLists, expression, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new ExpressionStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Expression, this.SemicolonToken); public ExpressionStatementSyntax WithExpression(ExpressionSyntax expression) => Update(this.AttributeLists, expression, this.SemicolonToken); public ExpressionStatementSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Expression, semicolonToken); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new ExpressionStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.EmptyStatement"/></description></item> /// </list> /// </remarks> public sealed partial class EmptyStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; internal EmptyStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxToken SemicolonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.EmptyStatementSyntax)this.Green).semicolonToken, GetChildPosition(1), GetChildIndex(1)); internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.attributeLists)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.attributeLists : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitEmptyStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitEmptyStatement(this); public EmptyStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.EmptyStatement(attributeLists, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new EmptyStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.SemicolonToken); public EmptyStatementSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, semicolonToken); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new EmptyStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); } /// <summary>Represents a labeled statement syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.LabeledStatement"/></description></item> /// </list> /// </remarks> public sealed partial class LabeledStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private StatementSyntax? statement; internal LabeledStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.LabeledStatementSyntax)this.Green).identifier, GetChildPosition(1), GetChildIndex(1)); /// <summary>Gets a SyntaxToken that represents the colon following the statement's label.</summary> public SyntaxToken ColonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.LabeledStatementSyntax)this.Green).colonToken, GetChildPosition(2), GetChildIndex(2)); public StatementSyntax Statement => GetRed(ref this.statement, 3)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 3 => GetRed(ref this.statement, 3)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 3 => this.statement, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitLabeledStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitLabeledStatement(this); public LabeledStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken identifier, SyntaxToken colonToken, StatementSyntax statement) { if (attributeLists != this.AttributeLists || identifier != this.Identifier || colonToken != this.ColonToken || statement != this.Statement) { var newNode = SyntaxFactory.LabeledStatement(attributeLists, identifier, colonToken, statement); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new LabeledStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Identifier, this.ColonToken, this.Statement); public LabeledStatementSyntax WithIdentifier(SyntaxToken identifier) => Update(this.AttributeLists, identifier, this.ColonToken, this.Statement); public LabeledStatementSyntax WithColonToken(SyntaxToken colonToken) => Update(this.AttributeLists, this.Identifier, colonToken, this.Statement); public LabeledStatementSyntax WithStatement(StatementSyntax statement) => Update(this.AttributeLists, this.Identifier, this.ColonToken, statement); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new LabeledStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); } /// <summary> /// Represents a goto statement syntax /// </summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.GotoStatement"/></description></item> /// <item><description><see cref="SyntaxKind.GotoCaseStatement"/></description></item> /// <item><description><see cref="SyntaxKind.GotoDefaultStatement"/></description></item> /// </list> /// </remarks> public sealed partial class GotoStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private ExpressionSyntax? expression; internal GotoStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); /// <summary> /// Gets a SyntaxToken that represents the goto keyword. /// </summary> public SyntaxToken GotoKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.GotoStatementSyntax)this.Green).gotoKeyword, GetChildPosition(1), GetChildIndex(1)); /// <summary> /// Gets a SyntaxToken that represents the case or default keywords if any exists. /// </summary> public SyntaxToken CaseOrDefaultKeyword { get { var slot = ((Syntax.InternalSyntax.GotoStatementSyntax)this.Green).caseOrDefaultKeyword; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(2), GetChildIndex(2)) : default; } } /// <summary> /// Gets a constant expression for a goto case statement. /// </summary> public ExpressionSyntax? Expression => GetRed(ref this.expression, 3); /// <summary> /// Gets a SyntaxToken that represents the semi-colon at the end of the statement. /// </summary> public SyntaxToken SemicolonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.GotoStatementSyntax)this.Green).semicolonToken, GetChildPosition(4), GetChildIndex(4)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 3 => GetRed(ref this.expression, 3), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 3 => this.expression, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitGotoStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitGotoStatement(this); public GotoStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken gotoKeyword, SyntaxToken caseOrDefaultKeyword, ExpressionSyntax? expression, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || gotoKeyword != this.GotoKeyword || caseOrDefaultKeyword != this.CaseOrDefaultKeyword || expression != this.Expression || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.GotoStatement(this.Kind(), attributeLists, gotoKeyword, caseOrDefaultKeyword, expression, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new GotoStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.GotoKeyword, this.CaseOrDefaultKeyword, this.Expression, this.SemicolonToken); public GotoStatementSyntax WithGotoKeyword(SyntaxToken gotoKeyword) => Update(this.AttributeLists, gotoKeyword, this.CaseOrDefaultKeyword, this.Expression, this.SemicolonToken); public GotoStatementSyntax WithCaseOrDefaultKeyword(SyntaxToken caseOrDefaultKeyword) => Update(this.AttributeLists, this.GotoKeyword, caseOrDefaultKeyword, this.Expression, this.SemicolonToken); public GotoStatementSyntax WithExpression(ExpressionSyntax? expression) => Update(this.AttributeLists, this.GotoKeyword, this.CaseOrDefaultKeyword, expression, this.SemicolonToken); public GotoStatementSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.GotoKeyword, this.CaseOrDefaultKeyword, this.Expression, semicolonToken); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new GotoStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.BreakStatement"/></description></item> /// </list> /// </remarks> public sealed partial class BreakStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; internal BreakStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxToken BreakKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.BreakStatementSyntax)this.Green).breakKeyword, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken SemicolonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.BreakStatementSyntax)this.Green).semicolonToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.attributeLists)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.attributeLists : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitBreakStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitBreakStatement(this); public BreakStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken breakKeyword, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || breakKeyword != this.BreakKeyword || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.BreakStatement(attributeLists, breakKeyword, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new BreakStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.BreakKeyword, this.SemicolonToken); public BreakStatementSyntax WithBreakKeyword(SyntaxToken breakKeyword) => Update(this.AttributeLists, breakKeyword, this.SemicolonToken); public BreakStatementSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.BreakKeyword, semicolonToken); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new BreakStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ContinueStatement"/></description></item> /// </list> /// </remarks> public sealed partial class ContinueStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; internal ContinueStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxToken ContinueKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ContinueStatementSyntax)this.Green).continueKeyword, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken SemicolonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ContinueStatementSyntax)this.Green).semicolonToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.attributeLists)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.attributeLists : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitContinueStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitContinueStatement(this); public ContinueStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken continueKeyword, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || continueKeyword != this.ContinueKeyword || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.ContinueStatement(attributeLists, continueKeyword, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new ContinueStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.ContinueKeyword, this.SemicolonToken); public ContinueStatementSyntax WithContinueKeyword(SyntaxToken continueKeyword) => Update(this.AttributeLists, continueKeyword, this.SemicolonToken); public ContinueStatementSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.ContinueKeyword, semicolonToken); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new ContinueStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ReturnStatement"/></description></item> /// </list> /// </remarks> public sealed partial class ReturnStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private ExpressionSyntax? expression; internal ReturnStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxToken ReturnKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ReturnStatementSyntax)this.Green).returnKeyword, GetChildPosition(1), GetChildIndex(1)); public ExpressionSyntax? Expression => GetRed(ref this.expression, 2); public SyntaxToken SemicolonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ReturnStatementSyntax)this.Green).semicolonToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.expression, 2), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.expression, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitReturnStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitReturnStatement(this); public ReturnStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken returnKeyword, ExpressionSyntax? expression, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || returnKeyword != this.ReturnKeyword || expression != this.Expression || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.ReturnStatement(attributeLists, returnKeyword, expression, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new ReturnStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.ReturnKeyword, this.Expression, this.SemicolonToken); public ReturnStatementSyntax WithReturnKeyword(SyntaxToken returnKeyword) => Update(this.AttributeLists, returnKeyword, this.Expression, this.SemicolonToken); public ReturnStatementSyntax WithExpression(ExpressionSyntax? expression) => Update(this.AttributeLists, this.ReturnKeyword, expression, this.SemicolonToken); public ReturnStatementSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.ReturnKeyword, this.Expression, semicolonToken); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new ReturnStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ThrowStatement"/></description></item> /// </list> /// </remarks> public sealed partial class ThrowStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private ExpressionSyntax? expression; internal ThrowStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxToken ThrowKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ThrowStatementSyntax)this.Green).throwKeyword, GetChildPosition(1), GetChildIndex(1)); public ExpressionSyntax? Expression => GetRed(ref this.expression, 2); public SyntaxToken SemicolonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ThrowStatementSyntax)this.Green).semicolonToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.expression, 2), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.expression, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitThrowStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitThrowStatement(this); public ThrowStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken throwKeyword, ExpressionSyntax? expression, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || throwKeyword != this.ThrowKeyword || expression != this.Expression || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.ThrowStatement(attributeLists, throwKeyword, expression, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new ThrowStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.ThrowKeyword, this.Expression, this.SemicolonToken); public ThrowStatementSyntax WithThrowKeyword(SyntaxToken throwKeyword) => Update(this.AttributeLists, throwKeyword, this.Expression, this.SemicolonToken); public ThrowStatementSyntax WithExpression(ExpressionSyntax? expression) => Update(this.AttributeLists, this.ThrowKeyword, expression, this.SemicolonToken); public ThrowStatementSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.ThrowKeyword, this.Expression, semicolonToken); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new ThrowStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.YieldReturnStatement"/></description></item> /// <item><description><see cref="SyntaxKind.YieldBreakStatement"/></description></item> /// </list> /// </remarks> public sealed partial class YieldStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private ExpressionSyntax? expression; internal YieldStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxToken YieldKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.YieldStatementSyntax)this.Green).yieldKeyword, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken ReturnOrBreakKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.YieldStatementSyntax)this.Green).returnOrBreakKeyword, GetChildPosition(2), GetChildIndex(2)); public ExpressionSyntax? Expression => GetRed(ref this.expression, 3); public SyntaxToken SemicolonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.YieldStatementSyntax)this.Green).semicolonToken, GetChildPosition(4), GetChildIndex(4)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 3 => GetRed(ref this.expression, 3), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 3 => this.expression, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitYieldStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitYieldStatement(this); public YieldStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken yieldKeyword, SyntaxToken returnOrBreakKeyword, ExpressionSyntax? expression, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || yieldKeyword != this.YieldKeyword || returnOrBreakKeyword != this.ReturnOrBreakKeyword || expression != this.Expression || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.YieldStatement(this.Kind(), attributeLists, yieldKeyword, returnOrBreakKeyword, expression, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new YieldStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.YieldKeyword, this.ReturnOrBreakKeyword, this.Expression, this.SemicolonToken); public YieldStatementSyntax WithYieldKeyword(SyntaxToken yieldKeyword) => Update(this.AttributeLists, yieldKeyword, this.ReturnOrBreakKeyword, this.Expression, this.SemicolonToken); public YieldStatementSyntax WithReturnOrBreakKeyword(SyntaxToken returnOrBreakKeyword) => Update(this.AttributeLists, this.YieldKeyword, returnOrBreakKeyword, this.Expression, this.SemicolonToken); public YieldStatementSyntax WithExpression(ExpressionSyntax? expression) => Update(this.AttributeLists, this.YieldKeyword, this.ReturnOrBreakKeyword, expression, this.SemicolonToken); public YieldStatementSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.YieldKeyword, this.ReturnOrBreakKeyword, this.Expression, semicolonToken); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new YieldStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.WhileStatement"/></description></item> /// </list> /// </remarks> public sealed partial class WhileStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private ExpressionSyntax? condition; private StatementSyntax? statement; internal WhileStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxToken WhileKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.WhileStatementSyntax)this.Green).whileKeyword, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.WhileStatementSyntax)this.Green).openParenToken, GetChildPosition(2), GetChildIndex(2)); public ExpressionSyntax Condition => GetRed(ref this.condition, 3)!; public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.WhileStatementSyntax)this.Green).closeParenToken, GetChildPosition(4), GetChildIndex(4)); public StatementSyntax Statement => GetRed(ref this.statement, 5)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 3 => GetRed(ref this.condition, 3)!, 5 => GetRed(ref this.statement, 5)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 3 => this.condition, 5 => this.statement, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitWhileStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitWhileStatement(this); public WhileStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, StatementSyntax statement) { if (attributeLists != this.AttributeLists || whileKeyword != this.WhileKeyword || openParenToken != this.OpenParenToken || condition != this.Condition || closeParenToken != this.CloseParenToken || statement != this.Statement) { var newNode = SyntaxFactory.WhileStatement(attributeLists, whileKeyword, openParenToken, condition, closeParenToken, statement); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new WhileStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.WhileKeyword, this.OpenParenToken, this.Condition, this.CloseParenToken, this.Statement); public WhileStatementSyntax WithWhileKeyword(SyntaxToken whileKeyword) => Update(this.AttributeLists, whileKeyword, this.OpenParenToken, this.Condition, this.CloseParenToken, this.Statement); public WhileStatementSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.AttributeLists, this.WhileKeyword, openParenToken, this.Condition, this.CloseParenToken, this.Statement); public WhileStatementSyntax WithCondition(ExpressionSyntax condition) => Update(this.AttributeLists, this.WhileKeyword, this.OpenParenToken, condition, this.CloseParenToken, this.Statement); public WhileStatementSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.AttributeLists, this.WhileKeyword, this.OpenParenToken, this.Condition, closeParenToken, this.Statement); public WhileStatementSyntax WithStatement(StatementSyntax statement) => Update(this.AttributeLists, this.WhileKeyword, this.OpenParenToken, this.Condition, this.CloseParenToken, statement); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new WhileStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.DoStatement"/></description></item> /// </list> /// </remarks> public sealed partial class DoStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private StatementSyntax? statement; private ExpressionSyntax? condition; internal DoStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxToken DoKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.DoStatementSyntax)this.Green).doKeyword, GetChildPosition(1), GetChildIndex(1)); public StatementSyntax Statement => GetRed(ref this.statement, 2)!; public SyntaxToken WhileKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.DoStatementSyntax)this.Green).whileKeyword, GetChildPosition(3), GetChildIndex(3)); public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.DoStatementSyntax)this.Green).openParenToken, GetChildPosition(4), GetChildIndex(4)); public ExpressionSyntax Condition => GetRed(ref this.condition, 5)!; public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.DoStatementSyntax)this.Green).closeParenToken, GetChildPosition(6), GetChildIndex(6)); public SyntaxToken SemicolonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.DoStatementSyntax)this.Green).semicolonToken, GetChildPosition(7), GetChildIndex(7)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.statement, 2)!, 5 => GetRed(ref this.condition, 5)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.statement, 5 => this.condition, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitDoStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitDoStatement(this); public DoStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken doKeyword, StatementSyntax statement, SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || doKeyword != this.DoKeyword || statement != this.Statement || whileKeyword != this.WhileKeyword || openParenToken != this.OpenParenToken || condition != this.Condition || closeParenToken != this.CloseParenToken || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.DoStatement(attributeLists, doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new DoStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.DoKeyword, this.Statement, this.WhileKeyword, this.OpenParenToken, this.Condition, this.CloseParenToken, this.SemicolonToken); public DoStatementSyntax WithDoKeyword(SyntaxToken doKeyword) => Update(this.AttributeLists, doKeyword, this.Statement, this.WhileKeyword, this.OpenParenToken, this.Condition, this.CloseParenToken, this.SemicolonToken); public DoStatementSyntax WithStatement(StatementSyntax statement) => Update(this.AttributeLists, this.DoKeyword, statement, this.WhileKeyword, this.OpenParenToken, this.Condition, this.CloseParenToken, this.SemicolonToken); public DoStatementSyntax WithWhileKeyword(SyntaxToken whileKeyword) => Update(this.AttributeLists, this.DoKeyword, this.Statement, whileKeyword, this.OpenParenToken, this.Condition, this.CloseParenToken, this.SemicolonToken); public DoStatementSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.AttributeLists, this.DoKeyword, this.Statement, this.WhileKeyword, openParenToken, this.Condition, this.CloseParenToken, this.SemicolonToken); public DoStatementSyntax WithCondition(ExpressionSyntax condition) => Update(this.AttributeLists, this.DoKeyword, this.Statement, this.WhileKeyword, this.OpenParenToken, condition, this.CloseParenToken, this.SemicolonToken); public DoStatementSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.AttributeLists, this.DoKeyword, this.Statement, this.WhileKeyword, this.OpenParenToken, this.Condition, closeParenToken, this.SemicolonToken); public DoStatementSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.DoKeyword, this.Statement, this.WhileKeyword, this.OpenParenToken, this.Condition, this.CloseParenToken, semicolonToken); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new DoStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ForStatement"/></description></item> /// </list> /// </remarks> public sealed partial class ForStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private VariableDeclarationSyntax? declaration; private SyntaxNode? initializers; private ExpressionSyntax? condition; private SyntaxNode? incrementors; private StatementSyntax? statement; internal ForStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxToken ForKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ForStatementSyntax)this.Green).forKeyword, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ForStatementSyntax)this.Green).openParenToken, GetChildPosition(2), GetChildIndex(2)); public VariableDeclarationSyntax? Declaration => GetRed(ref this.declaration, 3); public SeparatedSyntaxList<ExpressionSyntax> Initializers { get { var red = GetRed(ref this.initializers, 4); return red != null ? new SeparatedSyntaxList<ExpressionSyntax>(red, GetChildIndex(4)) : default; } } public SyntaxToken FirstSemicolonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ForStatementSyntax)this.Green).firstSemicolonToken, GetChildPosition(5), GetChildIndex(5)); public ExpressionSyntax? Condition => GetRed(ref this.condition, 6); public SyntaxToken SecondSemicolonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ForStatementSyntax)this.Green).secondSemicolonToken, GetChildPosition(7), GetChildIndex(7)); public SeparatedSyntaxList<ExpressionSyntax> Incrementors { get { var red = GetRed(ref this.incrementors, 8); return red != null ? new SeparatedSyntaxList<ExpressionSyntax>(red, GetChildIndex(8)) : default; } } public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ForStatementSyntax)this.Green).closeParenToken, GetChildPosition(9), GetChildIndex(9)); public StatementSyntax Statement => GetRed(ref this.statement, 10)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 3 => GetRed(ref this.declaration, 3), 4 => GetRed(ref this.initializers, 4)!, 6 => GetRed(ref this.condition, 6), 8 => GetRed(ref this.incrementors, 8)!, 10 => GetRed(ref this.statement, 10)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 3 => this.declaration, 4 => this.initializers, 6 => this.condition, 8 => this.incrementors, 10 => this.statement, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitForStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitForStatement(this); public ForStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken forKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, SeparatedSyntaxList<ExpressionSyntax> initializers, SyntaxToken firstSemicolonToken, ExpressionSyntax? condition, SyntaxToken secondSemicolonToken, SeparatedSyntaxList<ExpressionSyntax> incrementors, SyntaxToken closeParenToken, StatementSyntax statement) { if (attributeLists != this.AttributeLists || forKeyword != this.ForKeyword || openParenToken != this.OpenParenToken || declaration != this.Declaration || initializers != this.Initializers || firstSemicolonToken != this.FirstSemicolonToken || condition != this.Condition || secondSemicolonToken != this.SecondSemicolonToken || incrementors != this.Incrementors || closeParenToken != this.CloseParenToken || statement != this.Statement) { var newNode = SyntaxFactory.ForStatement(attributeLists, forKeyword, openParenToken, declaration, initializers, firstSemicolonToken, condition, secondSemicolonToken, incrementors, closeParenToken, statement); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new ForStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.ForKeyword, this.OpenParenToken, this.Declaration, this.Initializers, this.FirstSemicolonToken, this.Condition, this.SecondSemicolonToken, this.Incrementors, this.CloseParenToken, this.Statement); public ForStatementSyntax WithForKeyword(SyntaxToken forKeyword) => Update(this.AttributeLists, forKeyword, this.OpenParenToken, this.Declaration, this.Initializers, this.FirstSemicolonToken, this.Condition, this.SecondSemicolonToken, this.Incrementors, this.CloseParenToken, this.Statement); public ForStatementSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.AttributeLists, this.ForKeyword, openParenToken, this.Declaration, this.Initializers, this.FirstSemicolonToken, this.Condition, this.SecondSemicolonToken, this.Incrementors, this.CloseParenToken, this.Statement); public ForStatementSyntax WithDeclaration(VariableDeclarationSyntax? declaration) => Update(this.AttributeLists, this.ForKeyword, this.OpenParenToken, declaration, this.Initializers, this.FirstSemicolonToken, this.Condition, this.SecondSemicolonToken, this.Incrementors, this.CloseParenToken, this.Statement); public ForStatementSyntax WithInitializers(SeparatedSyntaxList<ExpressionSyntax> initializers) => Update(this.AttributeLists, this.ForKeyword, this.OpenParenToken, this.Declaration, initializers, this.FirstSemicolonToken, this.Condition, this.SecondSemicolonToken, this.Incrementors, this.CloseParenToken, this.Statement); public ForStatementSyntax WithFirstSemicolonToken(SyntaxToken firstSemicolonToken) => Update(this.AttributeLists, this.ForKeyword, this.OpenParenToken, this.Declaration, this.Initializers, firstSemicolonToken, this.Condition, this.SecondSemicolonToken, this.Incrementors, this.CloseParenToken, this.Statement); public ForStatementSyntax WithCondition(ExpressionSyntax? condition) => Update(this.AttributeLists, this.ForKeyword, this.OpenParenToken, this.Declaration, this.Initializers, this.FirstSemicolonToken, condition, this.SecondSemicolonToken, this.Incrementors, this.CloseParenToken, this.Statement); public ForStatementSyntax WithSecondSemicolonToken(SyntaxToken secondSemicolonToken) => Update(this.AttributeLists, this.ForKeyword, this.OpenParenToken, this.Declaration, this.Initializers, this.FirstSemicolonToken, this.Condition, secondSemicolonToken, this.Incrementors, this.CloseParenToken, this.Statement); public ForStatementSyntax WithIncrementors(SeparatedSyntaxList<ExpressionSyntax> incrementors) => Update(this.AttributeLists, this.ForKeyword, this.OpenParenToken, this.Declaration, this.Initializers, this.FirstSemicolonToken, this.Condition, this.SecondSemicolonToken, incrementors, this.CloseParenToken, this.Statement); public ForStatementSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.AttributeLists, this.ForKeyword, this.OpenParenToken, this.Declaration, this.Initializers, this.FirstSemicolonToken, this.Condition, this.SecondSemicolonToken, this.Incrementors, closeParenToken, this.Statement); public ForStatementSyntax WithStatement(StatementSyntax statement) => Update(this.AttributeLists, this.ForKeyword, this.OpenParenToken, this.Declaration, this.Initializers, this.FirstSemicolonToken, this.Condition, this.SecondSemicolonToken, this.Incrementors, this.CloseParenToken, statement); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new ForStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); public ForStatementSyntax AddInitializers(params ExpressionSyntax[] items) => WithInitializers(this.Initializers.AddRange(items)); public ForStatementSyntax AddIncrementors(params ExpressionSyntax[] items) => WithIncrementors(this.Incrementors.AddRange(items)); } public abstract partial class CommonForEachStatementSyntax : StatementSyntax { internal CommonForEachStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public abstract SyntaxToken AwaitKeyword { get; } public CommonForEachStatementSyntax WithAwaitKeyword(SyntaxToken awaitKeyword) => WithAwaitKeywordCore(awaitKeyword); internal abstract CommonForEachStatementSyntax WithAwaitKeywordCore(SyntaxToken awaitKeyword); public abstract SyntaxToken ForEachKeyword { get; } public CommonForEachStatementSyntax WithForEachKeyword(SyntaxToken forEachKeyword) => WithForEachKeywordCore(forEachKeyword); internal abstract CommonForEachStatementSyntax WithForEachKeywordCore(SyntaxToken forEachKeyword); public abstract SyntaxToken OpenParenToken { get; } public CommonForEachStatementSyntax WithOpenParenToken(SyntaxToken openParenToken) => WithOpenParenTokenCore(openParenToken); internal abstract CommonForEachStatementSyntax WithOpenParenTokenCore(SyntaxToken openParenToken); public abstract SyntaxToken InKeyword { get; } public CommonForEachStatementSyntax WithInKeyword(SyntaxToken inKeyword) => WithInKeywordCore(inKeyword); internal abstract CommonForEachStatementSyntax WithInKeywordCore(SyntaxToken inKeyword); public abstract ExpressionSyntax Expression { get; } public CommonForEachStatementSyntax WithExpression(ExpressionSyntax expression) => WithExpressionCore(expression); internal abstract CommonForEachStatementSyntax WithExpressionCore(ExpressionSyntax expression); public abstract SyntaxToken CloseParenToken { get; } public CommonForEachStatementSyntax WithCloseParenToken(SyntaxToken closeParenToken) => WithCloseParenTokenCore(closeParenToken); internal abstract CommonForEachStatementSyntax WithCloseParenTokenCore(SyntaxToken closeParenToken); public abstract StatementSyntax Statement { get; } public CommonForEachStatementSyntax WithStatement(StatementSyntax statement) => WithStatementCore(statement); internal abstract CommonForEachStatementSyntax WithStatementCore(StatementSyntax statement); public new CommonForEachStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => (CommonForEachStatementSyntax)WithAttributeListsCore(attributeLists); public new CommonForEachStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => (CommonForEachStatementSyntax)AddAttributeListsCore(items); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ForEachStatement"/></description></item> /// </list> /// </remarks> public sealed partial class ForEachStatementSyntax : CommonForEachStatementSyntax { private SyntaxNode? attributeLists; private TypeSyntax? type; private ExpressionSyntax? expression; private StatementSyntax? statement; internal ForEachStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxToken AwaitKeyword { get { var slot = ((Syntax.InternalSyntax.ForEachStatementSyntax)this.Green).awaitKeyword; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public override SyntaxToken ForEachKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ForEachStatementSyntax)this.Green).forEachKeyword, GetChildPosition(2), GetChildIndex(2)); public override SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ForEachStatementSyntax)this.Green).openParenToken, GetChildPosition(3), GetChildIndex(3)); public TypeSyntax Type => GetRed(ref this.type, 4)!; /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.ForEachStatementSyntax)this.Green).identifier, GetChildPosition(5), GetChildIndex(5)); public override SyntaxToken InKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ForEachStatementSyntax)this.Green).inKeyword, GetChildPosition(6), GetChildIndex(6)); public override ExpressionSyntax Expression => GetRed(ref this.expression, 7)!; public override SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ForEachStatementSyntax)this.Green).closeParenToken, GetChildPosition(8), GetChildIndex(8)); public override StatementSyntax Statement => GetRed(ref this.statement, 9)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 4 => GetRed(ref this.type, 4)!, 7 => GetRed(ref this.expression, 7)!, 9 => GetRed(ref this.statement, 9)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 4 => this.type, 7 => this.expression, 9 => this.statement, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitForEachStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitForEachStatement(this); public ForEachStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken awaitKeyword, SyntaxToken forEachKeyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken identifier, SyntaxToken inKeyword, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement) { if (attributeLists != this.AttributeLists || awaitKeyword != this.AwaitKeyword || forEachKeyword != this.ForEachKeyword || openParenToken != this.OpenParenToken || type != this.Type || identifier != this.Identifier || inKeyword != this.InKeyword || expression != this.Expression || closeParenToken != this.CloseParenToken || statement != this.Statement) { var newNode = SyntaxFactory.ForEachStatement(attributeLists, awaitKeyword, forEachKeyword, openParenToken, type, identifier, inKeyword, expression, closeParenToken, statement); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new ForEachStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.AwaitKeyword, this.ForEachKeyword, this.OpenParenToken, this.Type, this.Identifier, this.InKeyword, this.Expression, this.CloseParenToken, this.Statement); internal override CommonForEachStatementSyntax WithAwaitKeywordCore(SyntaxToken awaitKeyword) => WithAwaitKeyword(awaitKeyword); public new ForEachStatementSyntax WithAwaitKeyword(SyntaxToken awaitKeyword) => Update(this.AttributeLists, awaitKeyword, this.ForEachKeyword, this.OpenParenToken, this.Type, this.Identifier, this.InKeyword, this.Expression, this.CloseParenToken, this.Statement); internal override CommonForEachStatementSyntax WithForEachKeywordCore(SyntaxToken forEachKeyword) => WithForEachKeyword(forEachKeyword); public new ForEachStatementSyntax WithForEachKeyword(SyntaxToken forEachKeyword) => Update(this.AttributeLists, this.AwaitKeyword, forEachKeyword, this.OpenParenToken, this.Type, this.Identifier, this.InKeyword, this.Expression, this.CloseParenToken, this.Statement); internal override CommonForEachStatementSyntax WithOpenParenTokenCore(SyntaxToken openParenToken) => WithOpenParenToken(openParenToken); public new ForEachStatementSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.AttributeLists, this.AwaitKeyword, this.ForEachKeyword, openParenToken, this.Type, this.Identifier, this.InKeyword, this.Expression, this.CloseParenToken, this.Statement); public ForEachStatementSyntax WithType(TypeSyntax type) => Update(this.AttributeLists, this.AwaitKeyword, this.ForEachKeyword, this.OpenParenToken, type, this.Identifier, this.InKeyword, this.Expression, this.CloseParenToken, this.Statement); public ForEachStatementSyntax WithIdentifier(SyntaxToken identifier) => Update(this.AttributeLists, this.AwaitKeyword, this.ForEachKeyword, this.OpenParenToken, this.Type, identifier, this.InKeyword, this.Expression, this.CloseParenToken, this.Statement); internal override CommonForEachStatementSyntax WithInKeywordCore(SyntaxToken inKeyword) => WithInKeyword(inKeyword); public new ForEachStatementSyntax WithInKeyword(SyntaxToken inKeyword) => Update(this.AttributeLists, this.AwaitKeyword, this.ForEachKeyword, this.OpenParenToken, this.Type, this.Identifier, inKeyword, this.Expression, this.CloseParenToken, this.Statement); internal override CommonForEachStatementSyntax WithExpressionCore(ExpressionSyntax expression) => WithExpression(expression); public new ForEachStatementSyntax WithExpression(ExpressionSyntax expression) => Update(this.AttributeLists, this.AwaitKeyword, this.ForEachKeyword, this.OpenParenToken, this.Type, this.Identifier, this.InKeyword, expression, this.CloseParenToken, this.Statement); internal override CommonForEachStatementSyntax WithCloseParenTokenCore(SyntaxToken closeParenToken) => WithCloseParenToken(closeParenToken); public new ForEachStatementSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.AttributeLists, this.AwaitKeyword, this.ForEachKeyword, this.OpenParenToken, this.Type, this.Identifier, this.InKeyword, this.Expression, closeParenToken, this.Statement); internal override CommonForEachStatementSyntax WithStatementCore(StatementSyntax statement) => WithStatement(statement); public new ForEachStatementSyntax WithStatement(StatementSyntax statement) => Update(this.AttributeLists, this.AwaitKeyword, this.ForEachKeyword, this.OpenParenToken, this.Type, this.Identifier, this.InKeyword, this.Expression, this.CloseParenToken, statement); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new ForEachStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ForEachVariableStatement"/></description></item> /// </list> /// </remarks> public sealed partial class ForEachVariableStatementSyntax : CommonForEachStatementSyntax { private SyntaxNode? attributeLists; private ExpressionSyntax? variable; private ExpressionSyntax? expression; private StatementSyntax? statement; internal ForEachVariableStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxToken AwaitKeyword { get { var slot = ((Syntax.InternalSyntax.ForEachVariableStatementSyntax)this.Green).awaitKeyword; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public override SyntaxToken ForEachKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ForEachVariableStatementSyntax)this.Green).forEachKeyword, GetChildPosition(2), GetChildIndex(2)); public override SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ForEachVariableStatementSyntax)this.Green).openParenToken, GetChildPosition(3), GetChildIndex(3)); /// <summary> /// The variable(s) of the loop. In correct code this is a tuple /// literal, declaration expression with a tuple designator, or /// a discard syntax in the form of a simple identifier. In broken /// code it could be something else. /// </summary> public ExpressionSyntax Variable => GetRed(ref this.variable, 4)!; public override SyntaxToken InKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ForEachVariableStatementSyntax)this.Green).inKeyword, GetChildPosition(5), GetChildIndex(5)); public override ExpressionSyntax Expression => GetRed(ref this.expression, 6)!; public override SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ForEachVariableStatementSyntax)this.Green).closeParenToken, GetChildPosition(7), GetChildIndex(7)); public override StatementSyntax Statement => GetRed(ref this.statement, 8)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 4 => GetRed(ref this.variable, 4)!, 6 => GetRed(ref this.expression, 6)!, 8 => GetRed(ref this.statement, 8)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 4 => this.variable, 6 => this.expression, 8 => this.statement, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitForEachVariableStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitForEachVariableStatement(this); public ForEachVariableStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken awaitKeyword, SyntaxToken forEachKeyword, SyntaxToken openParenToken, ExpressionSyntax variable, SyntaxToken inKeyword, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement) { if (attributeLists != this.AttributeLists || awaitKeyword != this.AwaitKeyword || forEachKeyword != this.ForEachKeyword || openParenToken != this.OpenParenToken || variable != this.Variable || inKeyword != this.InKeyword || expression != this.Expression || closeParenToken != this.CloseParenToken || statement != this.Statement) { var newNode = SyntaxFactory.ForEachVariableStatement(attributeLists, awaitKeyword, forEachKeyword, openParenToken, variable, inKeyword, expression, closeParenToken, statement); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new ForEachVariableStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.AwaitKeyword, this.ForEachKeyword, this.OpenParenToken, this.Variable, this.InKeyword, this.Expression, this.CloseParenToken, this.Statement); internal override CommonForEachStatementSyntax WithAwaitKeywordCore(SyntaxToken awaitKeyword) => WithAwaitKeyword(awaitKeyword); public new ForEachVariableStatementSyntax WithAwaitKeyword(SyntaxToken awaitKeyword) => Update(this.AttributeLists, awaitKeyword, this.ForEachKeyword, this.OpenParenToken, this.Variable, this.InKeyword, this.Expression, this.CloseParenToken, this.Statement); internal override CommonForEachStatementSyntax WithForEachKeywordCore(SyntaxToken forEachKeyword) => WithForEachKeyword(forEachKeyword); public new ForEachVariableStatementSyntax WithForEachKeyword(SyntaxToken forEachKeyword) => Update(this.AttributeLists, this.AwaitKeyword, forEachKeyword, this.OpenParenToken, this.Variable, this.InKeyword, this.Expression, this.CloseParenToken, this.Statement); internal override CommonForEachStatementSyntax WithOpenParenTokenCore(SyntaxToken openParenToken) => WithOpenParenToken(openParenToken); public new ForEachVariableStatementSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.AttributeLists, this.AwaitKeyword, this.ForEachKeyword, openParenToken, this.Variable, this.InKeyword, this.Expression, this.CloseParenToken, this.Statement); public ForEachVariableStatementSyntax WithVariable(ExpressionSyntax variable) => Update(this.AttributeLists, this.AwaitKeyword, this.ForEachKeyword, this.OpenParenToken, variable, this.InKeyword, this.Expression, this.CloseParenToken, this.Statement); internal override CommonForEachStatementSyntax WithInKeywordCore(SyntaxToken inKeyword) => WithInKeyword(inKeyword); public new ForEachVariableStatementSyntax WithInKeyword(SyntaxToken inKeyword) => Update(this.AttributeLists, this.AwaitKeyword, this.ForEachKeyword, this.OpenParenToken, this.Variable, inKeyword, this.Expression, this.CloseParenToken, this.Statement); internal override CommonForEachStatementSyntax WithExpressionCore(ExpressionSyntax expression) => WithExpression(expression); public new ForEachVariableStatementSyntax WithExpression(ExpressionSyntax expression) => Update(this.AttributeLists, this.AwaitKeyword, this.ForEachKeyword, this.OpenParenToken, this.Variable, this.InKeyword, expression, this.CloseParenToken, this.Statement); internal override CommonForEachStatementSyntax WithCloseParenTokenCore(SyntaxToken closeParenToken) => WithCloseParenToken(closeParenToken); public new ForEachVariableStatementSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.AttributeLists, this.AwaitKeyword, this.ForEachKeyword, this.OpenParenToken, this.Variable, this.InKeyword, this.Expression, closeParenToken, this.Statement); internal override CommonForEachStatementSyntax WithStatementCore(StatementSyntax statement) => WithStatement(statement); public new ForEachVariableStatementSyntax WithStatement(StatementSyntax statement) => Update(this.AttributeLists, this.AwaitKeyword, this.ForEachKeyword, this.OpenParenToken, this.Variable, this.InKeyword, this.Expression, this.CloseParenToken, statement); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new ForEachVariableStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.UsingStatement"/></description></item> /// </list> /// </remarks> public sealed partial class UsingStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private VariableDeclarationSyntax? declaration; private ExpressionSyntax? expression; private StatementSyntax? statement; internal UsingStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxToken AwaitKeyword { get { var slot = ((Syntax.InternalSyntax.UsingStatementSyntax)this.Green).awaitKeyword; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public SyntaxToken UsingKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.UsingStatementSyntax)this.Green).usingKeyword, GetChildPosition(2), GetChildIndex(2)); public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.UsingStatementSyntax)this.Green).openParenToken, GetChildPosition(3), GetChildIndex(3)); public VariableDeclarationSyntax? Declaration => GetRed(ref this.declaration, 4); public ExpressionSyntax? Expression => GetRed(ref this.expression, 5); public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.UsingStatementSyntax)this.Green).closeParenToken, GetChildPosition(6), GetChildIndex(6)); public StatementSyntax Statement => GetRed(ref this.statement, 7)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 4 => GetRed(ref this.declaration, 4), 5 => GetRed(ref this.expression, 5), 7 => GetRed(ref this.statement, 7)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 4 => this.declaration, 5 => this.expression, 7 => this.statement, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitUsingStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitUsingStatement(this); public UsingStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken awaitKeyword, SyntaxToken usingKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, ExpressionSyntax? expression, SyntaxToken closeParenToken, StatementSyntax statement) { if (attributeLists != this.AttributeLists || awaitKeyword != this.AwaitKeyword || usingKeyword != this.UsingKeyword || openParenToken != this.OpenParenToken || declaration != this.Declaration || expression != this.Expression || closeParenToken != this.CloseParenToken || statement != this.Statement) { var newNode = SyntaxFactory.UsingStatement(attributeLists, awaitKeyword, usingKeyword, openParenToken, declaration, expression, closeParenToken, statement); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new UsingStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.AwaitKeyword, this.UsingKeyword, this.OpenParenToken, this.Declaration, this.Expression, this.CloseParenToken, this.Statement); public UsingStatementSyntax WithAwaitKeyword(SyntaxToken awaitKeyword) => Update(this.AttributeLists, awaitKeyword, this.UsingKeyword, this.OpenParenToken, this.Declaration, this.Expression, this.CloseParenToken, this.Statement); public UsingStatementSyntax WithUsingKeyword(SyntaxToken usingKeyword) => Update(this.AttributeLists, this.AwaitKeyword, usingKeyword, this.OpenParenToken, this.Declaration, this.Expression, this.CloseParenToken, this.Statement); public UsingStatementSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.AttributeLists, this.AwaitKeyword, this.UsingKeyword, openParenToken, this.Declaration, this.Expression, this.CloseParenToken, this.Statement); public UsingStatementSyntax WithDeclaration(VariableDeclarationSyntax? declaration) => Update(this.AttributeLists, this.AwaitKeyword, this.UsingKeyword, this.OpenParenToken, declaration, this.Expression, this.CloseParenToken, this.Statement); public UsingStatementSyntax WithExpression(ExpressionSyntax? expression) => Update(this.AttributeLists, this.AwaitKeyword, this.UsingKeyword, this.OpenParenToken, this.Declaration, expression, this.CloseParenToken, this.Statement); public UsingStatementSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.AttributeLists, this.AwaitKeyword, this.UsingKeyword, this.OpenParenToken, this.Declaration, this.Expression, closeParenToken, this.Statement); public UsingStatementSyntax WithStatement(StatementSyntax statement) => Update(this.AttributeLists, this.AwaitKeyword, this.UsingKeyword, this.OpenParenToken, this.Declaration, this.Expression, this.CloseParenToken, statement); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new UsingStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.FixedStatement"/></description></item> /// </list> /// </remarks> public sealed partial class FixedStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private VariableDeclarationSyntax? declaration; private StatementSyntax? statement; internal FixedStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxToken FixedKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.FixedStatementSyntax)this.Green).fixedKeyword, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.FixedStatementSyntax)this.Green).openParenToken, GetChildPosition(2), GetChildIndex(2)); public VariableDeclarationSyntax Declaration => GetRed(ref this.declaration, 3)!; public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.FixedStatementSyntax)this.Green).closeParenToken, GetChildPosition(4), GetChildIndex(4)); public StatementSyntax Statement => GetRed(ref this.statement, 5)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 3 => GetRed(ref this.declaration, 3)!, 5 => GetRed(ref this.statement, 5)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 3 => this.declaration, 5 => this.statement, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitFixedStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitFixedStatement(this); public FixedStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken fixedKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax declaration, SyntaxToken closeParenToken, StatementSyntax statement) { if (attributeLists != this.AttributeLists || fixedKeyword != this.FixedKeyword || openParenToken != this.OpenParenToken || declaration != this.Declaration || closeParenToken != this.CloseParenToken || statement != this.Statement) { var newNode = SyntaxFactory.FixedStatement(attributeLists, fixedKeyword, openParenToken, declaration, closeParenToken, statement); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new FixedStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.FixedKeyword, this.OpenParenToken, this.Declaration, this.CloseParenToken, this.Statement); public FixedStatementSyntax WithFixedKeyword(SyntaxToken fixedKeyword) => Update(this.AttributeLists, fixedKeyword, this.OpenParenToken, this.Declaration, this.CloseParenToken, this.Statement); public FixedStatementSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.AttributeLists, this.FixedKeyword, openParenToken, this.Declaration, this.CloseParenToken, this.Statement); public FixedStatementSyntax WithDeclaration(VariableDeclarationSyntax declaration) => Update(this.AttributeLists, this.FixedKeyword, this.OpenParenToken, declaration, this.CloseParenToken, this.Statement); public FixedStatementSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.AttributeLists, this.FixedKeyword, this.OpenParenToken, this.Declaration, closeParenToken, this.Statement); public FixedStatementSyntax WithStatement(StatementSyntax statement) => Update(this.AttributeLists, this.FixedKeyword, this.OpenParenToken, this.Declaration, this.CloseParenToken, statement); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new FixedStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); public FixedStatementSyntax AddDeclarationVariables(params VariableDeclaratorSyntax[] items) => WithDeclaration(this.Declaration.WithVariables(this.Declaration.Variables.AddRange(items))); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.CheckedStatement"/></description></item> /// <item><description><see cref="SyntaxKind.UncheckedStatement"/></description></item> /// </list> /// </remarks> public sealed partial class CheckedStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private BlockSyntax? block; internal CheckedStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxToken Keyword => new SyntaxToken(this, ((Syntax.InternalSyntax.CheckedStatementSyntax)this.Green).keyword, GetChildPosition(1), GetChildIndex(1)); public BlockSyntax Block => GetRed(ref this.block, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.block, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.block, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitCheckedStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitCheckedStatement(this); public CheckedStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken keyword, BlockSyntax block) { if (attributeLists != this.AttributeLists || keyword != this.Keyword || block != this.Block) { var newNode = SyntaxFactory.CheckedStatement(this.Kind(), attributeLists, keyword, block); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new CheckedStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Keyword, this.Block); public CheckedStatementSyntax WithKeyword(SyntaxToken keyword) => Update(this.AttributeLists, keyword, this.Block); public CheckedStatementSyntax WithBlock(BlockSyntax block) => Update(this.AttributeLists, this.Keyword, block); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new CheckedStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); public CheckedStatementSyntax AddBlockAttributeLists(params AttributeListSyntax[] items) => WithBlock(this.Block.WithAttributeLists(this.Block.AttributeLists.AddRange(items))); public CheckedStatementSyntax AddBlockStatements(params StatementSyntax[] items) => WithBlock(this.Block.WithStatements(this.Block.Statements.AddRange(items))); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.UnsafeStatement"/></description></item> /// </list> /// </remarks> public sealed partial class UnsafeStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private BlockSyntax? block; internal UnsafeStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxToken UnsafeKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.UnsafeStatementSyntax)this.Green).unsafeKeyword, GetChildPosition(1), GetChildIndex(1)); public BlockSyntax Block => GetRed(ref this.block, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.block, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.block, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitUnsafeStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitUnsafeStatement(this); public UnsafeStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken unsafeKeyword, BlockSyntax block) { if (attributeLists != this.AttributeLists || unsafeKeyword != this.UnsafeKeyword || block != this.Block) { var newNode = SyntaxFactory.UnsafeStatement(attributeLists, unsafeKeyword, block); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new UnsafeStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.UnsafeKeyword, this.Block); public UnsafeStatementSyntax WithUnsafeKeyword(SyntaxToken unsafeKeyword) => Update(this.AttributeLists, unsafeKeyword, this.Block); public UnsafeStatementSyntax WithBlock(BlockSyntax block) => Update(this.AttributeLists, this.UnsafeKeyword, block); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new UnsafeStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); public UnsafeStatementSyntax AddBlockAttributeLists(params AttributeListSyntax[] items) => WithBlock(this.Block.WithAttributeLists(this.Block.AttributeLists.AddRange(items))); public UnsafeStatementSyntax AddBlockStatements(params StatementSyntax[] items) => WithBlock(this.Block.WithStatements(this.Block.Statements.AddRange(items))); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.LockStatement"/></description></item> /// </list> /// </remarks> public sealed partial class LockStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private ExpressionSyntax? expression; private StatementSyntax? statement; internal LockStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxToken LockKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.LockStatementSyntax)this.Green).lockKeyword, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.LockStatementSyntax)this.Green).openParenToken, GetChildPosition(2), GetChildIndex(2)); public ExpressionSyntax Expression => GetRed(ref this.expression, 3)!; public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.LockStatementSyntax)this.Green).closeParenToken, GetChildPosition(4), GetChildIndex(4)); public StatementSyntax Statement => GetRed(ref this.statement, 5)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 3 => GetRed(ref this.expression, 3)!, 5 => GetRed(ref this.statement, 5)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 3 => this.expression, 5 => this.statement, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitLockStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitLockStatement(this); public LockStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken lockKeyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement) { if (attributeLists != this.AttributeLists || lockKeyword != this.LockKeyword || openParenToken != this.OpenParenToken || expression != this.Expression || closeParenToken != this.CloseParenToken || statement != this.Statement) { var newNode = SyntaxFactory.LockStatement(attributeLists, lockKeyword, openParenToken, expression, closeParenToken, statement); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new LockStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.LockKeyword, this.OpenParenToken, this.Expression, this.CloseParenToken, this.Statement); public LockStatementSyntax WithLockKeyword(SyntaxToken lockKeyword) => Update(this.AttributeLists, lockKeyword, this.OpenParenToken, this.Expression, this.CloseParenToken, this.Statement); public LockStatementSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.AttributeLists, this.LockKeyword, openParenToken, this.Expression, this.CloseParenToken, this.Statement); public LockStatementSyntax WithExpression(ExpressionSyntax expression) => Update(this.AttributeLists, this.LockKeyword, this.OpenParenToken, expression, this.CloseParenToken, this.Statement); public LockStatementSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.AttributeLists, this.LockKeyword, this.OpenParenToken, this.Expression, closeParenToken, this.Statement); public LockStatementSyntax WithStatement(StatementSyntax statement) => Update(this.AttributeLists, this.LockKeyword, this.OpenParenToken, this.Expression, this.CloseParenToken, statement); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new LockStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); } /// <summary> /// Represents an if statement syntax. /// </summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.IfStatement"/></description></item> /// </list> /// </remarks> public sealed partial class IfStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private ExpressionSyntax? condition; private StatementSyntax? statement; private ElseClauseSyntax? @else; internal IfStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); /// <summary> /// Gets a SyntaxToken that represents the if keyword. /// </summary> public SyntaxToken IfKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.IfStatementSyntax)this.Green).ifKeyword, GetChildPosition(1), GetChildIndex(1)); /// <summary> /// Gets a SyntaxToken that represents the open parenthesis before the if statement's condition expression. /// </summary> public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.IfStatementSyntax)this.Green).openParenToken, GetChildPosition(2), GetChildIndex(2)); /// <summary> /// Gets an ExpressionSyntax that represents the condition of the if statement. /// </summary> public ExpressionSyntax Condition => GetRed(ref this.condition, 3)!; /// <summary> /// Gets a SyntaxToken that represents the close parenthesis after the if statement's condition expression. /// </summary> public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.IfStatementSyntax)this.Green).closeParenToken, GetChildPosition(4), GetChildIndex(4)); /// <summary> /// Gets a StatementSyntax the represents the statement to be executed when the condition is true. /// </summary> public StatementSyntax Statement => GetRed(ref this.statement, 5)!; /// <summary> /// Gets an ElseClauseSyntax that represents the statement to be executed when the condition is false if such statement exists. /// </summary> public ElseClauseSyntax? Else => GetRed(ref this.@else, 6); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 3 => GetRed(ref this.condition, 3)!, 5 => GetRed(ref this.statement, 5)!, 6 => GetRed(ref this.@else, 6), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 3 => this.condition, 5 => this.statement, 6 => this.@else, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitIfStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitIfStatement(this); public IfStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken ifKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, StatementSyntax statement, ElseClauseSyntax? @else) { if (attributeLists != this.AttributeLists || ifKeyword != this.IfKeyword || openParenToken != this.OpenParenToken || condition != this.Condition || closeParenToken != this.CloseParenToken || statement != this.Statement || @else != this.Else) { var newNode = SyntaxFactory.IfStatement(attributeLists, ifKeyword, openParenToken, condition, closeParenToken, statement, @else); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new IfStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.IfKeyword, this.OpenParenToken, this.Condition, this.CloseParenToken, this.Statement, this.Else); public IfStatementSyntax WithIfKeyword(SyntaxToken ifKeyword) => Update(this.AttributeLists, ifKeyword, this.OpenParenToken, this.Condition, this.CloseParenToken, this.Statement, this.Else); public IfStatementSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.AttributeLists, this.IfKeyword, openParenToken, this.Condition, this.CloseParenToken, this.Statement, this.Else); public IfStatementSyntax WithCondition(ExpressionSyntax condition) => Update(this.AttributeLists, this.IfKeyword, this.OpenParenToken, condition, this.CloseParenToken, this.Statement, this.Else); public IfStatementSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.AttributeLists, this.IfKeyword, this.OpenParenToken, this.Condition, closeParenToken, this.Statement, this.Else); public IfStatementSyntax WithStatement(StatementSyntax statement) => Update(this.AttributeLists, this.IfKeyword, this.OpenParenToken, this.Condition, this.CloseParenToken, statement, this.Else); public IfStatementSyntax WithElse(ElseClauseSyntax? @else) => Update(this.AttributeLists, this.IfKeyword, this.OpenParenToken, this.Condition, this.CloseParenToken, this.Statement, @else); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new IfStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); } /// <summary>Represents an else statement syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ElseClause"/></description></item> /// </list> /// </remarks> public sealed partial class ElseClauseSyntax : CSharpSyntaxNode { private StatementSyntax? statement; internal ElseClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary> /// Gets a syntax token /// </summary> public SyntaxToken ElseKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ElseClauseSyntax)this.Green).elseKeyword, Position, 0); public StatementSyntax Statement => GetRed(ref this.statement, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.statement, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.statement : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitElseClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitElseClause(this); public ElseClauseSyntax Update(SyntaxToken elseKeyword, StatementSyntax statement) { if (elseKeyword != this.ElseKeyword || statement != this.Statement) { var newNode = SyntaxFactory.ElseClause(elseKeyword, statement); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ElseClauseSyntax WithElseKeyword(SyntaxToken elseKeyword) => Update(elseKeyword, this.Statement); public ElseClauseSyntax WithStatement(StatementSyntax statement) => Update(this.ElseKeyword, statement); } /// <summary>Represents a switch statement syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.SwitchStatement"/></description></item> /// </list> /// </remarks> public sealed partial class SwitchStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private ExpressionSyntax? expression; private SyntaxNode? sections; internal SwitchStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); /// <summary> /// Gets a SyntaxToken that represents the switch keyword. /// </summary> public SyntaxToken SwitchKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.SwitchStatementSyntax)this.Green).switchKeyword, GetChildPosition(1), GetChildIndex(1)); /// <summary> /// Gets a SyntaxToken that represents the open parenthesis preceding the switch governing expression. /// </summary> public SyntaxToken OpenParenToken { get { var slot = ((Syntax.InternalSyntax.SwitchStatementSyntax)this.Green).openParenToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(2), GetChildIndex(2)) : default; } } /// <summary> /// Gets an ExpressionSyntax representing the expression of the switch statement. /// </summary> public ExpressionSyntax Expression => GetRed(ref this.expression, 3)!; /// <summary> /// Gets a SyntaxToken that represents the close parenthesis following the switch governing expression. /// </summary> public SyntaxToken CloseParenToken { get { var slot = ((Syntax.InternalSyntax.SwitchStatementSyntax)this.Green).closeParenToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(4), GetChildIndex(4)) : default; } } /// <summary> /// Gets a SyntaxToken that represents the open braces preceding the switch sections. /// </summary> public SyntaxToken OpenBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.SwitchStatementSyntax)this.Green).openBraceToken, GetChildPosition(5), GetChildIndex(5)); /// <summary> /// Gets a SyntaxList of SwitchSectionSyntax's that represents the switch sections of the switch statement. /// </summary> public SyntaxList<SwitchSectionSyntax> Sections => new SyntaxList<SwitchSectionSyntax>(GetRed(ref this.sections, 6)); /// <summary> /// Gets a SyntaxToken that represents the open braces following the switch sections. /// </summary> public SyntaxToken CloseBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.SwitchStatementSyntax)this.Green).closeBraceToken, GetChildPosition(7), GetChildIndex(7)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 3 => GetRed(ref this.expression, 3)!, 6 => GetRed(ref this.sections, 6)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 3 => this.expression, 6 => this.sections, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitSwitchStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitSwitchStatement(this); public SwitchStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken switchKeyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, SyntaxToken openBraceToken, SyntaxList<SwitchSectionSyntax> sections, SyntaxToken closeBraceToken) { if (attributeLists != this.AttributeLists || switchKeyword != this.SwitchKeyword || openParenToken != this.OpenParenToken || expression != this.Expression || closeParenToken != this.CloseParenToken || openBraceToken != this.OpenBraceToken || sections != this.Sections || closeBraceToken != this.CloseBraceToken) { var newNode = SyntaxFactory.SwitchStatement(attributeLists, switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, sections, closeBraceToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new SwitchStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.SwitchKeyword, this.OpenParenToken, this.Expression, this.CloseParenToken, this.OpenBraceToken, this.Sections, this.CloseBraceToken); public SwitchStatementSyntax WithSwitchKeyword(SyntaxToken switchKeyword) => Update(this.AttributeLists, switchKeyword, this.OpenParenToken, this.Expression, this.CloseParenToken, this.OpenBraceToken, this.Sections, this.CloseBraceToken); public SwitchStatementSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.AttributeLists, this.SwitchKeyword, openParenToken, this.Expression, this.CloseParenToken, this.OpenBraceToken, this.Sections, this.CloseBraceToken); public SwitchStatementSyntax WithExpression(ExpressionSyntax expression) => Update(this.AttributeLists, this.SwitchKeyword, this.OpenParenToken, expression, this.CloseParenToken, this.OpenBraceToken, this.Sections, this.CloseBraceToken); public SwitchStatementSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.AttributeLists, this.SwitchKeyword, this.OpenParenToken, this.Expression, closeParenToken, this.OpenBraceToken, this.Sections, this.CloseBraceToken); public SwitchStatementSyntax WithOpenBraceToken(SyntaxToken openBraceToken) => Update(this.AttributeLists, this.SwitchKeyword, this.OpenParenToken, this.Expression, this.CloseParenToken, openBraceToken, this.Sections, this.CloseBraceToken); public SwitchStatementSyntax WithSections(SyntaxList<SwitchSectionSyntax> sections) => Update(this.AttributeLists, this.SwitchKeyword, this.OpenParenToken, this.Expression, this.CloseParenToken, this.OpenBraceToken, sections, this.CloseBraceToken); public SwitchStatementSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) => Update(this.AttributeLists, this.SwitchKeyword, this.OpenParenToken, this.Expression, this.CloseParenToken, this.OpenBraceToken, this.Sections, closeBraceToken); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new SwitchStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); public SwitchStatementSyntax AddSections(params SwitchSectionSyntax[] items) => WithSections(this.Sections.AddRange(items)); } /// <summary>Represents a switch section syntax of a switch statement.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.SwitchSection"/></description></item> /// </list> /// </remarks> public sealed partial class SwitchSectionSyntax : CSharpSyntaxNode { private SyntaxNode? labels; private SyntaxNode? statements; internal SwitchSectionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary> /// Gets a SyntaxList of SwitchLabelSyntax's the represents the possible labels that control can transfer to within the section. /// </summary> public SyntaxList<SwitchLabelSyntax> Labels => new SyntaxList<SwitchLabelSyntax>(GetRed(ref this.labels, 0)); /// <summary> /// Gets a SyntaxList of StatementSyntax's the represents the statements to be executed when control transfer to a label the belongs to the section. /// </summary> public SyntaxList<StatementSyntax> Statements => new SyntaxList<StatementSyntax>(GetRed(ref this.statements, 1)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.labels)!, 1 => GetRed(ref this.statements, 1)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.labels, 1 => this.statements, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitSwitchSection(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitSwitchSection(this); public SwitchSectionSyntax Update(SyntaxList<SwitchLabelSyntax> labels, SyntaxList<StatementSyntax> statements) { if (labels != this.Labels || statements != this.Statements) { var newNode = SyntaxFactory.SwitchSection(labels, statements); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public SwitchSectionSyntax WithLabels(SyntaxList<SwitchLabelSyntax> labels) => Update(labels, this.Statements); public SwitchSectionSyntax WithStatements(SyntaxList<StatementSyntax> statements) => Update(this.Labels, statements); public SwitchSectionSyntax AddLabels(params SwitchLabelSyntax[] items) => WithLabels(this.Labels.AddRange(items)); public SwitchSectionSyntax AddStatements(params StatementSyntax[] items) => WithStatements(this.Statements.AddRange(items)); } /// <summary>Represents a switch label within a switch statement.</summary> public abstract partial class SwitchLabelSyntax : CSharpSyntaxNode { internal SwitchLabelSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary> /// Gets a SyntaxToken that represents a case or default keyword that belongs to a switch label. /// </summary> public abstract SyntaxToken Keyword { get; } public SwitchLabelSyntax WithKeyword(SyntaxToken keyword) => WithKeywordCore(keyword); internal abstract SwitchLabelSyntax WithKeywordCore(SyntaxToken keyword); /// <summary> /// Gets a SyntaxToken that represents the colon that terminates the switch label. /// </summary> public abstract SyntaxToken ColonToken { get; } public SwitchLabelSyntax WithColonToken(SyntaxToken colonToken) => WithColonTokenCore(colonToken); internal abstract SwitchLabelSyntax WithColonTokenCore(SyntaxToken colonToken); } /// <summary>Represents a case label within a switch statement.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.CasePatternSwitchLabel"/></description></item> /// </list> /// </remarks> public sealed partial class CasePatternSwitchLabelSyntax : SwitchLabelSyntax { private PatternSyntax? pattern; private WhenClauseSyntax? whenClause; internal CasePatternSwitchLabelSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the case keyword token.</summary> public override SyntaxToken Keyword => new SyntaxToken(this, ((Syntax.InternalSyntax.CasePatternSwitchLabelSyntax)this.Green).keyword, Position, 0); /// <summary> /// Gets a PatternSyntax that represents the pattern that gets matched for the case label. /// </summary> public PatternSyntax Pattern => GetRed(ref this.pattern, 1)!; public WhenClauseSyntax? WhenClause => GetRed(ref this.whenClause, 2); public override SyntaxToken ColonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.CasePatternSwitchLabelSyntax)this.Green).colonToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 1 => GetRed(ref this.pattern, 1)!, 2 => GetRed(ref this.whenClause, 2), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 1 => this.pattern, 2 => this.whenClause, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitCasePatternSwitchLabel(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitCasePatternSwitchLabel(this); public CasePatternSwitchLabelSyntax Update(SyntaxToken keyword, PatternSyntax pattern, WhenClauseSyntax? whenClause, SyntaxToken colonToken) { if (keyword != this.Keyword || pattern != this.Pattern || whenClause != this.WhenClause || colonToken != this.ColonToken) { var newNode = SyntaxFactory.CasePatternSwitchLabel(keyword, pattern, whenClause, colonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override SwitchLabelSyntax WithKeywordCore(SyntaxToken keyword) => WithKeyword(keyword); public new CasePatternSwitchLabelSyntax WithKeyword(SyntaxToken keyword) => Update(keyword, this.Pattern, this.WhenClause, this.ColonToken); public CasePatternSwitchLabelSyntax WithPattern(PatternSyntax pattern) => Update(this.Keyword, pattern, this.WhenClause, this.ColonToken); public CasePatternSwitchLabelSyntax WithWhenClause(WhenClauseSyntax? whenClause) => Update(this.Keyword, this.Pattern, whenClause, this.ColonToken); internal override SwitchLabelSyntax WithColonTokenCore(SyntaxToken colonToken) => WithColonToken(colonToken); public new CasePatternSwitchLabelSyntax WithColonToken(SyntaxToken colonToken) => Update(this.Keyword, this.Pattern, this.WhenClause, colonToken); } /// <summary>Represents a case label within a switch statement.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.CaseSwitchLabel"/></description></item> /// </list> /// </remarks> public sealed partial class CaseSwitchLabelSyntax : SwitchLabelSyntax { private ExpressionSyntax? value; internal CaseSwitchLabelSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the case keyword token.</summary> public override SyntaxToken Keyword => new SyntaxToken(this, ((Syntax.InternalSyntax.CaseSwitchLabelSyntax)this.Green).keyword, Position, 0); /// <summary> /// Gets an ExpressionSyntax that represents the constant expression that gets matched for the case label. /// </summary> public ExpressionSyntax Value => GetRed(ref this.value, 1)!; public override SyntaxToken ColonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.CaseSwitchLabelSyntax)this.Green).colonToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.value, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.value : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitCaseSwitchLabel(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitCaseSwitchLabel(this); public CaseSwitchLabelSyntax Update(SyntaxToken keyword, ExpressionSyntax value, SyntaxToken colonToken) { if (keyword != this.Keyword || value != this.Value || colonToken != this.ColonToken) { var newNode = SyntaxFactory.CaseSwitchLabel(keyword, value, colonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override SwitchLabelSyntax WithKeywordCore(SyntaxToken keyword) => WithKeyword(keyword); public new CaseSwitchLabelSyntax WithKeyword(SyntaxToken keyword) => Update(keyword, this.Value, this.ColonToken); public CaseSwitchLabelSyntax WithValue(ExpressionSyntax value) => Update(this.Keyword, value, this.ColonToken); internal override SwitchLabelSyntax WithColonTokenCore(SyntaxToken colonToken) => WithColonToken(colonToken); public new CaseSwitchLabelSyntax WithColonToken(SyntaxToken colonToken) => Update(this.Keyword, this.Value, colonToken); } /// <summary>Represents a default label within a switch statement.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.DefaultSwitchLabel"/></description></item> /// </list> /// </remarks> public sealed partial class DefaultSwitchLabelSyntax : SwitchLabelSyntax { internal DefaultSwitchLabelSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the default keyword token.</summary> public override SyntaxToken Keyword => new SyntaxToken(this, ((Syntax.InternalSyntax.DefaultSwitchLabelSyntax)this.Green).keyword, Position, 0); public override SyntaxToken ColonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.DefaultSwitchLabelSyntax)this.Green).colonToken, GetChildPosition(1), GetChildIndex(1)); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitDefaultSwitchLabel(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitDefaultSwitchLabel(this); public DefaultSwitchLabelSyntax Update(SyntaxToken keyword, SyntaxToken colonToken) { if (keyword != this.Keyword || colonToken != this.ColonToken) { var newNode = SyntaxFactory.DefaultSwitchLabel(keyword, colonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override SwitchLabelSyntax WithKeywordCore(SyntaxToken keyword) => WithKeyword(keyword); public new DefaultSwitchLabelSyntax WithKeyword(SyntaxToken keyword) => Update(keyword, this.ColonToken); internal override SwitchLabelSyntax WithColonTokenCore(SyntaxToken colonToken) => WithColonToken(colonToken); public new DefaultSwitchLabelSyntax WithColonToken(SyntaxToken colonToken) => Update(this.Keyword, colonToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.SwitchExpression"/></description></item> /// </list> /// </remarks> public sealed partial class SwitchExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? governingExpression; private SyntaxNode? arms; internal SwitchExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public ExpressionSyntax GoverningExpression => GetRedAtZero(ref this.governingExpression)!; public SyntaxToken SwitchKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.SwitchExpressionSyntax)this.Green).switchKeyword, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken OpenBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.SwitchExpressionSyntax)this.Green).openBraceToken, GetChildPosition(2), GetChildIndex(2)); public SeparatedSyntaxList<SwitchExpressionArmSyntax> Arms { get { var red = GetRed(ref this.arms, 3); return red != null ? new SeparatedSyntaxList<SwitchExpressionArmSyntax>(red, GetChildIndex(3)) : default; } } public SyntaxToken CloseBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.SwitchExpressionSyntax)this.Green).closeBraceToken, GetChildPosition(4), GetChildIndex(4)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.governingExpression)!, 3 => GetRed(ref this.arms, 3)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.governingExpression, 3 => this.arms, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitSwitchExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitSwitchExpression(this); public SwitchExpressionSyntax Update(ExpressionSyntax governingExpression, SyntaxToken switchKeyword, SyntaxToken openBraceToken, SeparatedSyntaxList<SwitchExpressionArmSyntax> arms, SyntaxToken closeBraceToken) { if (governingExpression != this.GoverningExpression || switchKeyword != this.SwitchKeyword || openBraceToken != this.OpenBraceToken || arms != this.Arms || closeBraceToken != this.CloseBraceToken) { var newNode = SyntaxFactory.SwitchExpression(governingExpression, switchKeyword, openBraceToken, arms, closeBraceToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public SwitchExpressionSyntax WithGoverningExpression(ExpressionSyntax governingExpression) => Update(governingExpression, this.SwitchKeyword, this.OpenBraceToken, this.Arms, this.CloseBraceToken); public SwitchExpressionSyntax WithSwitchKeyword(SyntaxToken switchKeyword) => Update(this.GoverningExpression, switchKeyword, this.OpenBraceToken, this.Arms, this.CloseBraceToken); public SwitchExpressionSyntax WithOpenBraceToken(SyntaxToken openBraceToken) => Update(this.GoverningExpression, this.SwitchKeyword, openBraceToken, this.Arms, this.CloseBraceToken); public SwitchExpressionSyntax WithArms(SeparatedSyntaxList<SwitchExpressionArmSyntax> arms) => Update(this.GoverningExpression, this.SwitchKeyword, this.OpenBraceToken, arms, this.CloseBraceToken); public SwitchExpressionSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) => Update(this.GoverningExpression, this.SwitchKeyword, this.OpenBraceToken, this.Arms, closeBraceToken); public SwitchExpressionSyntax AddArms(params SwitchExpressionArmSyntax[] items) => WithArms(this.Arms.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.SwitchExpressionArm"/></description></item> /// </list> /// </remarks> public sealed partial class SwitchExpressionArmSyntax : CSharpSyntaxNode { private PatternSyntax? pattern; private WhenClauseSyntax? whenClause; private ExpressionSyntax? expression; internal SwitchExpressionArmSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public PatternSyntax Pattern => GetRedAtZero(ref this.pattern)!; public WhenClauseSyntax? WhenClause => GetRed(ref this.whenClause, 1); public SyntaxToken EqualsGreaterThanToken => new SyntaxToken(this, ((Syntax.InternalSyntax.SwitchExpressionArmSyntax)this.Green).equalsGreaterThanToken, GetChildPosition(2), GetChildIndex(2)); public ExpressionSyntax Expression => GetRed(ref this.expression, 3)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.pattern)!, 1 => GetRed(ref this.whenClause, 1), 3 => GetRed(ref this.expression, 3)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.pattern, 1 => this.whenClause, 3 => this.expression, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitSwitchExpressionArm(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitSwitchExpressionArm(this); public SwitchExpressionArmSyntax Update(PatternSyntax pattern, WhenClauseSyntax? whenClause, SyntaxToken equalsGreaterThanToken, ExpressionSyntax expression) { if (pattern != this.Pattern || whenClause != this.WhenClause || equalsGreaterThanToken != this.EqualsGreaterThanToken || expression != this.Expression) { var newNode = SyntaxFactory.SwitchExpressionArm(pattern, whenClause, equalsGreaterThanToken, expression); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public SwitchExpressionArmSyntax WithPattern(PatternSyntax pattern) => Update(pattern, this.WhenClause, this.EqualsGreaterThanToken, this.Expression); public SwitchExpressionArmSyntax WithWhenClause(WhenClauseSyntax? whenClause) => Update(this.Pattern, whenClause, this.EqualsGreaterThanToken, this.Expression); public SwitchExpressionArmSyntax WithEqualsGreaterThanToken(SyntaxToken equalsGreaterThanToken) => Update(this.Pattern, this.WhenClause, equalsGreaterThanToken, this.Expression); public SwitchExpressionArmSyntax WithExpression(ExpressionSyntax expression) => Update(this.Pattern, this.WhenClause, this.EqualsGreaterThanToken, expression); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.TryStatement"/></description></item> /// </list> /// </remarks> public sealed partial class TryStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private BlockSyntax? block; private SyntaxNode? catches; private FinallyClauseSyntax? @finally; internal TryStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxToken TryKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.TryStatementSyntax)this.Green).tryKeyword, GetChildPosition(1), GetChildIndex(1)); public BlockSyntax Block => GetRed(ref this.block, 2)!; public SyntaxList<CatchClauseSyntax> Catches => new SyntaxList<CatchClauseSyntax>(GetRed(ref this.catches, 3)); public FinallyClauseSyntax? Finally => GetRed(ref this.@finally, 4); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.block, 2)!, 3 => GetRed(ref this.catches, 3)!, 4 => GetRed(ref this.@finally, 4), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.block, 3 => this.catches, 4 => this.@finally, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitTryStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitTryStatement(this); public TryStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken tryKeyword, BlockSyntax block, SyntaxList<CatchClauseSyntax> catches, FinallyClauseSyntax? @finally) { if (attributeLists != this.AttributeLists || tryKeyword != this.TryKeyword || block != this.Block || catches != this.Catches || @finally != this.Finally) { var newNode = SyntaxFactory.TryStatement(attributeLists, tryKeyword, block, catches, @finally); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new TryStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.TryKeyword, this.Block, this.Catches, this.Finally); public TryStatementSyntax WithTryKeyword(SyntaxToken tryKeyword) => Update(this.AttributeLists, tryKeyword, this.Block, this.Catches, this.Finally); public TryStatementSyntax WithBlock(BlockSyntax block) => Update(this.AttributeLists, this.TryKeyword, block, this.Catches, this.Finally); public TryStatementSyntax WithCatches(SyntaxList<CatchClauseSyntax> catches) => Update(this.AttributeLists, this.TryKeyword, this.Block, catches, this.Finally); public TryStatementSyntax WithFinally(FinallyClauseSyntax? @finally) => Update(this.AttributeLists, this.TryKeyword, this.Block, this.Catches, @finally); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new TryStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); public TryStatementSyntax AddBlockAttributeLists(params AttributeListSyntax[] items) => WithBlock(this.Block.WithAttributeLists(this.Block.AttributeLists.AddRange(items))); public TryStatementSyntax AddBlockStatements(params StatementSyntax[] items) => WithBlock(this.Block.WithStatements(this.Block.Statements.AddRange(items))); public TryStatementSyntax AddCatches(params CatchClauseSyntax[] items) => WithCatches(this.Catches.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.CatchClause"/></description></item> /// </list> /// </remarks> public sealed partial class CatchClauseSyntax : CSharpSyntaxNode { private CatchDeclarationSyntax? declaration; private CatchFilterClauseSyntax? filter; private BlockSyntax? block; internal CatchClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken CatchKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.CatchClauseSyntax)this.Green).catchKeyword, Position, 0); public CatchDeclarationSyntax? Declaration => GetRed(ref this.declaration, 1); public CatchFilterClauseSyntax? Filter => GetRed(ref this.filter, 2); public BlockSyntax Block => GetRed(ref this.block, 3)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 1 => GetRed(ref this.declaration, 1), 2 => GetRed(ref this.filter, 2), 3 => GetRed(ref this.block, 3)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 1 => this.declaration, 2 => this.filter, 3 => this.block, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitCatchClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitCatchClause(this); public CatchClauseSyntax Update(SyntaxToken catchKeyword, CatchDeclarationSyntax? declaration, CatchFilterClauseSyntax? filter, BlockSyntax block) { if (catchKeyword != this.CatchKeyword || declaration != this.Declaration || filter != this.Filter || block != this.Block) { var newNode = SyntaxFactory.CatchClause(catchKeyword, declaration, filter, block); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public CatchClauseSyntax WithCatchKeyword(SyntaxToken catchKeyword) => Update(catchKeyword, this.Declaration, this.Filter, this.Block); public CatchClauseSyntax WithDeclaration(CatchDeclarationSyntax? declaration) => Update(this.CatchKeyword, declaration, this.Filter, this.Block); public CatchClauseSyntax WithFilter(CatchFilterClauseSyntax? filter) => Update(this.CatchKeyword, this.Declaration, filter, this.Block); public CatchClauseSyntax WithBlock(BlockSyntax block) => Update(this.CatchKeyword, this.Declaration, this.Filter, block); public CatchClauseSyntax AddBlockAttributeLists(params AttributeListSyntax[] items) => WithBlock(this.Block.WithAttributeLists(this.Block.AttributeLists.AddRange(items))); public CatchClauseSyntax AddBlockStatements(params StatementSyntax[] items) => WithBlock(this.Block.WithStatements(this.Block.Statements.AddRange(items))); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.CatchDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class CatchDeclarationSyntax : CSharpSyntaxNode { private TypeSyntax? type; internal CatchDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.CatchDeclarationSyntax)this.Green).openParenToken, Position, 0); public TypeSyntax Type => GetRed(ref this.type, 1)!; public SyntaxToken Identifier { get { var slot = ((Syntax.InternalSyntax.CatchDeclarationSyntax)this.Green).identifier; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(2), GetChildIndex(2)) : default; } } public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.CatchDeclarationSyntax)this.Green).closeParenToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.type, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.type : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitCatchDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitCatchDeclaration(this); public CatchDeclarationSyntax Update(SyntaxToken openParenToken, TypeSyntax type, SyntaxToken identifier, SyntaxToken closeParenToken) { if (openParenToken != this.OpenParenToken || type != this.Type || identifier != this.Identifier || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.CatchDeclaration(openParenToken, type, identifier, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public CatchDeclarationSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(openParenToken, this.Type, this.Identifier, this.CloseParenToken); public CatchDeclarationSyntax WithType(TypeSyntax type) => Update(this.OpenParenToken, type, this.Identifier, this.CloseParenToken); public CatchDeclarationSyntax WithIdentifier(SyntaxToken identifier) => Update(this.OpenParenToken, this.Type, identifier, this.CloseParenToken); public CatchDeclarationSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.OpenParenToken, this.Type, this.Identifier, closeParenToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.CatchFilterClause"/></description></item> /// </list> /// </remarks> public sealed partial class CatchFilterClauseSyntax : CSharpSyntaxNode { private ExpressionSyntax? filterExpression; internal CatchFilterClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken WhenKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.CatchFilterClauseSyntax)this.Green).whenKeyword, Position, 0); public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.CatchFilterClauseSyntax)this.Green).openParenToken, GetChildPosition(1), GetChildIndex(1)); public ExpressionSyntax FilterExpression => GetRed(ref this.filterExpression, 2)!; public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.CatchFilterClauseSyntax)this.Green).closeParenToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => index == 2 ? GetRed(ref this.filterExpression, 2)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 2 ? this.filterExpression : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitCatchFilterClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitCatchFilterClause(this); public CatchFilterClauseSyntax Update(SyntaxToken whenKeyword, SyntaxToken openParenToken, ExpressionSyntax filterExpression, SyntaxToken closeParenToken) { if (whenKeyword != this.WhenKeyword || openParenToken != this.OpenParenToken || filterExpression != this.FilterExpression || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.CatchFilterClause(whenKeyword, openParenToken, filterExpression, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public CatchFilterClauseSyntax WithWhenKeyword(SyntaxToken whenKeyword) => Update(whenKeyword, this.OpenParenToken, this.FilterExpression, this.CloseParenToken); public CatchFilterClauseSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.WhenKeyword, openParenToken, this.FilterExpression, this.CloseParenToken); public CatchFilterClauseSyntax WithFilterExpression(ExpressionSyntax filterExpression) => Update(this.WhenKeyword, this.OpenParenToken, filterExpression, this.CloseParenToken); public CatchFilterClauseSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.WhenKeyword, this.OpenParenToken, this.FilterExpression, closeParenToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.FinallyClause"/></description></item> /// </list> /// </remarks> public sealed partial class FinallyClauseSyntax : CSharpSyntaxNode { private BlockSyntax? block; internal FinallyClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken FinallyKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.FinallyClauseSyntax)this.Green).finallyKeyword, Position, 0); public BlockSyntax Block => GetRed(ref this.block, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.block, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.block : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitFinallyClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitFinallyClause(this); public FinallyClauseSyntax Update(SyntaxToken finallyKeyword, BlockSyntax block) { if (finallyKeyword != this.FinallyKeyword || block != this.Block) { var newNode = SyntaxFactory.FinallyClause(finallyKeyword, block); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public FinallyClauseSyntax WithFinallyKeyword(SyntaxToken finallyKeyword) => Update(finallyKeyword, this.Block); public FinallyClauseSyntax WithBlock(BlockSyntax block) => Update(this.FinallyKeyword, block); public FinallyClauseSyntax AddBlockAttributeLists(params AttributeListSyntax[] items) => WithBlock(this.Block.WithAttributeLists(this.Block.AttributeLists.AddRange(items))); public FinallyClauseSyntax AddBlockStatements(params StatementSyntax[] items) => WithBlock(this.Block.WithStatements(this.Block.Statements.AddRange(items))); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.CompilationUnit"/></description></item> /// </list> /// </remarks> public sealed partial class CompilationUnitSyntax : CSharpSyntaxNode { private SyntaxNode? externs; private SyntaxNode? usings; private SyntaxNode? attributeLists; private SyntaxNode? members; internal CompilationUnitSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxList<ExternAliasDirectiveSyntax> Externs => new SyntaxList<ExternAliasDirectiveSyntax>(GetRed(ref this.externs, 0)); public SyntaxList<UsingDirectiveSyntax> Usings => new SyntaxList<UsingDirectiveSyntax>(GetRed(ref this.usings, 1)); /// <summary>Gets the attribute declaration list.</summary> public SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 2)); public SyntaxList<MemberDeclarationSyntax> Members => new SyntaxList<MemberDeclarationSyntax>(GetRed(ref this.members, 3)); public SyntaxToken EndOfFileToken => new SyntaxToken(this, ((Syntax.InternalSyntax.CompilationUnitSyntax)this.Green).endOfFileToken, GetChildPosition(4), GetChildIndex(4)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.externs)!, 1 => GetRed(ref this.usings, 1)!, 2 => GetRed(ref this.attributeLists, 2)!, 3 => GetRed(ref this.members, 3)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.externs, 1 => this.usings, 2 => this.attributeLists, 3 => this.members, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitCompilationUnit(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitCompilationUnit(this); public CompilationUnitSyntax Update(SyntaxList<ExternAliasDirectiveSyntax> externs, SyntaxList<UsingDirectiveSyntax> usings, SyntaxList<AttributeListSyntax> attributeLists, SyntaxList<MemberDeclarationSyntax> members, SyntaxToken endOfFileToken) { if (externs != this.Externs || usings != this.Usings || attributeLists != this.AttributeLists || members != this.Members || endOfFileToken != this.EndOfFileToken) { var newNode = SyntaxFactory.CompilationUnit(externs, usings, attributeLists, members, endOfFileToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public CompilationUnitSyntax WithExterns(SyntaxList<ExternAliasDirectiveSyntax> externs) => Update(externs, this.Usings, this.AttributeLists, this.Members, this.EndOfFileToken); public CompilationUnitSyntax WithUsings(SyntaxList<UsingDirectiveSyntax> usings) => Update(this.Externs, usings, this.AttributeLists, this.Members, this.EndOfFileToken); public CompilationUnitSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(this.Externs, this.Usings, attributeLists, this.Members, this.EndOfFileToken); public CompilationUnitSyntax WithMembers(SyntaxList<MemberDeclarationSyntax> members) => Update(this.Externs, this.Usings, this.AttributeLists, members, this.EndOfFileToken); public CompilationUnitSyntax WithEndOfFileToken(SyntaxToken endOfFileToken) => Update(this.Externs, this.Usings, this.AttributeLists, this.Members, endOfFileToken); public CompilationUnitSyntax AddExterns(params ExternAliasDirectiveSyntax[] items) => WithExterns(this.Externs.AddRange(items)); public CompilationUnitSyntax AddUsings(params UsingDirectiveSyntax[] items) => WithUsings(this.Usings.AddRange(items)); public CompilationUnitSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); public CompilationUnitSyntax AddMembers(params MemberDeclarationSyntax[] items) => WithMembers(this.Members.AddRange(items)); } /// <summary> /// Represents an ExternAlias directive syntax, e.g. "extern alias MyAlias;" with specifying "/r:MyAlias=SomeAssembly.dll " on the compiler command line. /// </summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ExternAliasDirective"/></description></item> /// </list> /// </remarks> public sealed partial class ExternAliasDirectiveSyntax : CSharpSyntaxNode { internal ExternAliasDirectiveSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the extern keyword.</summary> public SyntaxToken ExternKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ExternAliasDirectiveSyntax)this.Green).externKeyword, Position, 0); /// <summary>SyntaxToken representing the alias keyword.</summary> public SyntaxToken AliasKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ExternAliasDirectiveSyntax)this.Green).aliasKeyword, GetChildPosition(1), GetChildIndex(1)); /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.ExternAliasDirectiveSyntax)this.Green).identifier, GetChildPosition(2), GetChildIndex(2)); /// <summary>SyntaxToken representing the semicolon token.</summary> public SyntaxToken SemicolonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ExternAliasDirectiveSyntax)this.Green).semicolonToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitExternAliasDirective(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitExternAliasDirective(this); public ExternAliasDirectiveSyntax Update(SyntaxToken externKeyword, SyntaxToken aliasKeyword, SyntaxToken identifier, SyntaxToken semicolonToken) { if (externKeyword != this.ExternKeyword || aliasKeyword != this.AliasKeyword || identifier != this.Identifier || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.ExternAliasDirective(externKeyword, aliasKeyword, identifier, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ExternAliasDirectiveSyntax WithExternKeyword(SyntaxToken externKeyword) => Update(externKeyword, this.AliasKeyword, this.Identifier, this.SemicolonToken); public ExternAliasDirectiveSyntax WithAliasKeyword(SyntaxToken aliasKeyword) => Update(this.ExternKeyword, aliasKeyword, this.Identifier, this.SemicolonToken); public ExternAliasDirectiveSyntax WithIdentifier(SyntaxToken identifier) => Update(this.ExternKeyword, this.AliasKeyword, identifier, this.SemicolonToken); public ExternAliasDirectiveSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.ExternKeyword, this.AliasKeyword, this.Identifier, semicolonToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.UsingDirective"/></description></item> /// </list> /// </remarks> public sealed partial class UsingDirectiveSyntax : CSharpSyntaxNode { private NameEqualsSyntax? alias; private NameSyntax? name; internal UsingDirectiveSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken GlobalKeyword { get { var slot = ((Syntax.InternalSyntax.UsingDirectiveSyntax)this.Green).globalKeyword; return slot != null ? new SyntaxToken(this, slot, Position, 0) : default; } } public SyntaxToken UsingKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.UsingDirectiveSyntax)this.Green).usingKeyword, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken StaticKeyword { get { var slot = ((Syntax.InternalSyntax.UsingDirectiveSyntax)this.Green).staticKeyword; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(2), GetChildIndex(2)) : default; } } public NameEqualsSyntax? Alias => GetRed(ref this.alias, 3); public NameSyntax Name => GetRed(ref this.name, 4)!; public SyntaxToken SemicolonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.UsingDirectiveSyntax)this.Green).semicolonToken, GetChildPosition(5), GetChildIndex(5)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 3 => GetRed(ref this.alias, 3), 4 => GetRed(ref this.name, 4)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 3 => this.alias, 4 => this.name, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitUsingDirective(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitUsingDirective(this); public UsingDirectiveSyntax Update(SyntaxToken globalKeyword, SyntaxToken usingKeyword, SyntaxToken staticKeyword, NameEqualsSyntax? alias, NameSyntax name, SyntaxToken semicolonToken) { if (globalKeyword != this.GlobalKeyword || usingKeyword != this.UsingKeyword || staticKeyword != this.StaticKeyword || alias != this.Alias || name != this.Name || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.UsingDirective(globalKeyword, usingKeyword, staticKeyword, alias, name, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public UsingDirectiveSyntax WithGlobalKeyword(SyntaxToken globalKeyword) => Update(globalKeyword, this.UsingKeyword, this.StaticKeyword, this.Alias, this.Name, this.SemicolonToken); public UsingDirectiveSyntax WithUsingKeyword(SyntaxToken usingKeyword) => Update(this.GlobalKeyword, usingKeyword, this.StaticKeyword, this.Alias, this.Name, this.SemicolonToken); public UsingDirectiveSyntax WithStaticKeyword(SyntaxToken staticKeyword) => Update(this.GlobalKeyword, this.UsingKeyword, staticKeyword, this.Alias, this.Name, this.SemicolonToken); public UsingDirectiveSyntax WithAlias(NameEqualsSyntax? alias) => Update(this.GlobalKeyword, this.UsingKeyword, this.StaticKeyword, alias, this.Name, this.SemicolonToken); public UsingDirectiveSyntax WithName(NameSyntax name) => Update(this.GlobalKeyword, this.UsingKeyword, this.StaticKeyword, this.Alias, name, this.SemicolonToken); public UsingDirectiveSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.GlobalKeyword, this.UsingKeyword, this.StaticKeyword, this.Alias, this.Name, semicolonToken); } /// <summary>Member declaration syntax.</summary> public abstract partial class MemberDeclarationSyntax : CSharpSyntaxNode { internal MemberDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the attribute declaration list.</summary> public abstract SyntaxList<AttributeListSyntax> AttributeLists { get; } public MemberDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeListsCore(attributeLists); internal abstract MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists); public MemberDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => AddAttributeListsCore(items); internal abstract MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items); /// <summary>Gets the modifier list.</summary> public abstract SyntaxTokenList Modifiers { get; } public MemberDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => WithModifiersCore(modifiers); internal abstract MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers); public MemberDeclarationSyntax AddModifiers(params SyntaxToken[] items) => AddModifiersCore(items); internal abstract MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items); } public abstract partial class BaseNamespaceDeclarationSyntax : MemberDeclarationSyntax { internal BaseNamespaceDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public abstract SyntaxToken NamespaceKeyword { get; } public BaseNamespaceDeclarationSyntax WithNamespaceKeyword(SyntaxToken namespaceKeyword) => WithNamespaceKeywordCore(namespaceKeyword); internal abstract BaseNamespaceDeclarationSyntax WithNamespaceKeywordCore(SyntaxToken namespaceKeyword); public abstract NameSyntax Name { get; } public BaseNamespaceDeclarationSyntax WithName(NameSyntax name) => WithNameCore(name); internal abstract BaseNamespaceDeclarationSyntax WithNameCore(NameSyntax name); public abstract SyntaxList<ExternAliasDirectiveSyntax> Externs { get; } public BaseNamespaceDeclarationSyntax WithExterns(SyntaxList<ExternAliasDirectiveSyntax> externs) => WithExternsCore(externs); internal abstract BaseNamespaceDeclarationSyntax WithExternsCore(SyntaxList<ExternAliasDirectiveSyntax> externs); public BaseNamespaceDeclarationSyntax AddExterns(params ExternAliasDirectiveSyntax[] items) => AddExternsCore(items); internal abstract BaseNamespaceDeclarationSyntax AddExternsCore(params ExternAliasDirectiveSyntax[] items); public abstract SyntaxList<UsingDirectiveSyntax> Usings { get; } public BaseNamespaceDeclarationSyntax WithUsings(SyntaxList<UsingDirectiveSyntax> usings) => WithUsingsCore(usings); internal abstract BaseNamespaceDeclarationSyntax WithUsingsCore(SyntaxList<UsingDirectiveSyntax> usings); public BaseNamespaceDeclarationSyntax AddUsings(params UsingDirectiveSyntax[] items) => AddUsingsCore(items); internal abstract BaseNamespaceDeclarationSyntax AddUsingsCore(params UsingDirectiveSyntax[] items); public abstract SyntaxList<MemberDeclarationSyntax> Members { get; } public BaseNamespaceDeclarationSyntax WithMembers(SyntaxList<MemberDeclarationSyntax> members) => WithMembersCore(members); internal abstract BaseNamespaceDeclarationSyntax WithMembersCore(SyntaxList<MemberDeclarationSyntax> members); public BaseNamespaceDeclarationSyntax AddMembers(params MemberDeclarationSyntax[] items) => AddMembersCore(items); internal abstract BaseNamespaceDeclarationSyntax AddMembersCore(params MemberDeclarationSyntax[] items); public new BaseNamespaceDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => (BaseNamespaceDeclarationSyntax)WithAttributeListsCore(attributeLists); public new BaseNamespaceDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => (BaseNamespaceDeclarationSyntax)WithModifiersCore(modifiers); public new BaseNamespaceDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => (BaseNamespaceDeclarationSyntax)AddAttributeListsCore(items); public new BaseNamespaceDeclarationSyntax AddModifiers(params SyntaxToken[] items) => (BaseNamespaceDeclarationSyntax)AddModifiersCore(items); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.NamespaceDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class NamespaceDeclarationSyntax : BaseNamespaceDeclarationSyntax { private SyntaxNode? attributeLists; private NameSyntax? name; private SyntaxNode? externs; private SyntaxNode? usings; private SyntaxNode? members; internal NamespaceDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public override SyntaxToken NamespaceKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.NamespaceDeclarationSyntax)this.Green).namespaceKeyword, GetChildPosition(2), GetChildIndex(2)); public override NameSyntax Name => GetRed(ref this.name, 3)!; public SyntaxToken OpenBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.NamespaceDeclarationSyntax)this.Green).openBraceToken, GetChildPosition(4), GetChildIndex(4)); public override SyntaxList<ExternAliasDirectiveSyntax> Externs => new SyntaxList<ExternAliasDirectiveSyntax>(GetRed(ref this.externs, 5)); public override SyntaxList<UsingDirectiveSyntax> Usings => new SyntaxList<UsingDirectiveSyntax>(GetRed(ref this.usings, 6)); public override SyntaxList<MemberDeclarationSyntax> Members => new SyntaxList<MemberDeclarationSyntax>(GetRed(ref this.members, 7)); public SyntaxToken CloseBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.NamespaceDeclarationSyntax)this.Green).closeBraceToken, GetChildPosition(8), GetChildIndex(8)); /// <summary>Gets the optional semicolon token.</summary> public SyntaxToken SemicolonToken { get { var slot = ((Syntax.InternalSyntax.NamespaceDeclarationSyntax)this.Green).semicolonToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(9), GetChildIndex(9)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 3 => GetRed(ref this.name, 3)!, 5 => GetRed(ref this.externs, 5)!, 6 => GetRed(ref this.usings, 6)!, 7 => GetRed(ref this.members, 7)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 3 => this.name, 5 => this.externs, 6 => this.usings, 7 => this.members, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitNamespaceDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitNamespaceDeclaration(this); public NamespaceDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken namespaceKeyword, NameSyntax name, SyntaxToken openBraceToken, SyntaxList<ExternAliasDirectiveSyntax> externs, SyntaxList<UsingDirectiveSyntax> usings, SyntaxList<MemberDeclarationSyntax> members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || namespaceKeyword != this.NamespaceKeyword || name != this.Name || openBraceToken != this.OpenBraceToken || externs != this.Externs || usings != this.Usings || members != this.Members || closeBraceToken != this.CloseBraceToken || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.NamespaceDeclaration(attributeLists, modifiers, namespaceKeyword, name, openBraceToken, externs, usings, members, closeBraceToken, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new NamespaceDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.NamespaceKeyword, this.Name, this.OpenBraceToken, this.Externs, this.Usings, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new NamespaceDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.NamespaceKeyword, this.Name, this.OpenBraceToken, this.Externs, this.Usings, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseNamespaceDeclarationSyntax WithNamespaceKeywordCore(SyntaxToken namespaceKeyword) => WithNamespaceKeyword(namespaceKeyword); public new NamespaceDeclarationSyntax WithNamespaceKeyword(SyntaxToken namespaceKeyword) => Update(this.AttributeLists, this.Modifiers, namespaceKeyword, this.Name, this.OpenBraceToken, this.Externs, this.Usings, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseNamespaceDeclarationSyntax WithNameCore(NameSyntax name) => WithName(name); public new NamespaceDeclarationSyntax WithName(NameSyntax name) => Update(this.AttributeLists, this.Modifiers, this.NamespaceKeyword, name, this.OpenBraceToken, this.Externs, this.Usings, this.Members, this.CloseBraceToken, this.SemicolonToken); public NamespaceDeclarationSyntax WithOpenBraceToken(SyntaxToken openBraceToken) => Update(this.AttributeLists, this.Modifiers, this.NamespaceKeyword, this.Name, openBraceToken, this.Externs, this.Usings, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseNamespaceDeclarationSyntax WithExternsCore(SyntaxList<ExternAliasDirectiveSyntax> externs) => WithExterns(externs); public new NamespaceDeclarationSyntax WithExterns(SyntaxList<ExternAliasDirectiveSyntax> externs) => Update(this.AttributeLists, this.Modifiers, this.NamespaceKeyword, this.Name, this.OpenBraceToken, externs, this.Usings, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseNamespaceDeclarationSyntax WithUsingsCore(SyntaxList<UsingDirectiveSyntax> usings) => WithUsings(usings); public new NamespaceDeclarationSyntax WithUsings(SyntaxList<UsingDirectiveSyntax> usings) => Update(this.AttributeLists, this.Modifiers, this.NamespaceKeyword, this.Name, this.OpenBraceToken, this.Externs, usings, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseNamespaceDeclarationSyntax WithMembersCore(SyntaxList<MemberDeclarationSyntax> members) => WithMembers(members); public new NamespaceDeclarationSyntax WithMembers(SyntaxList<MemberDeclarationSyntax> members) => Update(this.AttributeLists, this.Modifiers, this.NamespaceKeyword, this.Name, this.OpenBraceToken, this.Externs, this.Usings, members, this.CloseBraceToken, this.SemicolonToken); public NamespaceDeclarationSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) => Update(this.AttributeLists, this.Modifiers, this.NamespaceKeyword, this.Name, this.OpenBraceToken, this.Externs, this.Usings, this.Members, closeBraceToken, this.SemicolonToken); public NamespaceDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.NamespaceKeyword, this.Name, this.OpenBraceToken, this.Externs, this.Usings, this.Members, this.CloseBraceToken, semicolonToken); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new NamespaceDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new NamespaceDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); internal override BaseNamespaceDeclarationSyntax AddExternsCore(params ExternAliasDirectiveSyntax[] items) => AddExterns(items); public new NamespaceDeclarationSyntax AddExterns(params ExternAliasDirectiveSyntax[] items) => WithExterns(this.Externs.AddRange(items)); internal override BaseNamespaceDeclarationSyntax AddUsingsCore(params UsingDirectiveSyntax[] items) => AddUsings(items); public new NamespaceDeclarationSyntax AddUsings(params UsingDirectiveSyntax[] items) => WithUsings(this.Usings.AddRange(items)); internal override BaseNamespaceDeclarationSyntax AddMembersCore(params MemberDeclarationSyntax[] items) => AddMembers(items); public new NamespaceDeclarationSyntax AddMembers(params MemberDeclarationSyntax[] items) => WithMembers(this.Members.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.FileScopedNamespaceDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class FileScopedNamespaceDeclarationSyntax : BaseNamespaceDeclarationSyntax { private SyntaxNode? attributeLists; private NameSyntax? name; private SyntaxNode? externs; private SyntaxNode? usings; private SyntaxNode? members; internal FileScopedNamespaceDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public override SyntaxToken NamespaceKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.FileScopedNamespaceDeclarationSyntax)this.Green).namespaceKeyword, GetChildPosition(2), GetChildIndex(2)); public override NameSyntax Name => GetRed(ref this.name, 3)!; public SyntaxToken SemicolonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.FileScopedNamespaceDeclarationSyntax)this.Green).semicolonToken, GetChildPosition(4), GetChildIndex(4)); public override SyntaxList<ExternAliasDirectiveSyntax> Externs => new SyntaxList<ExternAliasDirectiveSyntax>(GetRed(ref this.externs, 5)); public override SyntaxList<UsingDirectiveSyntax> Usings => new SyntaxList<UsingDirectiveSyntax>(GetRed(ref this.usings, 6)); public override SyntaxList<MemberDeclarationSyntax> Members => new SyntaxList<MemberDeclarationSyntax>(GetRed(ref this.members, 7)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 3 => GetRed(ref this.name, 3)!, 5 => GetRed(ref this.externs, 5)!, 6 => GetRed(ref this.usings, 6)!, 7 => GetRed(ref this.members, 7)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 3 => this.name, 5 => this.externs, 6 => this.usings, 7 => this.members, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitFileScopedNamespaceDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitFileScopedNamespaceDeclaration(this); public FileScopedNamespaceDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken namespaceKeyword, NameSyntax name, SyntaxToken semicolonToken, SyntaxList<ExternAliasDirectiveSyntax> externs, SyntaxList<UsingDirectiveSyntax> usings, SyntaxList<MemberDeclarationSyntax> members) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || namespaceKeyword != this.NamespaceKeyword || name != this.Name || semicolonToken != this.SemicolonToken || externs != this.Externs || usings != this.Usings || members != this.Members) { var newNode = SyntaxFactory.FileScopedNamespaceDeclaration(attributeLists, modifiers, namespaceKeyword, name, semicolonToken, externs, usings, members); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new FileScopedNamespaceDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.NamespaceKeyword, this.Name, this.SemicolonToken, this.Externs, this.Usings, this.Members); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new FileScopedNamespaceDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.NamespaceKeyword, this.Name, this.SemicolonToken, this.Externs, this.Usings, this.Members); internal override BaseNamespaceDeclarationSyntax WithNamespaceKeywordCore(SyntaxToken namespaceKeyword) => WithNamespaceKeyword(namespaceKeyword); public new FileScopedNamespaceDeclarationSyntax WithNamespaceKeyword(SyntaxToken namespaceKeyword) => Update(this.AttributeLists, this.Modifiers, namespaceKeyword, this.Name, this.SemicolonToken, this.Externs, this.Usings, this.Members); internal override BaseNamespaceDeclarationSyntax WithNameCore(NameSyntax name) => WithName(name); public new FileScopedNamespaceDeclarationSyntax WithName(NameSyntax name) => Update(this.AttributeLists, this.Modifiers, this.NamespaceKeyword, name, this.SemicolonToken, this.Externs, this.Usings, this.Members); public FileScopedNamespaceDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.NamespaceKeyword, this.Name, semicolonToken, this.Externs, this.Usings, this.Members); internal override BaseNamespaceDeclarationSyntax WithExternsCore(SyntaxList<ExternAliasDirectiveSyntax> externs) => WithExterns(externs); public new FileScopedNamespaceDeclarationSyntax WithExterns(SyntaxList<ExternAliasDirectiveSyntax> externs) => Update(this.AttributeLists, this.Modifiers, this.NamespaceKeyword, this.Name, this.SemicolonToken, externs, this.Usings, this.Members); internal override BaseNamespaceDeclarationSyntax WithUsingsCore(SyntaxList<UsingDirectiveSyntax> usings) => WithUsings(usings); public new FileScopedNamespaceDeclarationSyntax WithUsings(SyntaxList<UsingDirectiveSyntax> usings) => Update(this.AttributeLists, this.Modifiers, this.NamespaceKeyword, this.Name, this.SemicolonToken, this.Externs, usings, this.Members); internal override BaseNamespaceDeclarationSyntax WithMembersCore(SyntaxList<MemberDeclarationSyntax> members) => WithMembers(members); public new FileScopedNamespaceDeclarationSyntax WithMembers(SyntaxList<MemberDeclarationSyntax> members) => Update(this.AttributeLists, this.Modifiers, this.NamespaceKeyword, this.Name, this.SemicolonToken, this.Externs, this.Usings, members); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new FileScopedNamespaceDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new FileScopedNamespaceDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); internal override BaseNamespaceDeclarationSyntax AddExternsCore(params ExternAliasDirectiveSyntax[] items) => AddExterns(items); public new FileScopedNamespaceDeclarationSyntax AddExterns(params ExternAliasDirectiveSyntax[] items) => WithExterns(this.Externs.AddRange(items)); internal override BaseNamespaceDeclarationSyntax AddUsingsCore(params UsingDirectiveSyntax[] items) => AddUsings(items); public new FileScopedNamespaceDeclarationSyntax AddUsings(params UsingDirectiveSyntax[] items) => WithUsings(this.Usings.AddRange(items)); internal override BaseNamespaceDeclarationSyntax AddMembersCore(params MemberDeclarationSyntax[] items) => AddMembers(items); public new FileScopedNamespaceDeclarationSyntax AddMembers(params MemberDeclarationSyntax[] items) => WithMembers(this.Members.AddRange(items)); } /// <summary>Class representing one or more attributes applied to a language construct.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.AttributeList"/></description></item> /// </list> /// </remarks> public sealed partial class AttributeListSyntax : CSharpSyntaxNode { private AttributeTargetSpecifierSyntax? target; private SyntaxNode? attributes; internal AttributeListSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the open bracket token.</summary> public SyntaxToken OpenBracketToken => new SyntaxToken(this, ((Syntax.InternalSyntax.AttributeListSyntax)this.Green).openBracketToken, Position, 0); /// <summary>Gets the optional construct targeted by the attribute.</summary> public AttributeTargetSpecifierSyntax? Target => GetRed(ref this.target, 1); /// <summary>Gets the attribute declaration list.</summary> public SeparatedSyntaxList<AttributeSyntax> Attributes { get { var red = GetRed(ref this.attributes, 2); return red != null ? new SeparatedSyntaxList<AttributeSyntax>(red, GetChildIndex(2)) : default; } } /// <summary>Gets the close bracket token.</summary> public SyntaxToken CloseBracketToken => new SyntaxToken(this, ((Syntax.InternalSyntax.AttributeListSyntax)this.Green).closeBracketToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 1 => GetRed(ref this.target, 1), 2 => GetRed(ref this.attributes, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 1 => this.target, 2 => this.attributes, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitAttributeList(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitAttributeList(this); public AttributeListSyntax Update(SyntaxToken openBracketToken, AttributeTargetSpecifierSyntax? target, SeparatedSyntaxList<AttributeSyntax> attributes, SyntaxToken closeBracketToken) { if (openBracketToken != this.OpenBracketToken || target != this.Target || attributes != this.Attributes || closeBracketToken != this.CloseBracketToken) { var newNode = SyntaxFactory.AttributeList(openBracketToken, target, attributes, closeBracketToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public AttributeListSyntax WithOpenBracketToken(SyntaxToken openBracketToken) => Update(openBracketToken, this.Target, this.Attributes, this.CloseBracketToken); public AttributeListSyntax WithTarget(AttributeTargetSpecifierSyntax? target) => Update(this.OpenBracketToken, target, this.Attributes, this.CloseBracketToken); public AttributeListSyntax WithAttributes(SeparatedSyntaxList<AttributeSyntax> attributes) => Update(this.OpenBracketToken, this.Target, attributes, this.CloseBracketToken); public AttributeListSyntax WithCloseBracketToken(SyntaxToken closeBracketToken) => Update(this.OpenBracketToken, this.Target, this.Attributes, closeBracketToken); public AttributeListSyntax AddAttributes(params AttributeSyntax[] items) => WithAttributes(this.Attributes.AddRange(items)); } /// <summary>Class representing what language construct an attribute targets.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.AttributeTargetSpecifier"/></description></item> /// </list> /// </remarks> public sealed partial class AttributeTargetSpecifierSyntax : CSharpSyntaxNode { internal AttributeTargetSpecifierSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.AttributeTargetSpecifierSyntax)this.Green).identifier, Position, 0); /// <summary>Gets the colon token.</summary> public SyntaxToken ColonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.AttributeTargetSpecifierSyntax)this.Green).colonToken, GetChildPosition(1), GetChildIndex(1)); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitAttributeTargetSpecifier(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitAttributeTargetSpecifier(this); public AttributeTargetSpecifierSyntax Update(SyntaxToken identifier, SyntaxToken colonToken) { if (identifier != this.Identifier || colonToken != this.ColonToken) { var newNode = SyntaxFactory.AttributeTargetSpecifier(identifier, colonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public AttributeTargetSpecifierSyntax WithIdentifier(SyntaxToken identifier) => Update(identifier, this.ColonToken); public AttributeTargetSpecifierSyntax WithColonToken(SyntaxToken colonToken) => Update(this.Identifier, colonToken); } /// <summary>Attribute syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.Attribute"/></description></item> /// </list> /// </remarks> public sealed partial class AttributeSyntax : CSharpSyntaxNode { private NameSyntax? name; private AttributeArgumentListSyntax? argumentList; internal AttributeSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the name.</summary> public NameSyntax Name => GetRedAtZero(ref this.name)!; public AttributeArgumentListSyntax? ArgumentList => GetRed(ref this.argumentList, 1); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.name)!, 1 => GetRed(ref this.argumentList, 1), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.name, 1 => this.argumentList, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitAttribute(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitAttribute(this); public AttributeSyntax Update(NameSyntax name, AttributeArgumentListSyntax? argumentList) { if (name != this.Name || argumentList != this.ArgumentList) { var newNode = SyntaxFactory.Attribute(name, argumentList); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public AttributeSyntax WithName(NameSyntax name) => Update(name, this.ArgumentList); public AttributeSyntax WithArgumentList(AttributeArgumentListSyntax? argumentList) => Update(this.Name, argumentList); public AttributeSyntax AddArgumentListArguments(params AttributeArgumentSyntax[] items) { var argumentList = this.ArgumentList ?? SyntaxFactory.AttributeArgumentList(); return WithArgumentList(argumentList.WithArguments(argumentList.Arguments.AddRange(items))); } } /// <summary>Attribute argument list syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.AttributeArgumentList"/></description></item> /// </list> /// </remarks> public sealed partial class AttributeArgumentListSyntax : CSharpSyntaxNode { private SyntaxNode? arguments; internal AttributeArgumentListSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the open paren token.</summary> public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.AttributeArgumentListSyntax)this.Green).openParenToken, Position, 0); /// <summary>Gets the arguments syntax list.</summary> public SeparatedSyntaxList<AttributeArgumentSyntax> Arguments { get { var red = GetRed(ref this.arguments, 1); return red != null ? new SeparatedSyntaxList<AttributeArgumentSyntax>(red, GetChildIndex(1)) : default; } } /// <summary>Gets the close paren token.</summary> public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.AttributeArgumentListSyntax)this.Green).closeParenToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.arguments, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.arguments : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitAttributeArgumentList(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitAttributeArgumentList(this); public AttributeArgumentListSyntax Update(SyntaxToken openParenToken, SeparatedSyntaxList<AttributeArgumentSyntax> arguments, SyntaxToken closeParenToken) { if (openParenToken != this.OpenParenToken || arguments != this.Arguments || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.AttributeArgumentList(openParenToken, arguments, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public AttributeArgumentListSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(openParenToken, this.Arguments, this.CloseParenToken); public AttributeArgumentListSyntax WithArguments(SeparatedSyntaxList<AttributeArgumentSyntax> arguments) => Update(this.OpenParenToken, arguments, this.CloseParenToken); public AttributeArgumentListSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.OpenParenToken, this.Arguments, closeParenToken); public AttributeArgumentListSyntax AddArguments(params AttributeArgumentSyntax[] items) => WithArguments(this.Arguments.AddRange(items)); } /// <summary>Attribute argument syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.AttributeArgument"/></description></item> /// </list> /// </remarks> public sealed partial class AttributeArgumentSyntax : CSharpSyntaxNode { private NameEqualsSyntax? nameEquals; private NameColonSyntax? nameColon; private ExpressionSyntax? expression; internal AttributeArgumentSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public NameEqualsSyntax? NameEquals => GetRedAtZero(ref this.nameEquals); public NameColonSyntax? NameColon => GetRed(ref this.nameColon, 1); /// <summary>Gets the expression.</summary> public ExpressionSyntax Expression => GetRed(ref this.expression, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.nameEquals), 1 => GetRed(ref this.nameColon, 1), 2 => GetRed(ref this.expression, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.nameEquals, 1 => this.nameColon, 2 => this.expression, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitAttributeArgument(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitAttributeArgument(this); public AttributeArgumentSyntax Update(NameEqualsSyntax? nameEquals, NameColonSyntax? nameColon, ExpressionSyntax expression) { if (nameEquals != this.NameEquals || nameColon != this.NameColon || expression != this.Expression) { var newNode = SyntaxFactory.AttributeArgument(nameEquals, nameColon, expression); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public AttributeArgumentSyntax WithNameEquals(NameEqualsSyntax? nameEquals) => Update(nameEquals, this.NameColon, this.Expression); public AttributeArgumentSyntax WithNameColon(NameColonSyntax? nameColon) => Update(this.NameEquals, nameColon, this.Expression); public AttributeArgumentSyntax WithExpression(ExpressionSyntax expression) => Update(this.NameEquals, this.NameColon, expression); } /// <summary>Class representing an identifier name followed by an equals token.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.NameEquals"/></description></item> /// </list> /// </remarks> public sealed partial class NameEqualsSyntax : CSharpSyntaxNode { private IdentifierNameSyntax? name; internal NameEqualsSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the identifier name.</summary> public IdentifierNameSyntax Name => GetRedAtZero(ref this.name)!; public SyntaxToken EqualsToken => new SyntaxToken(this, ((Syntax.InternalSyntax.NameEqualsSyntax)this.Green).equalsToken, GetChildPosition(1), GetChildIndex(1)); internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.name)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.name : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitNameEquals(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitNameEquals(this); public NameEqualsSyntax Update(IdentifierNameSyntax name, SyntaxToken equalsToken) { if (name != this.Name || equalsToken != this.EqualsToken) { var newNode = SyntaxFactory.NameEquals(name, equalsToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public NameEqualsSyntax WithName(IdentifierNameSyntax name) => Update(name, this.EqualsToken); public NameEqualsSyntax WithEqualsToken(SyntaxToken equalsToken) => Update(this.Name, equalsToken); } /// <summary>Type parameter list syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.TypeParameterList"/></description></item> /// </list> /// </remarks> public sealed partial class TypeParameterListSyntax : CSharpSyntaxNode { private SyntaxNode? parameters; internal TypeParameterListSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the &lt; token.</summary> public SyntaxToken LessThanToken => new SyntaxToken(this, ((Syntax.InternalSyntax.TypeParameterListSyntax)this.Green).lessThanToken, Position, 0); /// <summary>Gets the parameter list.</summary> public SeparatedSyntaxList<TypeParameterSyntax> Parameters { get { var red = GetRed(ref this.parameters, 1); return red != null ? new SeparatedSyntaxList<TypeParameterSyntax>(red, GetChildIndex(1)) : default; } } /// <summary>Gets the &gt; token.</summary> public SyntaxToken GreaterThanToken => new SyntaxToken(this, ((Syntax.InternalSyntax.TypeParameterListSyntax)this.Green).greaterThanToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.parameters, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.parameters : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitTypeParameterList(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitTypeParameterList(this); public TypeParameterListSyntax Update(SyntaxToken lessThanToken, SeparatedSyntaxList<TypeParameterSyntax> parameters, SyntaxToken greaterThanToken) { if (lessThanToken != this.LessThanToken || parameters != this.Parameters || greaterThanToken != this.GreaterThanToken) { var newNode = SyntaxFactory.TypeParameterList(lessThanToken, parameters, greaterThanToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public TypeParameterListSyntax WithLessThanToken(SyntaxToken lessThanToken) => Update(lessThanToken, this.Parameters, this.GreaterThanToken); public TypeParameterListSyntax WithParameters(SeparatedSyntaxList<TypeParameterSyntax> parameters) => Update(this.LessThanToken, parameters, this.GreaterThanToken); public TypeParameterListSyntax WithGreaterThanToken(SyntaxToken greaterThanToken) => Update(this.LessThanToken, this.Parameters, greaterThanToken); public TypeParameterListSyntax AddParameters(params TypeParameterSyntax[] items) => WithParameters(this.Parameters.AddRange(items)); } /// <summary>Type parameter syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.TypeParameter"/></description></item> /// </list> /// </remarks> public sealed partial class TypeParameterSyntax : CSharpSyntaxNode { private SyntaxNode? attributeLists; internal TypeParameterSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the attribute declaration list.</summary> public SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxToken VarianceKeyword { get { var slot = ((Syntax.InternalSyntax.TypeParameterSyntax)this.Green).varianceKeyword; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.TypeParameterSyntax)this.Green).identifier, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.attributeLists)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.attributeLists : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitTypeParameter(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitTypeParameter(this); public TypeParameterSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken varianceKeyword, SyntaxToken identifier) { if (attributeLists != this.AttributeLists || varianceKeyword != this.VarianceKeyword || identifier != this.Identifier) { var newNode = SyntaxFactory.TypeParameter(attributeLists, varianceKeyword, identifier); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public TypeParameterSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.VarianceKeyword, this.Identifier); public TypeParameterSyntax WithVarianceKeyword(SyntaxToken varianceKeyword) => Update(this.AttributeLists, varianceKeyword, this.Identifier); public TypeParameterSyntax WithIdentifier(SyntaxToken identifier) => Update(this.AttributeLists, this.VarianceKeyword, identifier); public TypeParameterSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); } /// <summary>Base class for type declaration syntax.</summary> public abstract partial class BaseTypeDeclarationSyntax : MemberDeclarationSyntax { internal BaseTypeDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the identifier.</summary> public abstract SyntaxToken Identifier { get; } public BaseTypeDeclarationSyntax WithIdentifier(SyntaxToken identifier) => WithIdentifierCore(identifier); internal abstract BaseTypeDeclarationSyntax WithIdentifierCore(SyntaxToken identifier); /// <summary>Gets the base type list.</summary> public abstract BaseListSyntax? BaseList { get; } public BaseTypeDeclarationSyntax WithBaseList(BaseListSyntax? baseList) => WithBaseListCore(baseList); internal abstract BaseTypeDeclarationSyntax WithBaseListCore(BaseListSyntax? baseList); public BaseTypeDeclarationSyntax AddBaseListTypes(params BaseTypeSyntax[] items) => AddBaseListTypesCore(items); internal abstract BaseTypeDeclarationSyntax AddBaseListTypesCore(params BaseTypeSyntax[] items); /// <summary>Gets the open brace token.</summary> public abstract SyntaxToken OpenBraceToken { get; } public BaseTypeDeclarationSyntax WithOpenBraceToken(SyntaxToken openBraceToken) => WithOpenBraceTokenCore(openBraceToken); internal abstract BaseTypeDeclarationSyntax WithOpenBraceTokenCore(SyntaxToken openBraceToken); /// <summary>Gets the close brace token.</summary> public abstract SyntaxToken CloseBraceToken { get; } public BaseTypeDeclarationSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) => WithCloseBraceTokenCore(closeBraceToken); internal abstract BaseTypeDeclarationSyntax WithCloseBraceTokenCore(SyntaxToken closeBraceToken); /// <summary>Gets the optional semicolon token.</summary> public abstract SyntaxToken SemicolonToken { get; } public BaseTypeDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => WithSemicolonTokenCore(semicolonToken); internal abstract BaseTypeDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken); public new BaseTypeDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => (BaseTypeDeclarationSyntax)WithAttributeListsCore(attributeLists); public new BaseTypeDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => (BaseTypeDeclarationSyntax)WithModifiersCore(modifiers); public new BaseTypeDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => (BaseTypeDeclarationSyntax)AddAttributeListsCore(items); public new BaseTypeDeclarationSyntax AddModifiers(params SyntaxToken[] items) => (BaseTypeDeclarationSyntax)AddModifiersCore(items); } /// <summary>Base class for type declaration syntax (class, struct, interface, record).</summary> public abstract partial class TypeDeclarationSyntax : BaseTypeDeclarationSyntax { internal TypeDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the type keyword token ("class", "struct", "interface", "record").</summary> public abstract SyntaxToken Keyword { get; } public TypeDeclarationSyntax WithKeyword(SyntaxToken keyword) => WithKeywordCore(keyword); internal abstract TypeDeclarationSyntax WithKeywordCore(SyntaxToken keyword); public abstract TypeParameterListSyntax? TypeParameterList { get; } public TypeDeclarationSyntax WithTypeParameterList(TypeParameterListSyntax? typeParameterList) => WithTypeParameterListCore(typeParameterList); internal abstract TypeDeclarationSyntax WithTypeParameterListCore(TypeParameterListSyntax? typeParameterList); public TypeDeclarationSyntax AddTypeParameterListParameters(params TypeParameterSyntax[] items) => AddTypeParameterListParametersCore(items); internal abstract TypeDeclarationSyntax AddTypeParameterListParametersCore(params TypeParameterSyntax[] items); /// <summary>Gets the type constraint list.</summary> public abstract SyntaxList<TypeParameterConstraintClauseSyntax> ConstraintClauses { get; } public TypeDeclarationSyntax WithConstraintClauses(SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses) => WithConstraintClausesCore(constraintClauses); internal abstract TypeDeclarationSyntax WithConstraintClausesCore(SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses); public TypeDeclarationSyntax AddConstraintClauses(params TypeParameterConstraintClauseSyntax[] items) => AddConstraintClausesCore(items); internal abstract TypeDeclarationSyntax AddConstraintClausesCore(params TypeParameterConstraintClauseSyntax[] items); /// <summary>Gets the member declarations.</summary> public abstract SyntaxList<MemberDeclarationSyntax> Members { get; } public TypeDeclarationSyntax WithMembers(SyntaxList<MemberDeclarationSyntax> members) => WithMembersCore(members); internal abstract TypeDeclarationSyntax WithMembersCore(SyntaxList<MemberDeclarationSyntax> members); public TypeDeclarationSyntax AddMembers(params MemberDeclarationSyntax[] items) => AddMembersCore(items); internal abstract TypeDeclarationSyntax AddMembersCore(params MemberDeclarationSyntax[] items); public new TypeDeclarationSyntax WithIdentifier(SyntaxToken identifier) => (TypeDeclarationSyntax)WithIdentifierCore(identifier); public new TypeDeclarationSyntax WithBaseList(BaseListSyntax? baseList) => (TypeDeclarationSyntax)WithBaseListCore(baseList); public new TypeDeclarationSyntax WithOpenBraceToken(SyntaxToken openBraceToken) => (TypeDeclarationSyntax)WithOpenBraceTokenCore(openBraceToken); public new TypeDeclarationSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) => (TypeDeclarationSyntax)WithCloseBraceTokenCore(closeBraceToken); public new TypeDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => (TypeDeclarationSyntax)WithSemicolonTokenCore(semicolonToken); public new BaseTypeDeclarationSyntax AddBaseListTypes(params BaseTypeSyntax[] items) => AddBaseListTypesCore(items); } /// <summary>Class type declaration syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ClassDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class ClassDeclarationSyntax : TypeDeclarationSyntax { private SyntaxNode? attributeLists; private TypeParameterListSyntax? typeParameterList; private BaseListSyntax? baseList; private SyntaxNode? constraintClauses; private SyntaxNode? members; internal ClassDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } /// <summary>Gets the class keyword token.</summary> public override SyntaxToken Keyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ClassDeclarationSyntax)this.Green).keyword, GetChildPosition(2), GetChildIndex(2)); public override SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.ClassDeclarationSyntax)this.Green).identifier, GetChildPosition(3), GetChildIndex(3)); public override TypeParameterListSyntax? TypeParameterList => GetRed(ref this.typeParameterList, 4); public override BaseListSyntax? BaseList => GetRed(ref this.baseList, 5); public override SyntaxList<TypeParameterConstraintClauseSyntax> ConstraintClauses => new SyntaxList<TypeParameterConstraintClauseSyntax>(GetRed(ref this.constraintClauses, 6)); public override SyntaxToken OpenBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ClassDeclarationSyntax)this.Green).openBraceToken, GetChildPosition(7), GetChildIndex(7)); public override SyntaxList<MemberDeclarationSyntax> Members => new SyntaxList<MemberDeclarationSyntax>(GetRed(ref this.members, 8)); public override SyntaxToken CloseBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ClassDeclarationSyntax)this.Green).closeBraceToken, GetChildPosition(9), GetChildIndex(9)); public override SyntaxToken SemicolonToken { get { var slot = ((Syntax.InternalSyntax.ClassDeclarationSyntax)this.Green).semicolonToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(10), GetChildIndex(10)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 4 => GetRed(ref this.typeParameterList, 4), 5 => GetRed(ref this.baseList, 5), 6 => GetRed(ref this.constraintClauses, 6)!, 8 => GetRed(ref this.members, 8)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 4 => this.typeParameterList, 5 => this.baseList, 6 => this.constraintClauses, 8 => this.members, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitClassDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitClassDeclaration(this); public ClassDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, BaseListSyntax? baseList, SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses, SyntaxToken openBraceToken, SyntaxList<MemberDeclarationSyntax> members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || keyword != this.Keyword || identifier != this.Identifier || typeParameterList != this.TypeParameterList || baseList != this.BaseList || constraintClauses != this.ConstraintClauses || openBraceToken != this.OpenBraceToken || members != this.Members || closeBraceToken != this.CloseBraceToken || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.ClassDeclaration(attributeLists, modifiers, keyword, identifier, typeParameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new ClassDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new ClassDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override TypeDeclarationSyntax WithKeywordCore(SyntaxToken keyword) => WithKeyword(keyword); public new ClassDeclarationSyntax WithKeyword(SyntaxToken keyword) => Update(this.AttributeLists, this.Modifiers, keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithIdentifierCore(SyntaxToken identifier) => WithIdentifier(identifier); public new ClassDeclarationSyntax WithIdentifier(SyntaxToken identifier) => Update(this.AttributeLists, this.Modifiers, this.Keyword, identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override TypeDeclarationSyntax WithTypeParameterListCore(TypeParameterListSyntax? typeParameterList) => WithTypeParameterList(typeParameterList); public new ClassDeclarationSyntax WithTypeParameterList(TypeParameterListSyntax? typeParameterList) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, typeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithBaseListCore(BaseListSyntax? baseList) => WithBaseList(baseList); public new ClassDeclarationSyntax WithBaseList(BaseListSyntax? baseList) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, baseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override TypeDeclarationSyntax WithConstraintClausesCore(SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses) => WithConstraintClauses(constraintClauses); public new ClassDeclarationSyntax WithConstraintClauses(SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, constraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithOpenBraceTokenCore(SyntaxToken openBraceToken) => WithOpenBraceToken(openBraceToken); public new ClassDeclarationSyntax WithOpenBraceToken(SyntaxToken openBraceToken) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, openBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override TypeDeclarationSyntax WithMembersCore(SyntaxList<MemberDeclarationSyntax> members) => WithMembers(members); public new ClassDeclarationSyntax WithMembers(SyntaxList<MemberDeclarationSyntax> members) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithCloseBraceTokenCore(SyntaxToken closeBraceToken) => WithCloseBraceToken(closeBraceToken); public new ClassDeclarationSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, closeBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken) => WithSemicolonToken(semicolonToken); public new ClassDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, semicolonToken); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new ClassDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new ClassDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); internal override TypeDeclarationSyntax AddTypeParameterListParametersCore(params TypeParameterSyntax[] items) => AddTypeParameterListParameters(items); public new ClassDeclarationSyntax AddTypeParameterListParameters(params TypeParameterSyntax[] items) { var typeParameterList = this.TypeParameterList ?? SyntaxFactory.TypeParameterList(); return WithTypeParameterList(typeParameterList.WithParameters(typeParameterList.Parameters.AddRange(items))); } internal override BaseTypeDeclarationSyntax AddBaseListTypesCore(params BaseTypeSyntax[] items) => AddBaseListTypes(items); public new ClassDeclarationSyntax AddBaseListTypes(params BaseTypeSyntax[] items) { var baseList = this.BaseList ?? SyntaxFactory.BaseList(); return WithBaseList(baseList.WithTypes(baseList.Types.AddRange(items))); } internal override TypeDeclarationSyntax AddConstraintClausesCore(params TypeParameterConstraintClauseSyntax[] items) => AddConstraintClauses(items); public new ClassDeclarationSyntax AddConstraintClauses(params TypeParameterConstraintClauseSyntax[] items) => WithConstraintClauses(this.ConstraintClauses.AddRange(items)); internal override TypeDeclarationSyntax AddMembersCore(params MemberDeclarationSyntax[] items) => AddMembers(items); public new ClassDeclarationSyntax AddMembers(params MemberDeclarationSyntax[] items) => WithMembers(this.Members.AddRange(items)); } /// <summary>Struct type declaration syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.StructDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class StructDeclarationSyntax : TypeDeclarationSyntax { private SyntaxNode? attributeLists; private TypeParameterListSyntax? typeParameterList; private BaseListSyntax? baseList; private SyntaxNode? constraintClauses; private SyntaxNode? members; internal StructDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } /// <summary>Gets the struct keyword token.</summary> public override SyntaxToken Keyword => new SyntaxToken(this, ((Syntax.InternalSyntax.StructDeclarationSyntax)this.Green).keyword, GetChildPosition(2), GetChildIndex(2)); public override SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.StructDeclarationSyntax)this.Green).identifier, GetChildPosition(3), GetChildIndex(3)); public override TypeParameterListSyntax? TypeParameterList => GetRed(ref this.typeParameterList, 4); public override BaseListSyntax? BaseList => GetRed(ref this.baseList, 5); public override SyntaxList<TypeParameterConstraintClauseSyntax> ConstraintClauses => new SyntaxList<TypeParameterConstraintClauseSyntax>(GetRed(ref this.constraintClauses, 6)); public override SyntaxToken OpenBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.StructDeclarationSyntax)this.Green).openBraceToken, GetChildPosition(7), GetChildIndex(7)); public override SyntaxList<MemberDeclarationSyntax> Members => new SyntaxList<MemberDeclarationSyntax>(GetRed(ref this.members, 8)); public override SyntaxToken CloseBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.StructDeclarationSyntax)this.Green).closeBraceToken, GetChildPosition(9), GetChildIndex(9)); public override SyntaxToken SemicolonToken { get { var slot = ((Syntax.InternalSyntax.StructDeclarationSyntax)this.Green).semicolonToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(10), GetChildIndex(10)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 4 => GetRed(ref this.typeParameterList, 4), 5 => GetRed(ref this.baseList, 5), 6 => GetRed(ref this.constraintClauses, 6)!, 8 => GetRed(ref this.members, 8)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 4 => this.typeParameterList, 5 => this.baseList, 6 => this.constraintClauses, 8 => this.members, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitStructDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitStructDeclaration(this); public StructDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, BaseListSyntax? baseList, SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses, SyntaxToken openBraceToken, SyntaxList<MemberDeclarationSyntax> members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || keyword != this.Keyword || identifier != this.Identifier || typeParameterList != this.TypeParameterList || baseList != this.BaseList || constraintClauses != this.ConstraintClauses || openBraceToken != this.OpenBraceToken || members != this.Members || closeBraceToken != this.CloseBraceToken || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.StructDeclaration(attributeLists, modifiers, keyword, identifier, typeParameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new StructDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new StructDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override TypeDeclarationSyntax WithKeywordCore(SyntaxToken keyword) => WithKeyword(keyword); public new StructDeclarationSyntax WithKeyword(SyntaxToken keyword) => Update(this.AttributeLists, this.Modifiers, keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithIdentifierCore(SyntaxToken identifier) => WithIdentifier(identifier); public new StructDeclarationSyntax WithIdentifier(SyntaxToken identifier) => Update(this.AttributeLists, this.Modifiers, this.Keyword, identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override TypeDeclarationSyntax WithTypeParameterListCore(TypeParameterListSyntax? typeParameterList) => WithTypeParameterList(typeParameterList); public new StructDeclarationSyntax WithTypeParameterList(TypeParameterListSyntax? typeParameterList) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, typeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithBaseListCore(BaseListSyntax? baseList) => WithBaseList(baseList); public new StructDeclarationSyntax WithBaseList(BaseListSyntax? baseList) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, baseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override TypeDeclarationSyntax WithConstraintClausesCore(SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses) => WithConstraintClauses(constraintClauses); public new StructDeclarationSyntax WithConstraintClauses(SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, constraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithOpenBraceTokenCore(SyntaxToken openBraceToken) => WithOpenBraceToken(openBraceToken); public new StructDeclarationSyntax WithOpenBraceToken(SyntaxToken openBraceToken) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, openBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override TypeDeclarationSyntax WithMembersCore(SyntaxList<MemberDeclarationSyntax> members) => WithMembers(members); public new StructDeclarationSyntax WithMembers(SyntaxList<MemberDeclarationSyntax> members) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithCloseBraceTokenCore(SyntaxToken closeBraceToken) => WithCloseBraceToken(closeBraceToken); public new StructDeclarationSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, closeBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken) => WithSemicolonToken(semicolonToken); public new StructDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, semicolonToken); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new StructDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new StructDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); internal override TypeDeclarationSyntax AddTypeParameterListParametersCore(params TypeParameterSyntax[] items) => AddTypeParameterListParameters(items); public new StructDeclarationSyntax AddTypeParameterListParameters(params TypeParameterSyntax[] items) { var typeParameterList = this.TypeParameterList ?? SyntaxFactory.TypeParameterList(); return WithTypeParameterList(typeParameterList.WithParameters(typeParameterList.Parameters.AddRange(items))); } internal override BaseTypeDeclarationSyntax AddBaseListTypesCore(params BaseTypeSyntax[] items) => AddBaseListTypes(items); public new StructDeclarationSyntax AddBaseListTypes(params BaseTypeSyntax[] items) { var baseList = this.BaseList ?? SyntaxFactory.BaseList(); return WithBaseList(baseList.WithTypes(baseList.Types.AddRange(items))); } internal override TypeDeclarationSyntax AddConstraintClausesCore(params TypeParameterConstraintClauseSyntax[] items) => AddConstraintClauses(items); public new StructDeclarationSyntax AddConstraintClauses(params TypeParameterConstraintClauseSyntax[] items) => WithConstraintClauses(this.ConstraintClauses.AddRange(items)); internal override TypeDeclarationSyntax AddMembersCore(params MemberDeclarationSyntax[] items) => AddMembers(items); public new StructDeclarationSyntax AddMembers(params MemberDeclarationSyntax[] items) => WithMembers(this.Members.AddRange(items)); } /// <summary>Interface type declaration syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.InterfaceDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class InterfaceDeclarationSyntax : TypeDeclarationSyntax { private SyntaxNode? attributeLists; private TypeParameterListSyntax? typeParameterList; private BaseListSyntax? baseList; private SyntaxNode? constraintClauses; private SyntaxNode? members; internal InterfaceDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } /// <summary>Gets the interface keyword token.</summary> public override SyntaxToken Keyword => new SyntaxToken(this, ((Syntax.InternalSyntax.InterfaceDeclarationSyntax)this.Green).keyword, GetChildPosition(2), GetChildIndex(2)); public override SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.InterfaceDeclarationSyntax)this.Green).identifier, GetChildPosition(3), GetChildIndex(3)); public override TypeParameterListSyntax? TypeParameterList => GetRed(ref this.typeParameterList, 4); public override BaseListSyntax? BaseList => GetRed(ref this.baseList, 5); public override SyntaxList<TypeParameterConstraintClauseSyntax> ConstraintClauses => new SyntaxList<TypeParameterConstraintClauseSyntax>(GetRed(ref this.constraintClauses, 6)); public override SyntaxToken OpenBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.InterfaceDeclarationSyntax)this.Green).openBraceToken, GetChildPosition(7), GetChildIndex(7)); public override SyntaxList<MemberDeclarationSyntax> Members => new SyntaxList<MemberDeclarationSyntax>(GetRed(ref this.members, 8)); public override SyntaxToken CloseBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.InterfaceDeclarationSyntax)this.Green).closeBraceToken, GetChildPosition(9), GetChildIndex(9)); public override SyntaxToken SemicolonToken { get { var slot = ((Syntax.InternalSyntax.InterfaceDeclarationSyntax)this.Green).semicolonToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(10), GetChildIndex(10)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 4 => GetRed(ref this.typeParameterList, 4), 5 => GetRed(ref this.baseList, 5), 6 => GetRed(ref this.constraintClauses, 6)!, 8 => GetRed(ref this.members, 8)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 4 => this.typeParameterList, 5 => this.baseList, 6 => this.constraintClauses, 8 => this.members, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitInterfaceDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitInterfaceDeclaration(this); public InterfaceDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, BaseListSyntax? baseList, SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses, SyntaxToken openBraceToken, SyntaxList<MemberDeclarationSyntax> members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || keyword != this.Keyword || identifier != this.Identifier || typeParameterList != this.TypeParameterList || baseList != this.BaseList || constraintClauses != this.ConstraintClauses || openBraceToken != this.OpenBraceToken || members != this.Members || closeBraceToken != this.CloseBraceToken || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.InterfaceDeclaration(attributeLists, modifiers, keyword, identifier, typeParameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new InterfaceDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new InterfaceDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override TypeDeclarationSyntax WithKeywordCore(SyntaxToken keyword) => WithKeyword(keyword); public new InterfaceDeclarationSyntax WithKeyword(SyntaxToken keyword) => Update(this.AttributeLists, this.Modifiers, keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithIdentifierCore(SyntaxToken identifier) => WithIdentifier(identifier); public new InterfaceDeclarationSyntax WithIdentifier(SyntaxToken identifier) => Update(this.AttributeLists, this.Modifiers, this.Keyword, identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override TypeDeclarationSyntax WithTypeParameterListCore(TypeParameterListSyntax? typeParameterList) => WithTypeParameterList(typeParameterList); public new InterfaceDeclarationSyntax WithTypeParameterList(TypeParameterListSyntax? typeParameterList) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, typeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithBaseListCore(BaseListSyntax? baseList) => WithBaseList(baseList); public new InterfaceDeclarationSyntax WithBaseList(BaseListSyntax? baseList) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, baseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override TypeDeclarationSyntax WithConstraintClausesCore(SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses) => WithConstraintClauses(constraintClauses); public new InterfaceDeclarationSyntax WithConstraintClauses(SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, constraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithOpenBraceTokenCore(SyntaxToken openBraceToken) => WithOpenBraceToken(openBraceToken); public new InterfaceDeclarationSyntax WithOpenBraceToken(SyntaxToken openBraceToken) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, openBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override TypeDeclarationSyntax WithMembersCore(SyntaxList<MemberDeclarationSyntax> members) => WithMembers(members); public new InterfaceDeclarationSyntax WithMembers(SyntaxList<MemberDeclarationSyntax> members) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithCloseBraceTokenCore(SyntaxToken closeBraceToken) => WithCloseBraceToken(closeBraceToken); public new InterfaceDeclarationSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, closeBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken) => WithSemicolonToken(semicolonToken); public new InterfaceDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, semicolonToken); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new InterfaceDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new InterfaceDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); internal override TypeDeclarationSyntax AddTypeParameterListParametersCore(params TypeParameterSyntax[] items) => AddTypeParameterListParameters(items); public new InterfaceDeclarationSyntax AddTypeParameterListParameters(params TypeParameterSyntax[] items) { var typeParameterList = this.TypeParameterList ?? SyntaxFactory.TypeParameterList(); return WithTypeParameterList(typeParameterList.WithParameters(typeParameterList.Parameters.AddRange(items))); } internal override BaseTypeDeclarationSyntax AddBaseListTypesCore(params BaseTypeSyntax[] items) => AddBaseListTypes(items); public new InterfaceDeclarationSyntax AddBaseListTypes(params BaseTypeSyntax[] items) { var baseList = this.BaseList ?? SyntaxFactory.BaseList(); return WithBaseList(baseList.WithTypes(baseList.Types.AddRange(items))); } internal override TypeDeclarationSyntax AddConstraintClausesCore(params TypeParameterConstraintClauseSyntax[] items) => AddConstraintClauses(items); public new InterfaceDeclarationSyntax AddConstraintClauses(params TypeParameterConstraintClauseSyntax[] items) => WithConstraintClauses(this.ConstraintClauses.AddRange(items)); internal override TypeDeclarationSyntax AddMembersCore(params MemberDeclarationSyntax[] items) => AddMembers(items); public new InterfaceDeclarationSyntax AddMembers(params MemberDeclarationSyntax[] items) => WithMembers(this.Members.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.RecordDeclaration"/></description></item> /// <item><description><see cref="SyntaxKind.RecordStructDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class RecordDeclarationSyntax : TypeDeclarationSyntax { private SyntaxNode? attributeLists; private TypeParameterListSyntax? typeParameterList; private ParameterListSyntax? parameterList; private BaseListSyntax? baseList; private SyntaxNode? constraintClauses; private SyntaxNode? members; internal RecordDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public override SyntaxToken Keyword => new SyntaxToken(this, ((Syntax.InternalSyntax.RecordDeclarationSyntax)this.Green).keyword, GetChildPosition(2), GetChildIndex(2)); public SyntaxToken ClassOrStructKeyword { get { var slot = ((Syntax.InternalSyntax.RecordDeclarationSyntax)this.Green).classOrStructKeyword; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(3), GetChildIndex(3)) : default; } } public override SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.RecordDeclarationSyntax)this.Green).identifier, GetChildPosition(4), GetChildIndex(4)); public override TypeParameterListSyntax? TypeParameterList => GetRed(ref this.typeParameterList, 5); public ParameterListSyntax? ParameterList => GetRed(ref this.parameterList, 6); public override BaseListSyntax? BaseList => GetRed(ref this.baseList, 7); public override SyntaxList<TypeParameterConstraintClauseSyntax> ConstraintClauses => new SyntaxList<TypeParameterConstraintClauseSyntax>(GetRed(ref this.constraintClauses, 8)); public override SyntaxToken OpenBraceToken { get { var slot = ((Syntax.InternalSyntax.RecordDeclarationSyntax)this.Green).openBraceToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(9), GetChildIndex(9)) : default; } } public override SyntaxList<MemberDeclarationSyntax> Members => new SyntaxList<MemberDeclarationSyntax>(GetRed(ref this.members, 10)); public override SyntaxToken CloseBraceToken { get { var slot = ((Syntax.InternalSyntax.RecordDeclarationSyntax)this.Green).closeBraceToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(11), GetChildIndex(11)) : default; } } public override SyntaxToken SemicolonToken { get { var slot = ((Syntax.InternalSyntax.RecordDeclarationSyntax)this.Green).semicolonToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(12), GetChildIndex(12)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 5 => GetRed(ref this.typeParameterList, 5), 6 => GetRed(ref this.parameterList, 6), 7 => GetRed(ref this.baseList, 7), 8 => GetRed(ref this.constraintClauses, 8)!, 10 => GetRed(ref this.members, 10)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 5 => this.typeParameterList, 6 => this.parameterList, 7 => this.baseList, 8 => this.constraintClauses, 10 => this.members, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitRecordDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitRecordDeclaration(this); public RecordDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, SyntaxToken classOrStructKeyword, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax? parameterList, BaseListSyntax? baseList, SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses, SyntaxToken openBraceToken, SyntaxList<MemberDeclarationSyntax> members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || keyword != this.Keyword || classOrStructKeyword != this.ClassOrStructKeyword || identifier != this.Identifier || typeParameterList != this.TypeParameterList || parameterList != this.ParameterList || baseList != this.BaseList || constraintClauses != this.ConstraintClauses || openBraceToken != this.OpenBraceToken || members != this.Members || closeBraceToken != this.CloseBraceToken || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.RecordDeclaration(this.Kind(), attributeLists, modifiers, keyword, classOrStructKeyword, identifier, typeParameterList, parameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new RecordDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.Keyword, this.ClassOrStructKeyword, this.Identifier, this.TypeParameterList, this.ParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new RecordDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.Keyword, this.ClassOrStructKeyword, this.Identifier, this.TypeParameterList, this.ParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override TypeDeclarationSyntax WithKeywordCore(SyntaxToken keyword) => WithKeyword(keyword); public new RecordDeclarationSyntax WithKeyword(SyntaxToken keyword) => Update(this.AttributeLists, this.Modifiers, keyword, this.ClassOrStructKeyword, this.Identifier, this.TypeParameterList, this.ParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); public RecordDeclarationSyntax WithClassOrStructKeyword(SyntaxToken classOrStructKeyword) => Update(this.AttributeLists, this.Modifiers, this.Keyword, classOrStructKeyword, this.Identifier, this.TypeParameterList, this.ParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithIdentifierCore(SyntaxToken identifier) => WithIdentifier(identifier); public new RecordDeclarationSyntax WithIdentifier(SyntaxToken identifier) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.ClassOrStructKeyword, identifier, this.TypeParameterList, this.ParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override TypeDeclarationSyntax WithTypeParameterListCore(TypeParameterListSyntax? typeParameterList) => WithTypeParameterList(typeParameterList); public new RecordDeclarationSyntax WithTypeParameterList(TypeParameterListSyntax? typeParameterList) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.ClassOrStructKeyword, this.Identifier, typeParameterList, this.ParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); public RecordDeclarationSyntax WithParameterList(ParameterListSyntax? parameterList) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.ClassOrStructKeyword, this.Identifier, this.TypeParameterList, parameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithBaseListCore(BaseListSyntax? baseList) => WithBaseList(baseList); public new RecordDeclarationSyntax WithBaseList(BaseListSyntax? baseList) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.ClassOrStructKeyword, this.Identifier, this.TypeParameterList, this.ParameterList, baseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override TypeDeclarationSyntax WithConstraintClausesCore(SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses) => WithConstraintClauses(constraintClauses); public new RecordDeclarationSyntax WithConstraintClauses(SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.ClassOrStructKeyword, this.Identifier, this.TypeParameterList, this.ParameterList, this.BaseList, constraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithOpenBraceTokenCore(SyntaxToken openBraceToken) => WithOpenBraceToken(openBraceToken); public new RecordDeclarationSyntax WithOpenBraceToken(SyntaxToken openBraceToken) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.ClassOrStructKeyword, this.Identifier, this.TypeParameterList, this.ParameterList, this.BaseList, this.ConstraintClauses, openBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override TypeDeclarationSyntax WithMembersCore(SyntaxList<MemberDeclarationSyntax> members) => WithMembers(members); public new RecordDeclarationSyntax WithMembers(SyntaxList<MemberDeclarationSyntax> members) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.ClassOrStructKeyword, this.Identifier, this.TypeParameterList, this.ParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithCloseBraceTokenCore(SyntaxToken closeBraceToken) => WithCloseBraceToken(closeBraceToken); public new RecordDeclarationSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.ClassOrStructKeyword, this.Identifier, this.TypeParameterList, this.ParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, closeBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken) => WithSemicolonToken(semicolonToken); public new RecordDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.ClassOrStructKeyword, this.Identifier, this.TypeParameterList, this.ParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, semicolonToken); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new RecordDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new RecordDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); internal override TypeDeclarationSyntax AddTypeParameterListParametersCore(params TypeParameterSyntax[] items) => AddTypeParameterListParameters(items); public new RecordDeclarationSyntax AddTypeParameterListParameters(params TypeParameterSyntax[] items) { var typeParameterList = this.TypeParameterList ?? SyntaxFactory.TypeParameterList(); return WithTypeParameterList(typeParameterList.WithParameters(typeParameterList.Parameters.AddRange(items))); } public RecordDeclarationSyntax AddParameterListParameters(params ParameterSyntax[] items) { var parameterList = this.ParameterList ?? SyntaxFactory.ParameterList(); return WithParameterList(parameterList.WithParameters(parameterList.Parameters.AddRange(items))); } internal override BaseTypeDeclarationSyntax AddBaseListTypesCore(params BaseTypeSyntax[] items) => AddBaseListTypes(items); public new RecordDeclarationSyntax AddBaseListTypes(params BaseTypeSyntax[] items) { var baseList = this.BaseList ?? SyntaxFactory.BaseList(); return WithBaseList(baseList.WithTypes(baseList.Types.AddRange(items))); } internal override TypeDeclarationSyntax AddConstraintClausesCore(params TypeParameterConstraintClauseSyntax[] items) => AddConstraintClauses(items); public new RecordDeclarationSyntax AddConstraintClauses(params TypeParameterConstraintClauseSyntax[] items) => WithConstraintClauses(this.ConstraintClauses.AddRange(items)); internal override TypeDeclarationSyntax AddMembersCore(params MemberDeclarationSyntax[] items) => AddMembers(items); public new RecordDeclarationSyntax AddMembers(params MemberDeclarationSyntax[] items) => WithMembers(this.Members.AddRange(items)); } /// <summary>Enum type declaration syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.EnumDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class EnumDeclarationSyntax : BaseTypeDeclarationSyntax { private SyntaxNode? attributeLists; private BaseListSyntax? baseList; private SyntaxNode? members; internal EnumDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } /// <summary>Gets the enum keyword token.</summary> public SyntaxToken EnumKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.EnumDeclarationSyntax)this.Green).enumKeyword, GetChildPosition(2), GetChildIndex(2)); public override SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.EnumDeclarationSyntax)this.Green).identifier, GetChildPosition(3), GetChildIndex(3)); public override BaseListSyntax? BaseList => GetRed(ref this.baseList, 4); public override SyntaxToken OpenBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.EnumDeclarationSyntax)this.Green).openBraceToken, GetChildPosition(5), GetChildIndex(5)); /// <summary>Gets the members declaration list.</summary> public SeparatedSyntaxList<EnumMemberDeclarationSyntax> Members { get { var red = GetRed(ref this.members, 6); return red != null ? new SeparatedSyntaxList<EnumMemberDeclarationSyntax>(red, GetChildIndex(6)) : default; } } public override SyntaxToken CloseBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.EnumDeclarationSyntax)this.Green).closeBraceToken, GetChildPosition(7), GetChildIndex(7)); /// <summary>Gets the optional semicolon token.</summary> public override SyntaxToken SemicolonToken { get { var slot = ((Syntax.InternalSyntax.EnumDeclarationSyntax)this.Green).semicolonToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(8), GetChildIndex(8)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 4 => GetRed(ref this.baseList, 4), 6 => GetRed(ref this.members, 6)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 4 => this.baseList, 6 => this.members, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitEnumDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitEnumDeclaration(this); public EnumDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken enumKeyword, SyntaxToken identifier, BaseListSyntax? baseList, SyntaxToken openBraceToken, SeparatedSyntaxList<EnumMemberDeclarationSyntax> members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || enumKeyword != this.EnumKeyword || identifier != this.Identifier || baseList != this.BaseList || openBraceToken != this.OpenBraceToken || members != this.Members || closeBraceToken != this.CloseBraceToken || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.EnumDeclaration(attributeLists, modifiers, enumKeyword, identifier, baseList, openBraceToken, members, closeBraceToken, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new EnumDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.EnumKeyword, this.Identifier, this.BaseList, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new EnumDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.EnumKeyword, this.Identifier, this.BaseList, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); public EnumDeclarationSyntax WithEnumKeyword(SyntaxToken enumKeyword) => Update(this.AttributeLists, this.Modifiers, enumKeyword, this.Identifier, this.BaseList, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithIdentifierCore(SyntaxToken identifier) => WithIdentifier(identifier); public new EnumDeclarationSyntax WithIdentifier(SyntaxToken identifier) => Update(this.AttributeLists, this.Modifiers, this.EnumKeyword, identifier, this.BaseList, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithBaseListCore(BaseListSyntax? baseList) => WithBaseList(baseList); public new EnumDeclarationSyntax WithBaseList(BaseListSyntax? baseList) => Update(this.AttributeLists, this.Modifiers, this.EnumKeyword, this.Identifier, baseList, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithOpenBraceTokenCore(SyntaxToken openBraceToken) => WithOpenBraceToken(openBraceToken); public new EnumDeclarationSyntax WithOpenBraceToken(SyntaxToken openBraceToken) => Update(this.AttributeLists, this.Modifiers, this.EnumKeyword, this.Identifier, this.BaseList, openBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); public EnumDeclarationSyntax WithMembers(SeparatedSyntaxList<EnumMemberDeclarationSyntax> members) => Update(this.AttributeLists, this.Modifiers, this.EnumKeyword, this.Identifier, this.BaseList, this.OpenBraceToken, members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithCloseBraceTokenCore(SyntaxToken closeBraceToken) => WithCloseBraceToken(closeBraceToken); public new EnumDeclarationSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) => Update(this.AttributeLists, this.Modifiers, this.EnumKeyword, this.Identifier, this.BaseList, this.OpenBraceToken, this.Members, closeBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken) => WithSemicolonToken(semicolonToken); public new EnumDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.EnumKeyword, this.Identifier, this.BaseList, this.OpenBraceToken, this.Members, this.CloseBraceToken, semicolonToken); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new EnumDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new EnumDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); internal override BaseTypeDeclarationSyntax AddBaseListTypesCore(params BaseTypeSyntax[] items) => AddBaseListTypes(items); public new EnumDeclarationSyntax AddBaseListTypes(params BaseTypeSyntax[] items) { var baseList = this.BaseList ?? SyntaxFactory.BaseList(); return WithBaseList(baseList.WithTypes(baseList.Types.AddRange(items))); } public EnumDeclarationSyntax AddMembers(params EnumMemberDeclarationSyntax[] items) => WithMembers(this.Members.AddRange(items)); } /// <summary>Delegate declaration syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.DelegateDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class DelegateDeclarationSyntax : MemberDeclarationSyntax { private SyntaxNode? attributeLists; private TypeSyntax? returnType; private TypeParameterListSyntax? typeParameterList; private ParameterListSyntax? parameterList; private SyntaxNode? constraintClauses; internal DelegateDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } /// <summary>Gets the "delegate" keyword.</summary> public SyntaxToken DelegateKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.DelegateDeclarationSyntax)this.Green).delegateKeyword, GetChildPosition(2), GetChildIndex(2)); /// <summary>Gets the return type.</summary> public TypeSyntax ReturnType => GetRed(ref this.returnType, 3)!; /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.DelegateDeclarationSyntax)this.Green).identifier, GetChildPosition(4), GetChildIndex(4)); public TypeParameterListSyntax? TypeParameterList => GetRed(ref this.typeParameterList, 5); /// <summary>Gets the parameter list.</summary> public ParameterListSyntax ParameterList => GetRed(ref this.parameterList, 6)!; /// <summary>Gets the constraint clause list.</summary> public SyntaxList<TypeParameterConstraintClauseSyntax> ConstraintClauses => new SyntaxList<TypeParameterConstraintClauseSyntax>(GetRed(ref this.constraintClauses, 7)); /// <summary>Gets the semicolon token.</summary> public SyntaxToken SemicolonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.DelegateDeclarationSyntax)this.Green).semicolonToken, GetChildPosition(8), GetChildIndex(8)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 3 => GetRed(ref this.returnType, 3)!, 5 => GetRed(ref this.typeParameterList, 5), 6 => GetRed(ref this.parameterList, 6)!, 7 => GetRed(ref this.constraintClauses, 7)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 3 => this.returnType, 5 => this.typeParameterList, 6 => this.parameterList, 7 => this.constraintClauses, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitDelegateDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitDelegateDeclaration(this); public DelegateDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken delegateKeyword, TypeSyntax returnType, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax parameterList, SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || delegateKeyword != this.DelegateKeyword || returnType != this.ReturnType || identifier != this.Identifier || typeParameterList != this.TypeParameterList || parameterList != this.ParameterList || constraintClauses != this.ConstraintClauses || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.DelegateDeclaration(attributeLists, modifiers, delegateKeyword, returnType, identifier, typeParameterList, parameterList, constraintClauses, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new DelegateDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.DelegateKeyword, this.ReturnType, this.Identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, this.SemicolonToken); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new DelegateDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.DelegateKeyword, this.ReturnType, this.Identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, this.SemicolonToken); public DelegateDeclarationSyntax WithDelegateKeyword(SyntaxToken delegateKeyword) => Update(this.AttributeLists, this.Modifiers, delegateKeyword, this.ReturnType, this.Identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, this.SemicolonToken); public DelegateDeclarationSyntax WithReturnType(TypeSyntax returnType) => Update(this.AttributeLists, this.Modifiers, this.DelegateKeyword, returnType, this.Identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, this.SemicolonToken); public DelegateDeclarationSyntax WithIdentifier(SyntaxToken identifier) => Update(this.AttributeLists, this.Modifiers, this.DelegateKeyword, this.ReturnType, identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, this.SemicolonToken); public DelegateDeclarationSyntax WithTypeParameterList(TypeParameterListSyntax? typeParameterList) => Update(this.AttributeLists, this.Modifiers, this.DelegateKeyword, this.ReturnType, this.Identifier, typeParameterList, this.ParameterList, this.ConstraintClauses, this.SemicolonToken); public DelegateDeclarationSyntax WithParameterList(ParameterListSyntax parameterList) => Update(this.AttributeLists, this.Modifiers, this.DelegateKeyword, this.ReturnType, this.Identifier, this.TypeParameterList, parameterList, this.ConstraintClauses, this.SemicolonToken); public DelegateDeclarationSyntax WithConstraintClauses(SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses) => Update(this.AttributeLists, this.Modifiers, this.DelegateKeyword, this.ReturnType, this.Identifier, this.TypeParameterList, this.ParameterList, constraintClauses, this.SemicolonToken); public DelegateDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.DelegateKeyword, this.ReturnType, this.Identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, semicolonToken); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new DelegateDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new DelegateDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); public DelegateDeclarationSyntax AddTypeParameterListParameters(params TypeParameterSyntax[] items) { var typeParameterList = this.TypeParameterList ?? SyntaxFactory.TypeParameterList(); return WithTypeParameterList(typeParameterList.WithParameters(typeParameterList.Parameters.AddRange(items))); } public DelegateDeclarationSyntax AddParameterListParameters(params ParameterSyntax[] items) => WithParameterList(this.ParameterList.WithParameters(this.ParameterList.Parameters.AddRange(items))); public DelegateDeclarationSyntax AddConstraintClauses(params TypeParameterConstraintClauseSyntax[] items) => WithConstraintClauses(this.ConstraintClauses.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.EnumMemberDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class EnumMemberDeclarationSyntax : MemberDeclarationSyntax { private SyntaxNode? attributeLists; private EqualsValueClauseSyntax? equalsValue; internal EnumMemberDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.EnumMemberDeclarationSyntax)this.Green).identifier, GetChildPosition(2), GetChildIndex(2)); public EqualsValueClauseSyntax? EqualsValue => GetRed(ref this.equalsValue, 3); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 3 => GetRed(ref this.equalsValue, 3), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 3 => this.equalsValue, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitEnumMemberDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitEnumMemberDeclaration(this); public EnumMemberDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken identifier, EqualsValueClauseSyntax? equalsValue) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || identifier != this.Identifier || equalsValue != this.EqualsValue) { var newNode = SyntaxFactory.EnumMemberDeclaration(attributeLists, modifiers, identifier, equalsValue); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new EnumMemberDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.Identifier, this.EqualsValue); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new EnumMemberDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.Identifier, this.EqualsValue); public EnumMemberDeclarationSyntax WithIdentifier(SyntaxToken identifier) => Update(this.AttributeLists, this.Modifiers, identifier, this.EqualsValue); public EnumMemberDeclarationSyntax WithEqualsValue(EqualsValueClauseSyntax? equalsValue) => Update(this.AttributeLists, this.Modifiers, this.Identifier, equalsValue); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new EnumMemberDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new EnumMemberDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); } /// <summary>Base list syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.BaseList"/></description></item> /// </list> /// </remarks> public sealed partial class BaseListSyntax : CSharpSyntaxNode { private SyntaxNode? types; internal BaseListSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the colon token.</summary> public SyntaxToken ColonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.BaseListSyntax)this.Green).colonToken, Position, 0); /// <summary>Gets the base type references.</summary> public SeparatedSyntaxList<BaseTypeSyntax> Types { get { var red = GetRed(ref this.types, 1); return red != null ? new SeparatedSyntaxList<BaseTypeSyntax>(red, GetChildIndex(1)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.types, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.types : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitBaseList(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitBaseList(this); public BaseListSyntax Update(SyntaxToken colonToken, SeparatedSyntaxList<BaseTypeSyntax> types) { if (colonToken != this.ColonToken || types != this.Types) { var newNode = SyntaxFactory.BaseList(colonToken, types); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public BaseListSyntax WithColonToken(SyntaxToken colonToken) => Update(colonToken, this.Types); public BaseListSyntax WithTypes(SeparatedSyntaxList<BaseTypeSyntax> types) => Update(this.ColonToken, types); public BaseListSyntax AddTypes(params BaseTypeSyntax[] items) => WithTypes(this.Types.AddRange(items)); } /// <summary>Provides the base class from which the classes that represent base type syntax nodes are derived. This is an abstract class.</summary> public abstract partial class BaseTypeSyntax : CSharpSyntaxNode { internal BaseTypeSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public abstract TypeSyntax Type { get; } public BaseTypeSyntax WithType(TypeSyntax type) => WithTypeCore(type); internal abstract BaseTypeSyntax WithTypeCore(TypeSyntax type); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.SimpleBaseType"/></description></item> /// </list> /// </remarks> public sealed partial class SimpleBaseTypeSyntax : BaseTypeSyntax { private TypeSyntax? type; internal SimpleBaseTypeSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override TypeSyntax Type => GetRedAtZero(ref this.type)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.type)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.type : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitSimpleBaseType(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitSimpleBaseType(this); public SimpleBaseTypeSyntax Update(TypeSyntax type) { if (type != this.Type) { var newNode = SyntaxFactory.SimpleBaseType(type); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override BaseTypeSyntax WithTypeCore(TypeSyntax type) => WithType(type); public new SimpleBaseTypeSyntax WithType(TypeSyntax type) => Update(type); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.PrimaryConstructorBaseType"/></description></item> /// </list> /// </remarks> public sealed partial class PrimaryConstructorBaseTypeSyntax : BaseTypeSyntax { private TypeSyntax? type; private ArgumentListSyntax? argumentList; internal PrimaryConstructorBaseTypeSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override TypeSyntax Type => GetRedAtZero(ref this.type)!; public ArgumentListSyntax ArgumentList => GetRed(ref this.argumentList, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.type)!, 1 => GetRed(ref this.argumentList, 1)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.type, 1 => this.argumentList, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitPrimaryConstructorBaseType(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitPrimaryConstructorBaseType(this); public PrimaryConstructorBaseTypeSyntax Update(TypeSyntax type, ArgumentListSyntax argumentList) { if (type != this.Type || argumentList != this.ArgumentList) { var newNode = SyntaxFactory.PrimaryConstructorBaseType(type, argumentList); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override BaseTypeSyntax WithTypeCore(TypeSyntax type) => WithType(type); public new PrimaryConstructorBaseTypeSyntax WithType(TypeSyntax type) => Update(type, this.ArgumentList); public PrimaryConstructorBaseTypeSyntax WithArgumentList(ArgumentListSyntax argumentList) => Update(this.Type, argumentList); public PrimaryConstructorBaseTypeSyntax AddArgumentListArguments(params ArgumentSyntax[] items) => WithArgumentList(this.ArgumentList.WithArguments(this.ArgumentList.Arguments.AddRange(items))); } /// <summary>Type parameter constraint clause.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.TypeParameterConstraintClause"/></description></item> /// </list> /// </remarks> public sealed partial class TypeParameterConstraintClauseSyntax : CSharpSyntaxNode { private IdentifierNameSyntax? name; private SyntaxNode? constraints; internal TypeParameterConstraintClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken WhereKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.TypeParameterConstraintClauseSyntax)this.Green).whereKeyword, Position, 0); /// <summary>Gets the identifier.</summary> public IdentifierNameSyntax Name => GetRed(ref this.name, 1)!; /// <summary>Gets the colon token.</summary> public SyntaxToken ColonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.TypeParameterConstraintClauseSyntax)this.Green).colonToken, GetChildPosition(2), GetChildIndex(2)); /// <summary>Gets the constraints list.</summary> public SeparatedSyntaxList<TypeParameterConstraintSyntax> Constraints { get { var red = GetRed(ref this.constraints, 3); return red != null ? new SeparatedSyntaxList<TypeParameterConstraintSyntax>(red, GetChildIndex(3)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index switch { 1 => GetRed(ref this.name, 1)!, 3 => GetRed(ref this.constraints, 3)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 1 => this.name, 3 => this.constraints, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitTypeParameterConstraintClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitTypeParameterConstraintClause(this); public TypeParameterConstraintClauseSyntax Update(SyntaxToken whereKeyword, IdentifierNameSyntax name, SyntaxToken colonToken, SeparatedSyntaxList<TypeParameterConstraintSyntax> constraints) { if (whereKeyword != this.WhereKeyword || name != this.Name || colonToken != this.ColonToken || constraints != this.Constraints) { var newNode = SyntaxFactory.TypeParameterConstraintClause(whereKeyword, name, colonToken, constraints); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public TypeParameterConstraintClauseSyntax WithWhereKeyword(SyntaxToken whereKeyword) => Update(whereKeyword, this.Name, this.ColonToken, this.Constraints); public TypeParameterConstraintClauseSyntax WithName(IdentifierNameSyntax name) => Update(this.WhereKeyword, name, this.ColonToken, this.Constraints); public TypeParameterConstraintClauseSyntax WithColonToken(SyntaxToken colonToken) => Update(this.WhereKeyword, this.Name, colonToken, this.Constraints); public TypeParameterConstraintClauseSyntax WithConstraints(SeparatedSyntaxList<TypeParameterConstraintSyntax> constraints) => Update(this.WhereKeyword, this.Name, this.ColonToken, constraints); public TypeParameterConstraintClauseSyntax AddConstraints(params TypeParameterConstraintSyntax[] items) => WithConstraints(this.Constraints.AddRange(items)); } /// <summary>Base type for type parameter constraint syntax.</summary> public abstract partial class TypeParameterConstraintSyntax : CSharpSyntaxNode { internal TypeParameterConstraintSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } } /// <summary>Constructor constraint syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ConstructorConstraint"/></description></item> /// </list> /// </remarks> public sealed partial class ConstructorConstraintSyntax : TypeParameterConstraintSyntax { internal ConstructorConstraintSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the "new" keyword.</summary> public SyntaxToken NewKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ConstructorConstraintSyntax)this.Green).newKeyword, Position, 0); /// <summary>Gets the open paren keyword.</summary> public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ConstructorConstraintSyntax)this.Green).openParenToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>Gets the close paren keyword.</summary> public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ConstructorConstraintSyntax)this.Green).closeParenToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitConstructorConstraint(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitConstructorConstraint(this); public ConstructorConstraintSyntax Update(SyntaxToken newKeyword, SyntaxToken openParenToken, SyntaxToken closeParenToken) { if (newKeyword != this.NewKeyword || openParenToken != this.OpenParenToken || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.ConstructorConstraint(newKeyword, openParenToken, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ConstructorConstraintSyntax WithNewKeyword(SyntaxToken newKeyword) => Update(newKeyword, this.OpenParenToken, this.CloseParenToken); public ConstructorConstraintSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.NewKeyword, openParenToken, this.CloseParenToken); public ConstructorConstraintSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.NewKeyword, this.OpenParenToken, closeParenToken); } /// <summary>Class or struct constraint syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ClassConstraint"/></description></item> /// <item><description><see cref="SyntaxKind.StructConstraint"/></description></item> /// </list> /// </remarks> public sealed partial class ClassOrStructConstraintSyntax : TypeParameterConstraintSyntax { internal ClassOrStructConstraintSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the constraint keyword ("class" or "struct").</summary> public SyntaxToken ClassOrStructKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ClassOrStructConstraintSyntax)this.Green).classOrStructKeyword, Position, 0); /// <summary>SyntaxToken representing the question mark.</summary> public SyntaxToken QuestionToken { get { var slot = ((Syntax.InternalSyntax.ClassOrStructConstraintSyntax)this.Green).questionToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitClassOrStructConstraint(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitClassOrStructConstraint(this); public ClassOrStructConstraintSyntax Update(SyntaxToken classOrStructKeyword, SyntaxToken questionToken) { if (classOrStructKeyword != this.ClassOrStructKeyword || questionToken != this.QuestionToken) { var newNode = SyntaxFactory.ClassOrStructConstraint(this.Kind(), classOrStructKeyword, questionToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ClassOrStructConstraintSyntax WithClassOrStructKeyword(SyntaxToken classOrStructKeyword) => Update(classOrStructKeyword, this.QuestionToken); public ClassOrStructConstraintSyntax WithQuestionToken(SyntaxToken questionToken) => Update(this.ClassOrStructKeyword, questionToken); } /// <summary>Type constraint syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.TypeConstraint"/></description></item> /// </list> /// </remarks> public sealed partial class TypeConstraintSyntax : TypeParameterConstraintSyntax { private TypeSyntax? type; internal TypeConstraintSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the type syntax.</summary> public TypeSyntax Type => GetRedAtZero(ref this.type)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.type)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.type : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitTypeConstraint(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitTypeConstraint(this); public TypeConstraintSyntax Update(TypeSyntax type) { if (type != this.Type) { var newNode = SyntaxFactory.TypeConstraint(type); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public TypeConstraintSyntax WithType(TypeSyntax type) => Update(type); } /// <summary>Default constraint syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.DefaultConstraint"/></description></item> /// </list> /// </remarks> public sealed partial class DefaultConstraintSyntax : TypeParameterConstraintSyntax { internal DefaultConstraintSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the "default" keyword.</summary> public SyntaxToken DefaultKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.DefaultConstraintSyntax)this.Green).defaultKeyword, Position, 0); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitDefaultConstraint(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitDefaultConstraint(this); public DefaultConstraintSyntax Update(SyntaxToken defaultKeyword) { if (defaultKeyword != this.DefaultKeyword) { var newNode = SyntaxFactory.DefaultConstraint(defaultKeyword); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public DefaultConstraintSyntax WithDefaultKeyword(SyntaxToken defaultKeyword) => Update(defaultKeyword); } public abstract partial class BaseFieldDeclarationSyntax : MemberDeclarationSyntax { internal BaseFieldDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public abstract VariableDeclarationSyntax Declaration { get; } public BaseFieldDeclarationSyntax WithDeclaration(VariableDeclarationSyntax declaration) => WithDeclarationCore(declaration); internal abstract BaseFieldDeclarationSyntax WithDeclarationCore(VariableDeclarationSyntax declaration); public BaseFieldDeclarationSyntax AddDeclarationVariables(params VariableDeclaratorSyntax[] items) => AddDeclarationVariablesCore(items); internal abstract BaseFieldDeclarationSyntax AddDeclarationVariablesCore(params VariableDeclaratorSyntax[] items); public abstract SyntaxToken SemicolonToken { get; } public BaseFieldDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => WithSemicolonTokenCore(semicolonToken); internal abstract BaseFieldDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken); public new BaseFieldDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => (BaseFieldDeclarationSyntax)WithAttributeListsCore(attributeLists); public new BaseFieldDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => (BaseFieldDeclarationSyntax)WithModifiersCore(modifiers); public new BaseFieldDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => (BaseFieldDeclarationSyntax)AddAttributeListsCore(items); public new BaseFieldDeclarationSyntax AddModifiers(params SyntaxToken[] items) => (BaseFieldDeclarationSyntax)AddModifiersCore(items); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.FieldDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class FieldDeclarationSyntax : BaseFieldDeclarationSyntax { private SyntaxNode? attributeLists; private VariableDeclarationSyntax? declaration; internal FieldDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public override VariableDeclarationSyntax Declaration => GetRed(ref this.declaration, 2)!; public override SyntaxToken SemicolonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.FieldDeclarationSyntax)this.Green).semicolonToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.declaration, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.declaration, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitFieldDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitFieldDeclaration(this); public FieldDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || declaration != this.Declaration || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.FieldDeclaration(attributeLists, modifiers, declaration, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new FieldDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.Declaration, this.SemicolonToken); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new FieldDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.Declaration, this.SemicolonToken); internal override BaseFieldDeclarationSyntax WithDeclarationCore(VariableDeclarationSyntax declaration) => WithDeclaration(declaration); public new FieldDeclarationSyntax WithDeclaration(VariableDeclarationSyntax declaration) => Update(this.AttributeLists, this.Modifiers, declaration, this.SemicolonToken); internal override BaseFieldDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken) => WithSemicolonToken(semicolonToken); public new FieldDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.Declaration, semicolonToken); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new FieldDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new FieldDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); internal override BaseFieldDeclarationSyntax AddDeclarationVariablesCore(params VariableDeclaratorSyntax[] items) => AddDeclarationVariables(items); public new FieldDeclarationSyntax AddDeclarationVariables(params VariableDeclaratorSyntax[] items) => WithDeclaration(this.Declaration.WithVariables(this.Declaration.Variables.AddRange(items))); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.EventFieldDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class EventFieldDeclarationSyntax : BaseFieldDeclarationSyntax { private SyntaxNode? attributeLists; private VariableDeclarationSyntax? declaration; internal EventFieldDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public SyntaxToken EventKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.EventFieldDeclarationSyntax)this.Green).eventKeyword, GetChildPosition(2), GetChildIndex(2)); public override VariableDeclarationSyntax Declaration => GetRed(ref this.declaration, 3)!; public override SyntaxToken SemicolonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.EventFieldDeclarationSyntax)this.Green).semicolonToken, GetChildPosition(4), GetChildIndex(4)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 3 => GetRed(ref this.declaration, 3)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 3 => this.declaration, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitEventFieldDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitEventFieldDeclaration(this); public EventFieldDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken eventKeyword, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || eventKeyword != this.EventKeyword || declaration != this.Declaration || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.EventFieldDeclaration(attributeLists, modifiers, eventKeyword, declaration, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new EventFieldDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.EventKeyword, this.Declaration, this.SemicolonToken); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new EventFieldDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.EventKeyword, this.Declaration, this.SemicolonToken); public EventFieldDeclarationSyntax WithEventKeyword(SyntaxToken eventKeyword) => Update(this.AttributeLists, this.Modifiers, eventKeyword, this.Declaration, this.SemicolonToken); internal override BaseFieldDeclarationSyntax WithDeclarationCore(VariableDeclarationSyntax declaration) => WithDeclaration(declaration); public new EventFieldDeclarationSyntax WithDeclaration(VariableDeclarationSyntax declaration) => Update(this.AttributeLists, this.Modifiers, this.EventKeyword, declaration, this.SemicolonToken); internal override BaseFieldDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken) => WithSemicolonToken(semicolonToken); public new EventFieldDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.EventKeyword, this.Declaration, semicolonToken); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new EventFieldDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new EventFieldDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); internal override BaseFieldDeclarationSyntax AddDeclarationVariablesCore(params VariableDeclaratorSyntax[] items) => AddDeclarationVariables(items); public new EventFieldDeclarationSyntax AddDeclarationVariables(params VariableDeclaratorSyntax[] items) => WithDeclaration(this.Declaration.WithVariables(this.Declaration.Variables.AddRange(items))); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ExplicitInterfaceSpecifier"/></description></item> /// </list> /// </remarks> public sealed partial class ExplicitInterfaceSpecifierSyntax : CSharpSyntaxNode { private NameSyntax? name; internal ExplicitInterfaceSpecifierSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public NameSyntax Name => GetRedAtZero(ref this.name)!; public SyntaxToken DotToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ExplicitInterfaceSpecifierSyntax)this.Green).dotToken, GetChildPosition(1), GetChildIndex(1)); internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.name)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.name : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitExplicitInterfaceSpecifier(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitExplicitInterfaceSpecifier(this); public ExplicitInterfaceSpecifierSyntax Update(NameSyntax name, SyntaxToken dotToken) { if (name != this.Name || dotToken != this.DotToken) { var newNode = SyntaxFactory.ExplicitInterfaceSpecifier(name, dotToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ExplicitInterfaceSpecifierSyntax WithName(NameSyntax name) => Update(name, this.DotToken); public ExplicitInterfaceSpecifierSyntax WithDotToken(SyntaxToken dotToken) => Update(this.Name, dotToken); } /// <summary>Base type for method declaration syntax.</summary> public abstract partial class BaseMethodDeclarationSyntax : MemberDeclarationSyntax { internal BaseMethodDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the parameter list.</summary> public abstract ParameterListSyntax ParameterList { get; } public BaseMethodDeclarationSyntax WithParameterList(ParameterListSyntax parameterList) => WithParameterListCore(parameterList); internal abstract BaseMethodDeclarationSyntax WithParameterListCore(ParameterListSyntax parameterList); public BaseMethodDeclarationSyntax AddParameterListParameters(params ParameterSyntax[] items) => AddParameterListParametersCore(items); internal abstract BaseMethodDeclarationSyntax AddParameterListParametersCore(params ParameterSyntax[] items); public abstract BlockSyntax? Body { get; } public BaseMethodDeclarationSyntax WithBody(BlockSyntax? body) => WithBodyCore(body); internal abstract BaseMethodDeclarationSyntax WithBodyCore(BlockSyntax? body); public BaseMethodDeclarationSyntax AddBodyAttributeLists(params AttributeListSyntax[] items) => AddBodyAttributeListsCore(items); internal abstract BaseMethodDeclarationSyntax AddBodyAttributeListsCore(params AttributeListSyntax[] items); public BaseMethodDeclarationSyntax AddBodyStatements(params StatementSyntax[] items) => AddBodyStatementsCore(items); internal abstract BaseMethodDeclarationSyntax AddBodyStatementsCore(params StatementSyntax[] items); public abstract ArrowExpressionClauseSyntax? ExpressionBody { get; } public BaseMethodDeclarationSyntax WithExpressionBody(ArrowExpressionClauseSyntax? expressionBody) => WithExpressionBodyCore(expressionBody); internal abstract BaseMethodDeclarationSyntax WithExpressionBodyCore(ArrowExpressionClauseSyntax? expressionBody); /// <summary>Gets the optional semicolon token.</summary> public abstract SyntaxToken SemicolonToken { get; } public BaseMethodDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => WithSemicolonTokenCore(semicolonToken); internal abstract BaseMethodDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken); public new BaseMethodDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => (BaseMethodDeclarationSyntax)WithAttributeListsCore(attributeLists); public new BaseMethodDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => (BaseMethodDeclarationSyntax)WithModifiersCore(modifiers); public new BaseMethodDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => (BaseMethodDeclarationSyntax)AddAttributeListsCore(items); public new BaseMethodDeclarationSyntax AddModifiers(params SyntaxToken[] items) => (BaseMethodDeclarationSyntax)AddModifiersCore(items); } /// <summary>Method declaration syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.MethodDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class MethodDeclarationSyntax : BaseMethodDeclarationSyntax { private SyntaxNode? attributeLists; private TypeSyntax? returnType; private ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier; private TypeParameterListSyntax? typeParameterList; private ParameterListSyntax? parameterList; private SyntaxNode? constraintClauses; private BlockSyntax? body; private ArrowExpressionClauseSyntax? expressionBody; internal MethodDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } /// <summary>Gets the return type syntax.</summary> public TypeSyntax ReturnType => GetRed(ref this.returnType, 2)!; public ExplicitInterfaceSpecifierSyntax? ExplicitInterfaceSpecifier => GetRed(ref this.explicitInterfaceSpecifier, 3); /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.MethodDeclarationSyntax)this.Green).identifier, GetChildPosition(4), GetChildIndex(4)); public TypeParameterListSyntax? TypeParameterList => GetRed(ref this.typeParameterList, 5); public override ParameterListSyntax ParameterList => GetRed(ref this.parameterList, 6)!; /// <summary>Gets the constraint clause list.</summary> public SyntaxList<TypeParameterConstraintClauseSyntax> ConstraintClauses => new SyntaxList<TypeParameterConstraintClauseSyntax>(GetRed(ref this.constraintClauses, 7)); public override BlockSyntax? Body => GetRed(ref this.body, 8); public override ArrowExpressionClauseSyntax? ExpressionBody => GetRed(ref this.expressionBody, 9); /// <summary>Gets the optional semicolon token.</summary> public override SyntaxToken SemicolonToken { get { var slot = ((Syntax.InternalSyntax.MethodDeclarationSyntax)this.Green).semicolonToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(10), GetChildIndex(10)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.returnType, 2)!, 3 => GetRed(ref this.explicitInterfaceSpecifier, 3), 5 => GetRed(ref this.typeParameterList, 5), 6 => GetRed(ref this.parameterList, 6)!, 7 => GetRed(ref this.constraintClauses, 7)!, 8 => GetRed(ref this.body, 8), 9 => GetRed(ref this.expressionBody, 9), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.returnType, 3 => this.explicitInterfaceSpecifier, 5 => this.typeParameterList, 6 => this.parameterList, 7 => this.constraintClauses, 8 => this.body, 9 => this.expressionBody, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitMethodDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitMethodDeclaration(this); public MethodDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, TypeSyntax returnType, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax parameterList, SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || returnType != this.ReturnType || explicitInterfaceSpecifier != this.ExplicitInterfaceSpecifier || identifier != this.Identifier || typeParameterList != this.TypeParameterList || parameterList != this.ParameterList || constraintClauses != this.ConstraintClauses || body != this.Body || expressionBody != this.ExpressionBody || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.MethodDeclaration(attributeLists, modifiers, returnType, explicitInterfaceSpecifier, identifier, typeParameterList, parameterList, constraintClauses, body, expressionBody, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new MethodDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.ReturnType, this.ExplicitInterfaceSpecifier, this.Identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, this.Body, this.ExpressionBody, this.SemicolonToken); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new MethodDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.ReturnType, this.ExplicitInterfaceSpecifier, this.Identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, this.Body, this.ExpressionBody, this.SemicolonToken); public MethodDeclarationSyntax WithReturnType(TypeSyntax returnType) => Update(this.AttributeLists, this.Modifiers, returnType, this.ExplicitInterfaceSpecifier, this.Identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, this.Body, this.ExpressionBody, this.SemicolonToken); public MethodDeclarationSyntax WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, explicitInterfaceSpecifier, this.Identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, this.Body, this.ExpressionBody, this.SemicolonToken); public MethodDeclarationSyntax WithIdentifier(SyntaxToken identifier) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.ExplicitInterfaceSpecifier, identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, this.Body, this.ExpressionBody, this.SemicolonToken); public MethodDeclarationSyntax WithTypeParameterList(TypeParameterListSyntax? typeParameterList) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.ExplicitInterfaceSpecifier, this.Identifier, typeParameterList, this.ParameterList, this.ConstraintClauses, this.Body, this.ExpressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithParameterListCore(ParameterListSyntax parameterList) => WithParameterList(parameterList); public new MethodDeclarationSyntax WithParameterList(ParameterListSyntax parameterList) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.ExplicitInterfaceSpecifier, this.Identifier, this.TypeParameterList, parameterList, this.ConstraintClauses, this.Body, this.ExpressionBody, this.SemicolonToken); public MethodDeclarationSyntax WithConstraintClauses(SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.ExplicitInterfaceSpecifier, this.Identifier, this.TypeParameterList, this.ParameterList, constraintClauses, this.Body, this.ExpressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithBodyCore(BlockSyntax? body) => WithBody(body); public new MethodDeclarationSyntax WithBody(BlockSyntax? body) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.ExplicitInterfaceSpecifier, this.Identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, body, this.ExpressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithExpressionBodyCore(ArrowExpressionClauseSyntax? expressionBody) => WithExpressionBody(expressionBody); public new MethodDeclarationSyntax WithExpressionBody(ArrowExpressionClauseSyntax? expressionBody) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.ExplicitInterfaceSpecifier, this.Identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, this.Body, expressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken) => WithSemicolonToken(semicolonToken); public new MethodDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.ExplicitInterfaceSpecifier, this.Identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, this.Body, this.ExpressionBody, semicolonToken); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new MethodDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new MethodDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); public MethodDeclarationSyntax AddTypeParameterListParameters(params TypeParameterSyntax[] items) { var typeParameterList = this.TypeParameterList ?? SyntaxFactory.TypeParameterList(); return WithTypeParameterList(typeParameterList.WithParameters(typeParameterList.Parameters.AddRange(items))); } internal override BaseMethodDeclarationSyntax AddParameterListParametersCore(params ParameterSyntax[] items) => AddParameterListParameters(items); public new MethodDeclarationSyntax AddParameterListParameters(params ParameterSyntax[] items) => WithParameterList(this.ParameterList.WithParameters(this.ParameterList.Parameters.AddRange(items))); public MethodDeclarationSyntax AddConstraintClauses(params TypeParameterConstraintClauseSyntax[] items) => WithConstraintClauses(this.ConstraintClauses.AddRange(items)); internal override BaseMethodDeclarationSyntax AddBodyAttributeListsCore(params AttributeListSyntax[] items) => AddBodyAttributeLists(items); public new MethodDeclarationSyntax AddBodyAttributeLists(params AttributeListSyntax[] items) { var body = this.Body ?? SyntaxFactory.Block(); return WithBody(body.WithAttributeLists(body.AttributeLists.AddRange(items))); } internal override BaseMethodDeclarationSyntax AddBodyStatementsCore(params StatementSyntax[] items) => AddBodyStatements(items); public new MethodDeclarationSyntax AddBodyStatements(params StatementSyntax[] items) { var body = this.Body ?? SyntaxFactory.Block(); return WithBody(body.WithStatements(body.Statements.AddRange(items))); } } /// <summary>Operator declaration syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.OperatorDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class OperatorDeclarationSyntax : BaseMethodDeclarationSyntax { private SyntaxNode? attributeLists; private TypeSyntax? returnType; private ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier; private ParameterListSyntax? parameterList; private BlockSyntax? body; private ArrowExpressionClauseSyntax? expressionBody; internal OperatorDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } /// <summary>Gets the return type.</summary> public TypeSyntax ReturnType => GetRed(ref this.returnType, 2)!; public ExplicitInterfaceSpecifierSyntax? ExplicitInterfaceSpecifier => GetRed(ref this.explicitInterfaceSpecifier, 3); /// <summary>Gets the "operator" keyword.</summary> public SyntaxToken OperatorKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.OperatorDeclarationSyntax)this.Green).operatorKeyword, GetChildPosition(4), GetChildIndex(4)); /// <summary>Gets the operator token.</summary> public SyntaxToken OperatorToken => new SyntaxToken(this, ((Syntax.InternalSyntax.OperatorDeclarationSyntax)this.Green).operatorToken, GetChildPosition(5), GetChildIndex(5)); public override ParameterListSyntax ParameterList => GetRed(ref this.parameterList, 6)!; public override BlockSyntax? Body => GetRed(ref this.body, 7); public override ArrowExpressionClauseSyntax? ExpressionBody => GetRed(ref this.expressionBody, 8); /// <summary>Gets the optional semicolon token.</summary> public override SyntaxToken SemicolonToken { get { var slot = ((Syntax.InternalSyntax.OperatorDeclarationSyntax)this.Green).semicolonToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(9), GetChildIndex(9)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.returnType, 2)!, 3 => GetRed(ref this.explicitInterfaceSpecifier, 3), 6 => GetRed(ref this.parameterList, 6)!, 7 => GetRed(ref this.body, 7), 8 => GetRed(ref this.expressionBody, 8), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.returnType, 3 => this.explicitInterfaceSpecifier, 6 => this.parameterList, 7 => this.body, 8 => this.expressionBody, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitOperatorDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitOperatorDeclaration(this); public OperatorDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, TypeSyntax returnType, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken operatorKeyword, SyntaxToken operatorToken, ParameterListSyntax parameterList, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || returnType != this.ReturnType || explicitInterfaceSpecifier != this.ExplicitInterfaceSpecifier || operatorKeyword != this.OperatorKeyword || operatorToken != this.OperatorToken || parameterList != this.ParameterList || body != this.Body || expressionBody != this.ExpressionBody || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.OperatorDeclaration(attributeLists, modifiers, returnType, explicitInterfaceSpecifier, operatorKeyword, operatorToken, parameterList, body, expressionBody, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new OperatorDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.ReturnType, this.ExplicitInterfaceSpecifier, this.OperatorKeyword, this.OperatorToken, this.ParameterList, this.Body, this.ExpressionBody, this.SemicolonToken); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new OperatorDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.ReturnType, this.ExplicitInterfaceSpecifier, this.OperatorKeyword, this.OperatorToken, this.ParameterList, this.Body, this.ExpressionBody, this.SemicolonToken); public OperatorDeclarationSyntax WithReturnType(TypeSyntax returnType) => Update(this.AttributeLists, this.Modifiers, returnType, this.ExplicitInterfaceSpecifier, this.OperatorKeyword, this.OperatorToken, this.ParameterList, this.Body, this.ExpressionBody, this.SemicolonToken); public OperatorDeclarationSyntax WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, explicitInterfaceSpecifier, this.OperatorKeyword, this.OperatorToken, this.ParameterList, this.Body, this.ExpressionBody, this.SemicolonToken); public OperatorDeclarationSyntax WithOperatorKeyword(SyntaxToken operatorKeyword) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.ExplicitInterfaceSpecifier, operatorKeyword, this.OperatorToken, this.ParameterList, this.Body, this.ExpressionBody, this.SemicolonToken); public OperatorDeclarationSyntax WithOperatorToken(SyntaxToken operatorToken) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.ExplicitInterfaceSpecifier, this.OperatorKeyword, operatorToken, this.ParameterList, this.Body, this.ExpressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithParameterListCore(ParameterListSyntax parameterList) => WithParameterList(parameterList); public new OperatorDeclarationSyntax WithParameterList(ParameterListSyntax parameterList) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.ExplicitInterfaceSpecifier, this.OperatorKeyword, this.OperatorToken, parameterList, this.Body, this.ExpressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithBodyCore(BlockSyntax? body) => WithBody(body); public new OperatorDeclarationSyntax WithBody(BlockSyntax? body) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.ExplicitInterfaceSpecifier, this.OperatorKeyword, this.OperatorToken, this.ParameterList, body, this.ExpressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithExpressionBodyCore(ArrowExpressionClauseSyntax? expressionBody) => WithExpressionBody(expressionBody); public new OperatorDeclarationSyntax WithExpressionBody(ArrowExpressionClauseSyntax? expressionBody) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.ExplicitInterfaceSpecifier, this.OperatorKeyword, this.OperatorToken, this.ParameterList, this.Body, expressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken) => WithSemicolonToken(semicolonToken); public new OperatorDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.ExplicitInterfaceSpecifier, this.OperatorKeyword, this.OperatorToken, this.ParameterList, this.Body, this.ExpressionBody, semicolonToken); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new OperatorDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new OperatorDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); internal override BaseMethodDeclarationSyntax AddParameterListParametersCore(params ParameterSyntax[] items) => AddParameterListParameters(items); public new OperatorDeclarationSyntax AddParameterListParameters(params ParameterSyntax[] items) => WithParameterList(this.ParameterList.WithParameters(this.ParameterList.Parameters.AddRange(items))); internal override BaseMethodDeclarationSyntax AddBodyAttributeListsCore(params AttributeListSyntax[] items) => AddBodyAttributeLists(items); public new OperatorDeclarationSyntax AddBodyAttributeLists(params AttributeListSyntax[] items) { var body = this.Body ?? SyntaxFactory.Block(); return WithBody(body.WithAttributeLists(body.AttributeLists.AddRange(items))); } internal override BaseMethodDeclarationSyntax AddBodyStatementsCore(params StatementSyntax[] items) => AddBodyStatements(items); public new OperatorDeclarationSyntax AddBodyStatements(params StatementSyntax[] items) { var body = this.Body ?? SyntaxFactory.Block(); return WithBody(body.WithStatements(body.Statements.AddRange(items))); } } /// <summary>Conversion operator declaration syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ConversionOperatorDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class ConversionOperatorDeclarationSyntax : BaseMethodDeclarationSyntax { private SyntaxNode? attributeLists; private ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier; private TypeSyntax? type; private ParameterListSyntax? parameterList; private BlockSyntax? body; private ArrowExpressionClauseSyntax? expressionBody; internal ConversionOperatorDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } /// <summary>Gets the "implicit" or "explicit" token.</summary> public SyntaxToken ImplicitOrExplicitKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ConversionOperatorDeclarationSyntax)this.Green).implicitOrExplicitKeyword, GetChildPosition(2), GetChildIndex(2)); public ExplicitInterfaceSpecifierSyntax? ExplicitInterfaceSpecifier => GetRed(ref this.explicitInterfaceSpecifier, 3); /// <summary>Gets the "operator" token.</summary> public SyntaxToken OperatorKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ConversionOperatorDeclarationSyntax)this.Green).operatorKeyword, GetChildPosition(4), GetChildIndex(4)); /// <summary>Gets the type.</summary> public TypeSyntax Type => GetRed(ref this.type, 5)!; public override ParameterListSyntax ParameterList => GetRed(ref this.parameterList, 6)!; public override BlockSyntax? Body => GetRed(ref this.body, 7); public override ArrowExpressionClauseSyntax? ExpressionBody => GetRed(ref this.expressionBody, 8); /// <summary>Gets the optional semicolon token.</summary> public override SyntaxToken SemicolonToken { get { var slot = ((Syntax.InternalSyntax.ConversionOperatorDeclarationSyntax)this.Green).semicolonToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(9), GetChildIndex(9)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 3 => GetRed(ref this.explicitInterfaceSpecifier, 3), 5 => GetRed(ref this.type, 5)!, 6 => GetRed(ref this.parameterList, 6)!, 7 => GetRed(ref this.body, 7), 8 => GetRed(ref this.expressionBody, 8), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 3 => this.explicitInterfaceSpecifier, 5 => this.type, 6 => this.parameterList, 7 => this.body, 8 => this.expressionBody, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitConversionOperatorDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitConversionOperatorDeclaration(this); public ConversionOperatorDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken implicitOrExplicitKeyword, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken operatorKeyword, TypeSyntax type, ParameterListSyntax parameterList, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || implicitOrExplicitKeyword != this.ImplicitOrExplicitKeyword || explicitInterfaceSpecifier != this.ExplicitInterfaceSpecifier || operatorKeyword != this.OperatorKeyword || type != this.Type || parameterList != this.ParameterList || body != this.Body || expressionBody != this.ExpressionBody || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.ConversionOperatorDeclaration(attributeLists, modifiers, implicitOrExplicitKeyword, explicitInterfaceSpecifier, operatorKeyword, type, parameterList, body, expressionBody, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new ConversionOperatorDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.ImplicitOrExplicitKeyword, this.ExplicitInterfaceSpecifier, this.OperatorKeyword, this.Type, this.ParameterList, this.Body, this.ExpressionBody, this.SemicolonToken); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new ConversionOperatorDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.ImplicitOrExplicitKeyword, this.ExplicitInterfaceSpecifier, this.OperatorKeyword, this.Type, this.ParameterList, this.Body, this.ExpressionBody, this.SemicolonToken); public ConversionOperatorDeclarationSyntax WithImplicitOrExplicitKeyword(SyntaxToken implicitOrExplicitKeyword) => Update(this.AttributeLists, this.Modifiers, implicitOrExplicitKeyword, this.ExplicitInterfaceSpecifier, this.OperatorKeyword, this.Type, this.ParameterList, this.Body, this.ExpressionBody, this.SemicolonToken); public ConversionOperatorDeclarationSyntax WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier) => Update(this.AttributeLists, this.Modifiers, this.ImplicitOrExplicitKeyword, explicitInterfaceSpecifier, this.OperatorKeyword, this.Type, this.ParameterList, this.Body, this.ExpressionBody, this.SemicolonToken); public ConversionOperatorDeclarationSyntax WithOperatorKeyword(SyntaxToken operatorKeyword) => Update(this.AttributeLists, this.Modifiers, this.ImplicitOrExplicitKeyword, this.ExplicitInterfaceSpecifier, operatorKeyword, this.Type, this.ParameterList, this.Body, this.ExpressionBody, this.SemicolonToken); public ConversionOperatorDeclarationSyntax WithType(TypeSyntax type) => Update(this.AttributeLists, this.Modifiers, this.ImplicitOrExplicitKeyword, this.ExplicitInterfaceSpecifier, this.OperatorKeyword, type, this.ParameterList, this.Body, this.ExpressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithParameterListCore(ParameterListSyntax parameterList) => WithParameterList(parameterList); public new ConversionOperatorDeclarationSyntax WithParameterList(ParameterListSyntax parameterList) => Update(this.AttributeLists, this.Modifiers, this.ImplicitOrExplicitKeyword, this.ExplicitInterfaceSpecifier, this.OperatorKeyword, this.Type, parameterList, this.Body, this.ExpressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithBodyCore(BlockSyntax? body) => WithBody(body); public new ConversionOperatorDeclarationSyntax WithBody(BlockSyntax? body) => Update(this.AttributeLists, this.Modifiers, this.ImplicitOrExplicitKeyword, this.ExplicitInterfaceSpecifier, this.OperatorKeyword, this.Type, this.ParameterList, body, this.ExpressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithExpressionBodyCore(ArrowExpressionClauseSyntax? expressionBody) => WithExpressionBody(expressionBody); public new ConversionOperatorDeclarationSyntax WithExpressionBody(ArrowExpressionClauseSyntax? expressionBody) => Update(this.AttributeLists, this.Modifiers, this.ImplicitOrExplicitKeyword, this.ExplicitInterfaceSpecifier, this.OperatorKeyword, this.Type, this.ParameterList, this.Body, expressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken) => WithSemicolonToken(semicolonToken); public new ConversionOperatorDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.ImplicitOrExplicitKeyword, this.ExplicitInterfaceSpecifier, this.OperatorKeyword, this.Type, this.ParameterList, this.Body, this.ExpressionBody, semicolonToken); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new ConversionOperatorDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new ConversionOperatorDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); internal override BaseMethodDeclarationSyntax AddParameterListParametersCore(params ParameterSyntax[] items) => AddParameterListParameters(items); public new ConversionOperatorDeclarationSyntax AddParameterListParameters(params ParameterSyntax[] items) => WithParameterList(this.ParameterList.WithParameters(this.ParameterList.Parameters.AddRange(items))); internal override BaseMethodDeclarationSyntax AddBodyAttributeListsCore(params AttributeListSyntax[] items) => AddBodyAttributeLists(items); public new ConversionOperatorDeclarationSyntax AddBodyAttributeLists(params AttributeListSyntax[] items) { var body = this.Body ?? SyntaxFactory.Block(); return WithBody(body.WithAttributeLists(body.AttributeLists.AddRange(items))); } internal override BaseMethodDeclarationSyntax AddBodyStatementsCore(params StatementSyntax[] items) => AddBodyStatements(items); public new ConversionOperatorDeclarationSyntax AddBodyStatements(params StatementSyntax[] items) { var body = this.Body ?? SyntaxFactory.Block(); return WithBody(body.WithStatements(body.Statements.AddRange(items))); } } /// <summary>Constructor declaration syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ConstructorDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class ConstructorDeclarationSyntax : BaseMethodDeclarationSyntax { private SyntaxNode? attributeLists; private ParameterListSyntax? parameterList; private ConstructorInitializerSyntax? initializer; private BlockSyntax? body; private ArrowExpressionClauseSyntax? expressionBody; internal ConstructorDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.ConstructorDeclarationSyntax)this.Green).identifier, GetChildPosition(2), GetChildIndex(2)); public override ParameterListSyntax ParameterList => GetRed(ref this.parameterList, 3)!; public ConstructorInitializerSyntax? Initializer => GetRed(ref this.initializer, 4); public override BlockSyntax? Body => GetRed(ref this.body, 5); public override ArrowExpressionClauseSyntax? ExpressionBody => GetRed(ref this.expressionBody, 6); /// <summary>Gets the optional semicolon token.</summary> public override SyntaxToken SemicolonToken { get { var slot = ((Syntax.InternalSyntax.ConstructorDeclarationSyntax)this.Green).semicolonToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(7), GetChildIndex(7)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 3 => GetRed(ref this.parameterList, 3)!, 4 => GetRed(ref this.initializer, 4), 5 => GetRed(ref this.body, 5), 6 => GetRed(ref this.expressionBody, 6), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 3 => this.parameterList, 4 => this.initializer, 5 => this.body, 6 => this.expressionBody, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitConstructorDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitConstructorDeclaration(this); public ConstructorDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken identifier, ParameterListSyntax parameterList, ConstructorInitializerSyntax? initializer, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || identifier != this.Identifier || parameterList != this.ParameterList || initializer != this.Initializer || body != this.Body || expressionBody != this.ExpressionBody || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.ConstructorDeclaration(attributeLists, modifiers, identifier, parameterList, initializer, body, expressionBody, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new ConstructorDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.Identifier, this.ParameterList, this.Initializer, this.Body, this.ExpressionBody, this.SemicolonToken); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new ConstructorDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.Identifier, this.ParameterList, this.Initializer, this.Body, this.ExpressionBody, this.SemicolonToken); public ConstructorDeclarationSyntax WithIdentifier(SyntaxToken identifier) => Update(this.AttributeLists, this.Modifiers, identifier, this.ParameterList, this.Initializer, this.Body, this.ExpressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithParameterListCore(ParameterListSyntax parameterList) => WithParameterList(parameterList); public new ConstructorDeclarationSyntax WithParameterList(ParameterListSyntax parameterList) => Update(this.AttributeLists, this.Modifiers, this.Identifier, parameterList, this.Initializer, this.Body, this.ExpressionBody, this.SemicolonToken); public ConstructorDeclarationSyntax WithInitializer(ConstructorInitializerSyntax? initializer) => Update(this.AttributeLists, this.Modifiers, this.Identifier, this.ParameterList, initializer, this.Body, this.ExpressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithBodyCore(BlockSyntax? body) => WithBody(body); public new ConstructorDeclarationSyntax WithBody(BlockSyntax? body) => Update(this.AttributeLists, this.Modifiers, this.Identifier, this.ParameterList, this.Initializer, body, this.ExpressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithExpressionBodyCore(ArrowExpressionClauseSyntax? expressionBody) => WithExpressionBody(expressionBody); public new ConstructorDeclarationSyntax WithExpressionBody(ArrowExpressionClauseSyntax? expressionBody) => Update(this.AttributeLists, this.Modifiers, this.Identifier, this.ParameterList, this.Initializer, this.Body, expressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken) => WithSemicolonToken(semicolonToken); public new ConstructorDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.Identifier, this.ParameterList, this.Initializer, this.Body, this.ExpressionBody, semicolonToken); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new ConstructorDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new ConstructorDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); internal override BaseMethodDeclarationSyntax AddParameterListParametersCore(params ParameterSyntax[] items) => AddParameterListParameters(items); public new ConstructorDeclarationSyntax AddParameterListParameters(params ParameterSyntax[] items) => WithParameterList(this.ParameterList.WithParameters(this.ParameterList.Parameters.AddRange(items))); internal override BaseMethodDeclarationSyntax AddBodyAttributeListsCore(params AttributeListSyntax[] items) => AddBodyAttributeLists(items); public new ConstructorDeclarationSyntax AddBodyAttributeLists(params AttributeListSyntax[] items) { var body = this.Body ?? SyntaxFactory.Block(); return WithBody(body.WithAttributeLists(body.AttributeLists.AddRange(items))); } internal override BaseMethodDeclarationSyntax AddBodyStatementsCore(params StatementSyntax[] items) => AddBodyStatements(items); public new ConstructorDeclarationSyntax AddBodyStatements(params StatementSyntax[] items) { var body = this.Body ?? SyntaxFactory.Block(); return WithBody(body.WithStatements(body.Statements.AddRange(items))); } } /// <summary>Constructor initializer syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.BaseConstructorInitializer"/></description></item> /// <item><description><see cref="SyntaxKind.ThisConstructorInitializer"/></description></item> /// </list> /// </remarks> public sealed partial class ConstructorInitializerSyntax : CSharpSyntaxNode { private ArgumentListSyntax? argumentList; internal ConstructorInitializerSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the colon token.</summary> public SyntaxToken ColonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ConstructorInitializerSyntax)this.Green).colonToken, Position, 0); /// <summary>Gets the "this" or "base" keyword.</summary> public SyntaxToken ThisOrBaseKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ConstructorInitializerSyntax)this.Green).thisOrBaseKeyword, GetChildPosition(1), GetChildIndex(1)); public ArgumentListSyntax ArgumentList => GetRed(ref this.argumentList, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 2 ? GetRed(ref this.argumentList, 2)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 2 ? this.argumentList : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitConstructorInitializer(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitConstructorInitializer(this); public ConstructorInitializerSyntax Update(SyntaxToken colonToken, SyntaxToken thisOrBaseKeyword, ArgumentListSyntax argumentList) { if (colonToken != this.ColonToken || thisOrBaseKeyword != this.ThisOrBaseKeyword || argumentList != this.ArgumentList) { var newNode = SyntaxFactory.ConstructorInitializer(this.Kind(), colonToken, thisOrBaseKeyword, argumentList); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ConstructorInitializerSyntax WithColonToken(SyntaxToken colonToken) => Update(colonToken, this.ThisOrBaseKeyword, this.ArgumentList); public ConstructorInitializerSyntax WithThisOrBaseKeyword(SyntaxToken thisOrBaseKeyword) => Update(this.ColonToken, thisOrBaseKeyword, this.ArgumentList); public ConstructorInitializerSyntax WithArgumentList(ArgumentListSyntax argumentList) => Update(this.ColonToken, this.ThisOrBaseKeyword, argumentList); public ConstructorInitializerSyntax AddArgumentListArguments(params ArgumentSyntax[] items) => WithArgumentList(this.ArgumentList.WithArguments(this.ArgumentList.Arguments.AddRange(items))); } /// <summary>Destructor declaration syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.DestructorDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class DestructorDeclarationSyntax : BaseMethodDeclarationSyntax { private SyntaxNode? attributeLists; private ParameterListSyntax? parameterList; private BlockSyntax? body; private ArrowExpressionClauseSyntax? expressionBody; internal DestructorDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } /// <summary>Gets the tilde token.</summary> public SyntaxToken TildeToken => new SyntaxToken(this, ((Syntax.InternalSyntax.DestructorDeclarationSyntax)this.Green).tildeToken, GetChildPosition(2), GetChildIndex(2)); /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.DestructorDeclarationSyntax)this.Green).identifier, GetChildPosition(3), GetChildIndex(3)); public override ParameterListSyntax ParameterList => GetRed(ref this.parameterList, 4)!; public override BlockSyntax? Body => GetRed(ref this.body, 5); public override ArrowExpressionClauseSyntax? ExpressionBody => GetRed(ref this.expressionBody, 6); /// <summary>Gets the optional semicolon token.</summary> public override SyntaxToken SemicolonToken { get { var slot = ((Syntax.InternalSyntax.DestructorDeclarationSyntax)this.Green).semicolonToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(7), GetChildIndex(7)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 4 => GetRed(ref this.parameterList, 4)!, 5 => GetRed(ref this.body, 5), 6 => GetRed(ref this.expressionBody, 6), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 4 => this.parameterList, 5 => this.body, 6 => this.expressionBody, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitDestructorDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitDestructorDeclaration(this); public DestructorDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken tildeToken, SyntaxToken identifier, ParameterListSyntax parameterList, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || tildeToken != this.TildeToken || identifier != this.Identifier || parameterList != this.ParameterList || body != this.Body || expressionBody != this.ExpressionBody || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.DestructorDeclaration(attributeLists, modifiers, tildeToken, identifier, parameterList, body, expressionBody, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new DestructorDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.TildeToken, this.Identifier, this.ParameterList, this.Body, this.ExpressionBody, this.SemicolonToken); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new DestructorDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.TildeToken, this.Identifier, this.ParameterList, this.Body, this.ExpressionBody, this.SemicolonToken); public DestructorDeclarationSyntax WithTildeToken(SyntaxToken tildeToken) => Update(this.AttributeLists, this.Modifiers, tildeToken, this.Identifier, this.ParameterList, this.Body, this.ExpressionBody, this.SemicolonToken); public DestructorDeclarationSyntax WithIdentifier(SyntaxToken identifier) => Update(this.AttributeLists, this.Modifiers, this.TildeToken, identifier, this.ParameterList, this.Body, this.ExpressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithParameterListCore(ParameterListSyntax parameterList) => WithParameterList(parameterList); public new DestructorDeclarationSyntax WithParameterList(ParameterListSyntax parameterList) => Update(this.AttributeLists, this.Modifiers, this.TildeToken, this.Identifier, parameterList, this.Body, this.ExpressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithBodyCore(BlockSyntax? body) => WithBody(body); public new DestructorDeclarationSyntax WithBody(BlockSyntax? body) => Update(this.AttributeLists, this.Modifiers, this.TildeToken, this.Identifier, this.ParameterList, body, this.ExpressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithExpressionBodyCore(ArrowExpressionClauseSyntax? expressionBody) => WithExpressionBody(expressionBody); public new DestructorDeclarationSyntax WithExpressionBody(ArrowExpressionClauseSyntax? expressionBody) => Update(this.AttributeLists, this.Modifiers, this.TildeToken, this.Identifier, this.ParameterList, this.Body, expressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken) => WithSemicolonToken(semicolonToken); public new DestructorDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.TildeToken, this.Identifier, this.ParameterList, this.Body, this.ExpressionBody, semicolonToken); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new DestructorDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new DestructorDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); internal override BaseMethodDeclarationSyntax AddParameterListParametersCore(params ParameterSyntax[] items) => AddParameterListParameters(items); public new DestructorDeclarationSyntax AddParameterListParameters(params ParameterSyntax[] items) => WithParameterList(this.ParameterList.WithParameters(this.ParameterList.Parameters.AddRange(items))); internal override BaseMethodDeclarationSyntax AddBodyAttributeListsCore(params AttributeListSyntax[] items) => AddBodyAttributeLists(items); public new DestructorDeclarationSyntax AddBodyAttributeLists(params AttributeListSyntax[] items) { var body = this.Body ?? SyntaxFactory.Block(); return WithBody(body.WithAttributeLists(body.AttributeLists.AddRange(items))); } internal override BaseMethodDeclarationSyntax AddBodyStatementsCore(params StatementSyntax[] items) => AddBodyStatements(items); public new DestructorDeclarationSyntax AddBodyStatements(params StatementSyntax[] items) { var body = this.Body ?? SyntaxFactory.Block(); return WithBody(body.WithStatements(body.Statements.AddRange(items))); } } /// <summary>Base type for property declaration syntax.</summary> public abstract partial class BasePropertyDeclarationSyntax : MemberDeclarationSyntax { internal BasePropertyDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the type syntax.</summary> public abstract TypeSyntax Type { get; } public BasePropertyDeclarationSyntax WithType(TypeSyntax type) => WithTypeCore(type); internal abstract BasePropertyDeclarationSyntax WithTypeCore(TypeSyntax type); /// <summary>Gets the optional explicit interface specifier.</summary> public abstract ExplicitInterfaceSpecifierSyntax? ExplicitInterfaceSpecifier { get; } public BasePropertyDeclarationSyntax WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier) => WithExplicitInterfaceSpecifierCore(explicitInterfaceSpecifier); internal abstract BasePropertyDeclarationSyntax WithExplicitInterfaceSpecifierCore(ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier); public abstract AccessorListSyntax? AccessorList { get; } public BasePropertyDeclarationSyntax WithAccessorList(AccessorListSyntax? accessorList) => WithAccessorListCore(accessorList); internal abstract BasePropertyDeclarationSyntax WithAccessorListCore(AccessorListSyntax? accessorList); public BasePropertyDeclarationSyntax AddAccessorListAccessors(params AccessorDeclarationSyntax[] items) => AddAccessorListAccessorsCore(items); internal abstract BasePropertyDeclarationSyntax AddAccessorListAccessorsCore(params AccessorDeclarationSyntax[] items); public new BasePropertyDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => (BasePropertyDeclarationSyntax)WithAttributeListsCore(attributeLists); public new BasePropertyDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => (BasePropertyDeclarationSyntax)WithModifiersCore(modifiers); public new BasePropertyDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => (BasePropertyDeclarationSyntax)AddAttributeListsCore(items); public new BasePropertyDeclarationSyntax AddModifiers(params SyntaxToken[] items) => (BasePropertyDeclarationSyntax)AddModifiersCore(items); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.PropertyDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class PropertyDeclarationSyntax : BasePropertyDeclarationSyntax { private SyntaxNode? attributeLists; private TypeSyntax? type; private ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier; private AccessorListSyntax? accessorList; private ArrowExpressionClauseSyntax? expressionBody; private EqualsValueClauseSyntax? initializer; internal PropertyDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public override TypeSyntax Type => GetRed(ref this.type, 2)!; public override ExplicitInterfaceSpecifierSyntax? ExplicitInterfaceSpecifier => GetRed(ref this.explicitInterfaceSpecifier, 3); /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.PropertyDeclarationSyntax)this.Green).identifier, GetChildPosition(4), GetChildIndex(4)); public override AccessorListSyntax? AccessorList => GetRed(ref this.accessorList, 5); public ArrowExpressionClauseSyntax? ExpressionBody => GetRed(ref this.expressionBody, 6); public EqualsValueClauseSyntax? Initializer => GetRed(ref this.initializer, 7); public SyntaxToken SemicolonToken { get { var slot = ((Syntax.InternalSyntax.PropertyDeclarationSyntax)this.Green).semicolonToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(8), GetChildIndex(8)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.type, 2)!, 3 => GetRed(ref this.explicitInterfaceSpecifier, 3), 5 => GetRed(ref this.accessorList, 5), 6 => GetRed(ref this.expressionBody, 6), 7 => GetRed(ref this.initializer, 7), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.type, 3 => this.explicitInterfaceSpecifier, 5 => this.accessorList, 6 => this.expressionBody, 7 => this.initializer, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitPropertyDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitPropertyDeclaration(this); public PropertyDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken identifier, AccessorListSyntax? accessorList, ArrowExpressionClauseSyntax? expressionBody, EqualsValueClauseSyntax? initializer, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || type != this.Type || explicitInterfaceSpecifier != this.ExplicitInterfaceSpecifier || identifier != this.Identifier || accessorList != this.AccessorList || expressionBody != this.ExpressionBody || initializer != this.Initializer || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.PropertyDeclaration(attributeLists, modifiers, type, explicitInterfaceSpecifier, identifier, accessorList, expressionBody, initializer, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new PropertyDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.Type, this.ExplicitInterfaceSpecifier, this.Identifier, this.AccessorList, this.ExpressionBody, this.Initializer, this.SemicolonToken); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new PropertyDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.Type, this.ExplicitInterfaceSpecifier, this.Identifier, this.AccessorList, this.ExpressionBody, this.Initializer, this.SemicolonToken); internal override BasePropertyDeclarationSyntax WithTypeCore(TypeSyntax type) => WithType(type); public new PropertyDeclarationSyntax WithType(TypeSyntax type) => Update(this.AttributeLists, this.Modifiers, type, this.ExplicitInterfaceSpecifier, this.Identifier, this.AccessorList, this.ExpressionBody, this.Initializer, this.SemicolonToken); internal override BasePropertyDeclarationSyntax WithExplicitInterfaceSpecifierCore(ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier) => WithExplicitInterfaceSpecifier(explicitInterfaceSpecifier); public new PropertyDeclarationSyntax WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier) => Update(this.AttributeLists, this.Modifiers, this.Type, explicitInterfaceSpecifier, this.Identifier, this.AccessorList, this.ExpressionBody, this.Initializer, this.SemicolonToken); public PropertyDeclarationSyntax WithIdentifier(SyntaxToken identifier) => Update(this.AttributeLists, this.Modifiers, this.Type, this.ExplicitInterfaceSpecifier, identifier, this.AccessorList, this.ExpressionBody, this.Initializer, this.SemicolonToken); internal override BasePropertyDeclarationSyntax WithAccessorListCore(AccessorListSyntax? accessorList) => WithAccessorList(accessorList); public new PropertyDeclarationSyntax WithAccessorList(AccessorListSyntax? accessorList) => Update(this.AttributeLists, this.Modifiers, this.Type, this.ExplicitInterfaceSpecifier, this.Identifier, accessorList, this.ExpressionBody, this.Initializer, this.SemicolonToken); public PropertyDeclarationSyntax WithExpressionBody(ArrowExpressionClauseSyntax? expressionBody) => Update(this.AttributeLists, this.Modifiers, this.Type, this.ExplicitInterfaceSpecifier, this.Identifier, this.AccessorList, expressionBody, this.Initializer, this.SemicolonToken); public PropertyDeclarationSyntax WithInitializer(EqualsValueClauseSyntax? initializer) => Update(this.AttributeLists, this.Modifiers, this.Type, this.ExplicitInterfaceSpecifier, this.Identifier, this.AccessorList, this.ExpressionBody, initializer, this.SemicolonToken); public PropertyDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.Type, this.ExplicitInterfaceSpecifier, this.Identifier, this.AccessorList, this.ExpressionBody, this.Initializer, semicolonToken); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new PropertyDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new PropertyDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); internal override BasePropertyDeclarationSyntax AddAccessorListAccessorsCore(params AccessorDeclarationSyntax[] items) => AddAccessorListAccessors(items); public new PropertyDeclarationSyntax AddAccessorListAccessors(params AccessorDeclarationSyntax[] items) { var accessorList = this.AccessorList ?? SyntaxFactory.AccessorList(); return WithAccessorList(accessorList.WithAccessors(accessorList.Accessors.AddRange(items))); } } /// <summary>The syntax for the expression body of an expression-bodied member.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ArrowExpressionClause"/></description></item> /// </list> /// </remarks> public sealed partial class ArrowExpressionClauseSyntax : CSharpSyntaxNode { private ExpressionSyntax? expression; internal ArrowExpressionClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken ArrowToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ArrowExpressionClauseSyntax)this.Green).arrowToken, Position, 0); public ExpressionSyntax Expression => GetRed(ref this.expression, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.expression, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.expression : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitArrowExpressionClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitArrowExpressionClause(this); public ArrowExpressionClauseSyntax Update(SyntaxToken arrowToken, ExpressionSyntax expression) { if (arrowToken != this.ArrowToken || expression != this.Expression) { var newNode = SyntaxFactory.ArrowExpressionClause(arrowToken, expression); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ArrowExpressionClauseSyntax WithArrowToken(SyntaxToken arrowToken) => Update(arrowToken, this.Expression); public ArrowExpressionClauseSyntax WithExpression(ExpressionSyntax expression) => Update(this.ArrowToken, expression); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.EventDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class EventDeclarationSyntax : BasePropertyDeclarationSyntax { private SyntaxNode? attributeLists; private TypeSyntax? type; private ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier; private AccessorListSyntax? accessorList; internal EventDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public SyntaxToken EventKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.EventDeclarationSyntax)this.Green).eventKeyword, GetChildPosition(2), GetChildIndex(2)); public override TypeSyntax Type => GetRed(ref this.type, 3)!; public override ExplicitInterfaceSpecifierSyntax? ExplicitInterfaceSpecifier => GetRed(ref this.explicitInterfaceSpecifier, 4); /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.EventDeclarationSyntax)this.Green).identifier, GetChildPosition(5), GetChildIndex(5)); public override AccessorListSyntax? AccessorList => GetRed(ref this.accessorList, 6); public SyntaxToken SemicolonToken { get { var slot = ((Syntax.InternalSyntax.EventDeclarationSyntax)this.Green).semicolonToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(7), GetChildIndex(7)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 3 => GetRed(ref this.type, 3)!, 4 => GetRed(ref this.explicitInterfaceSpecifier, 4), 6 => GetRed(ref this.accessorList, 6), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 3 => this.type, 4 => this.explicitInterfaceSpecifier, 6 => this.accessorList, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitEventDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitEventDeclaration(this); public EventDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken eventKeyword, TypeSyntax type, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken identifier, AccessorListSyntax? accessorList, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || eventKeyword != this.EventKeyword || type != this.Type || explicitInterfaceSpecifier != this.ExplicitInterfaceSpecifier || identifier != this.Identifier || accessorList != this.AccessorList || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.EventDeclaration(attributeLists, modifiers, eventKeyword, type, explicitInterfaceSpecifier, identifier, accessorList, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new EventDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.EventKeyword, this.Type, this.ExplicitInterfaceSpecifier, this.Identifier, this.AccessorList, this.SemicolonToken); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new EventDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.EventKeyword, this.Type, this.ExplicitInterfaceSpecifier, this.Identifier, this.AccessorList, this.SemicolonToken); public EventDeclarationSyntax WithEventKeyword(SyntaxToken eventKeyword) => Update(this.AttributeLists, this.Modifiers, eventKeyword, this.Type, this.ExplicitInterfaceSpecifier, this.Identifier, this.AccessorList, this.SemicolonToken); internal override BasePropertyDeclarationSyntax WithTypeCore(TypeSyntax type) => WithType(type); public new EventDeclarationSyntax WithType(TypeSyntax type) => Update(this.AttributeLists, this.Modifiers, this.EventKeyword, type, this.ExplicitInterfaceSpecifier, this.Identifier, this.AccessorList, this.SemicolonToken); internal override BasePropertyDeclarationSyntax WithExplicitInterfaceSpecifierCore(ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier) => WithExplicitInterfaceSpecifier(explicitInterfaceSpecifier); public new EventDeclarationSyntax WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier) => Update(this.AttributeLists, this.Modifiers, this.EventKeyword, this.Type, explicitInterfaceSpecifier, this.Identifier, this.AccessorList, this.SemicolonToken); public EventDeclarationSyntax WithIdentifier(SyntaxToken identifier) => Update(this.AttributeLists, this.Modifiers, this.EventKeyword, this.Type, this.ExplicitInterfaceSpecifier, identifier, this.AccessorList, this.SemicolonToken); internal override BasePropertyDeclarationSyntax WithAccessorListCore(AccessorListSyntax? accessorList) => WithAccessorList(accessorList); public new EventDeclarationSyntax WithAccessorList(AccessorListSyntax? accessorList) => Update(this.AttributeLists, this.Modifiers, this.EventKeyword, this.Type, this.ExplicitInterfaceSpecifier, this.Identifier, accessorList, this.SemicolonToken); public EventDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.EventKeyword, this.Type, this.ExplicitInterfaceSpecifier, this.Identifier, this.AccessorList, semicolonToken); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new EventDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new EventDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); internal override BasePropertyDeclarationSyntax AddAccessorListAccessorsCore(params AccessorDeclarationSyntax[] items) => AddAccessorListAccessors(items); public new EventDeclarationSyntax AddAccessorListAccessors(params AccessorDeclarationSyntax[] items) { var accessorList = this.AccessorList ?? SyntaxFactory.AccessorList(); return WithAccessorList(accessorList.WithAccessors(accessorList.Accessors.AddRange(items))); } } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.IndexerDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class IndexerDeclarationSyntax : BasePropertyDeclarationSyntax { private SyntaxNode? attributeLists; private TypeSyntax? type; private ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier; private BracketedParameterListSyntax? parameterList; private AccessorListSyntax? accessorList; private ArrowExpressionClauseSyntax? expressionBody; internal IndexerDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public override TypeSyntax Type => GetRed(ref this.type, 2)!; public override ExplicitInterfaceSpecifierSyntax? ExplicitInterfaceSpecifier => GetRed(ref this.explicitInterfaceSpecifier, 3); public SyntaxToken ThisKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.IndexerDeclarationSyntax)this.Green).thisKeyword, GetChildPosition(4), GetChildIndex(4)); /// <summary>Gets the parameter list.</summary> public BracketedParameterListSyntax ParameterList => GetRed(ref this.parameterList, 5)!; public override AccessorListSyntax? AccessorList => GetRed(ref this.accessorList, 6); public ArrowExpressionClauseSyntax? ExpressionBody => GetRed(ref this.expressionBody, 7); public SyntaxToken SemicolonToken { get { var slot = ((Syntax.InternalSyntax.IndexerDeclarationSyntax)this.Green).semicolonToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(8), GetChildIndex(8)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.type, 2)!, 3 => GetRed(ref this.explicitInterfaceSpecifier, 3), 5 => GetRed(ref this.parameterList, 5)!, 6 => GetRed(ref this.accessorList, 6), 7 => GetRed(ref this.expressionBody, 7), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.type, 3 => this.explicitInterfaceSpecifier, 5 => this.parameterList, 6 => this.accessorList, 7 => this.expressionBody, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitIndexerDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitIndexerDeclaration(this); public IndexerDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken thisKeyword, BracketedParameterListSyntax parameterList, AccessorListSyntax? accessorList, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || type != this.Type || explicitInterfaceSpecifier != this.ExplicitInterfaceSpecifier || thisKeyword != this.ThisKeyword || parameterList != this.ParameterList || accessorList != this.AccessorList || expressionBody != this.ExpressionBody || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.IndexerDeclaration(attributeLists, modifiers, type, explicitInterfaceSpecifier, thisKeyword, parameterList, accessorList, expressionBody, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new IndexerDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.Type, this.ExplicitInterfaceSpecifier, this.ThisKeyword, this.ParameterList, this.AccessorList, this.ExpressionBody, this.SemicolonToken); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new IndexerDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.Type, this.ExplicitInterfaceSpecifier, this.ThisKeyword, this.ParameterList, this.AccessorList, this.ExpressionBody, this.SemicolonToken); internal override BasePropertyDeclarationSyntax WithTypeCore(TypeSyntax type) => WithType(type); public new IndexerDeclarationSyntax WithType(TypeSyntax type) => Update(this.AttributeLists, this.Modifiers, type, this.ExplicitInterfaceSpecifier, this.ThisKeyword, this.ParameterList, this.AccessorList, this.ExpressionBody, this.SemicolonToken); internal override BasePropertyDeclarationSyntax WithExplicitInterfaceSpecifierCore(ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier) => WithExplicitInterfaceSpecifier(explicitInterfaceSpecifier); public new IndexerDeclarationSyntax WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier) => Update(this.AttributeLists, this.Modifiers, this.Type, explicitInterfaceSpecifier, this.ThisKeyword, this.ParameterList, this.AccessorList, this.ExpressionBody, this.SemicolonToken); public IndexerDeclarationSyntax WithThisKeyword(SyntaxToken thisKeyword) => Update(this.AttributeLists, this.Modifiers, this.Type, this.ExplicitInterfaceSpecifier, thisKeyword, this.ParameterList, this.AccessorList, this.ExpressionBody, this.SemicolonToken); public IndexerDeclarationSyntax WithParameterList(BracketedParameterListSyntax parameterList) => Update(this.AttributeLists, this.Modifiers, this.Type, this.ExplicitInterfaceSpecifier, this.ThisKeyword, parameterList, this.AccessorList, this.ExpressionBody, this.SemicolonToken); internal override BasePropertyDeclarationSyntax WithAccessorListCore(AccessorListSyntax? accessorList) => WithAccessorList(accessorList); public new IndexerDeclarationSyntax WithAccessorList(AccessorListSyntax? accessorList) => Update(this.AttributeLists, this.Modifiers, this.Type, this.ExplicitInterfaceSpecifier, this.ThisKeyword, this.ParameterList, accessorList, this.ExpressionBody, this.SemicolonToken); public IndexerDeclarationSyntax WithExpressionBody(ArrowExpressionClauseSyntax? expressionBody) => Update(this.AttributeLists, this.Modifiers, this.Type, this.ExplicitInterfaceSpecifier, this.ThisKeyword, this.ParameterList, this.AccessorList, expressionBody, this.SemicolonToken); public IndexerDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.Type, this.ExplicitInterfaceSpecifier, this.ThisKeyword, this.ParameterList, this.AccessorList, this.ExpressionBody, semicolonToken); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new IndexerDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new IndexerDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); public IndexerDeclarationSyntax AddParameterListParameters(params ParameterSyntax[] items) => WithParameterList(this.ParameterList.WithParameters(this.ParameterList.Parameters.AddRange(items))); internal override BasePropertyDeclarationSyntax AddAccessorListAccessorsCore(params AccessorDeclarationSyntax[] items) => AddAccessorListAccessors(items); public new IndexerDeclarationSyntax AddAccessorListAccessors(params AccessorDeclarationSyntax[] items) { var accessorList = this.AccessorList ?? SyntaxFactory.AccessorList(); return WithAccessorList(accessorList.WithAccessors(accessorList.Accessors.AddRange(items))); } } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.AccessorList"/></description></item> /// </list> /// </remarks> public sealed partial class AccessorListSyntax : CSharpSyntaxNode { private SyntaxNode? accessors; internal AccessorListSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken OpenBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.AccessorListSyntax)this.Green).openBraceToken, Position, 0); public SyntaxList<AccessorDeclarationSyntax> Accessors => new SyntaxList<AccessorDeclarationSyntax>(GetRed(ref this.accessors, 1)); public SyntaxToken CloseBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.AccessorListSyntax)this.Green).closeBraceToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.accessors, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.accessors : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitAccessorList(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitAccessorList(this); public AccessorListSyntax Update(SyntaxToken openBraceToken, SyntaxList<AccessorDeclarationSyntax> accessors, SyntaxToken closeBraceToken) { if (openBraceToken != this.OpenBraceToken || accessors != this.Accessors || closeBraceToken != this.CloseBraceToken) { var newNode = SyntaxFactory.AccessorList(openBraceToken, accessors, closeBraceToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public AccessorListSyntax WithOpenBraceToken(SyntaxToken openBraceToken) => Update(openBraceToken, this.Accessors, this.CloseBraceToken); public AccessorListSyntax WithAccessors(SyntaxList<AccessorDeclarationSyntax> accessors) => Update(this.OpenBraceToken, accessors, this.CloseBraceToken); public AccessorListSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) => Update(this.OpenBraceToken, this.Accessors, closeBraceToken); public AccessorListSyntax AddAccessors(params AccessorDeclarationSyntax[] items) => WithAccessors(this.Accessors.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.GetAccessorDeclaration"/></description></item> /// <item><description><see cref="SyntaxKind.SetAccessorDeclaration"/></description></item> /// <item><description><see cref="SyntaxKind.InitAccessorDeclaration"/></description></item> /// <item><description><see cref="SyntaxKind.AddAccessorDeclaration"/></description></item> /// <item><description><see cref="SyntaxKind.RemoveAccessorDeclaration"/></description></item> /// <item><description><see cref="SyntaxKind.UnknownAccessorDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class AccessorDeclarationSyntax : CSharpSyntaxNode { private SyntaxNode? attributeLists; private BlockSyntax? body; private ArrowExpressionClauseSyntax? expressionBody; internal AccessorDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the attribute declaration list.</summary> public SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); /// <summary>Gets the modifier list.</summary> public SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } /// <summary>Gets the keyword token, or identifier if an erroneous accessor declaration.</summary> public SyntaxToken Keyword => new SyntaxToken(this, ((Syntax.InternalSyntax.AccessorDeclarationSyntax)this.Green).keyword, GetChildPosition(2), GetChildIndex(2)); /// <summary>Gets the optional body block which may be empty, but it is null if there are no braces.</summary> public BlockSyntax? Body => GetRed(ref this.body, 3); /// <summary>Gets the optional expression body.</summary> public ArrowExpressionClauseSyntax? ExpressionBody => GetRed(ref this.expressionBody, 4); /// <summary>Gets the optional semicolon token.</summary> public SyntaxToken SemicolonToken { get { var slot = ((Syntax.InternalSyntax.AccessorDeclarationSyntax)this.Green).semicolonToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(5), GetChildIndex(5)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 3 => GetRed(ref this.body, 3), 4 => GetRed(ref this.expressionBody, 4), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 3 => this.body, 4 => this.expressionBody, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitAccessorDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitAccessorDeclaration(this); public AccessorDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || keyword != this.Keyword || body != this.Body || expressionBody != this.ExpressionBody || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.AccessorDeclaration(this.Kind(), attributeLists, modifiers, keyword, body, expressionBody, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public AccessorDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.Keyword, this.Body, this.ExpressionBody, this.SemicolonToken); public AccessorDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.Keyword, this.Body, this.ExpressionBody, this.SemicolonToken); public AccessorDeclarationSyntax WithKeyword(SyntaxToken keyword) => Update(this.AttributeLists, this.Modifiers, keyword, this.Body, this.ExpressionBody, this.SemicolonToken); public AccessorDeclarationSyntax WithBody(BlockSyntax? body) => Update(this.AttributeLists, this.Modifiers, this.Keyword, body, this.ExpressionBody, this.SemicolonToken); public AccessorDeclarationSyntax WithExpressionBody(ArrowExpressionClauseSyntax? expressionBody) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Body, expressionBody, this.SemicolonToken); public AccessorDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Body, this.ExpressionBody, semicolonToken); public AccessorDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); public AccessorDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); public AccessorDeclarationSyntax AddBodyAttributeLists(params AttributeListSyntax[] items) { var body = this.Body ?? SyntaxFactory.Block(); return WithBody(body.WithAttributeLists(body.AttributeLists.AddRange(items))); } public AccessorDeclarationSyntax AddBodyStatements(params StatementSyntax[] items) { var body = this.Body ?? SyntaxFactory.Block(); return WithBody(body.WithStatements(body.Statements.AddRange(items))); } } /// <summary>Base type for parameter list syntax.</summary> public abstract partial class BaseParameterListSyntax : CSharpSyntaxNode { internal BaseParameterListSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the parameter list.</summary> public abstract SeparatedSyntaxList<ParameterSyntax> Parameters { get; } public BaseParameterListSyntax WithParameters(SeparatedSyntaxList<ParameterSyntax> parameters) => WithParametersCore(parameters); internal abstract BaseParameterListSyntax WithParametersCore(SeparatedSyntaxList<ParameterSyntax> parameters); public BaseParameterListSyntax AddParameters(params ParameterSyntax[] items) => AddParametersCore(items); internal abstract BaseParameterListSyntax AddParametersCore(params ParameterSyntax[] items); } /// <summary>Parameter list syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ParameterList"/></description></item> /// </list> /// </remarks> public sealed partial class ParameterListSyntax : BaseParameterListSyntax { private SyntaxNode? parameters; internal ParameterListSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the open paren token.</summary> public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ParameterListSyntax)this.Green).openParenToken, Position, 0); public override SeparatedSyntaxList<ParameterSyntax> Parameters { get { var red = GetRed(ref this.parameters, 1); return red != null ? new SeparatedSyntaxList<ParameterSyntax>(red, GetChildIndex(1)) : default; } } /// <summary>Gets the close paren token.</summary> public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ParameterListSyntax)this.Green).closeParenToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.parameters, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.parameters : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitParameterList(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitParameterList(this); public ParameterListSyntax Update(SyntaxToken openParenToken, SeparatedSyntaxList<ParameterSyntax> parameters, SyntaxToken closeParenToken) { if (openParenToken != this.OpenParenToken || parameters != this.Parameters || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.ParameterList(openParenToken, parameters, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ParameterListSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(openParenToken, this.Parameters, this.CloseParenToken); internal override BaseParameterListSyntax WithParametersCore(SeparatedSyntaxList<ParameterSyntax> parameters) => WithParameters(parameters); public new ParameterListSyntax WithParameters(SeparatedSyntaxList<ParameterSyntax> parameters) => Update(this.OpenParenToken, parameters, this.CloseParenToken); public ParameterListSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.OpenParenToken, this.Parameters, closeParenToken); internal override BaseParameterListSyntax AddParametersCore(params ParameterSyntax[] items) => AddParameters(items); public new ParameterListSyntax AddParameters(params ParameterSyntax[] items) => WithParameters(this.Parameters.AddRange(items)); } /// <summary>Parameter list syntax with surrounding brackets.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.BracketedParameterList"/></description></item> /// </list> /// </remarks> public sealed partial class BracketedParameterListSyntax : BaseParameterListSyntax { private SyntaxNode? parameters; internal BracketedParameterListSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the open bracket token.</summary> public SyntaxToken OpenBracketToken => new SyntaxToken(this, ((Syntax.InternalSyntax.BracketedParameterListSyntax)this.Green).openBracketToken, Position, 0); public override SeparatedSyntaxList<ParameterSyntax> Parameters { get { var red = GetRed(ref this.parameters, 1); return red != null ? new SeparatedSyntaxList<ParameterSyntax>(red, GetChildIndex(1)) : default; } } /// <summary>Gets the close bracket token.</summary> public SyntaxToken CloseBracketToken => new SyntaxToken(this, ((Syntax.InternalSyntax.BracketedParameterListSyntax)this.Green).closeBracketToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.parameters, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.parameters : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitBracketedParameterList(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitBracketedParameterList(this); public BracketedParameterListSyntax Update(SyntaxToken openBracketToken, SeparatedSyntaxList<ParameterSyntax> parameters, SyntaxToken closeBracketToken) { if (openBracketToken != this.OpenBracketToken || parameters != this.Parameters || closeBracketToken != this.CloseBracketToken) { var newNode = SyntaxFactory.BracketedParameterList(openBracketToken, parameters, closeBracketToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public BracketedParameterListSyntax WithOpenBracketToken(SyntaxToken openBracketToken) => Update(openBracketToken, this.Parameters, this.CloseBracketToken); internal override BaseParameterListSyntax WithParametersCore(SeparatedSyntaxList<ParameterSyntax> parameters) => WithParameters(parameters); public new BracketedParameterListSyntax WithParameters(SeparatedSyntaxList<ParameterSyntax> parameters) => Update(this.OpenBracketToken, parameters, this.CloseBracketToken); public BracketedParameterListSyntax WithCloseBracketToken(SyntaxToken closeBracketToken) => Update(this.OpenBracketToken, this.Parameters, closeBracketToken); internal override BaseParameterListSyntax AddParametersCore(params ParameterSyntax[] items) => AddParameters(items); public new BracketedParameterListSyntax AddParameters(params ParameterSyntax[] items) => WithParameters(this.Parameters.AddRange(items)); } /// <summary>Base parameter syntax.</summary> public abstract partial class BaseParameterSyntax : CSharpSyntaxNode { internal BaseParameterSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the attribute declaration list.</summary> public abstract SyntaxList<AttributeListSyntax> AttributeLists { get; } public BaseParameterSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeListsCore(attributeLists); internal abstract BaseParameterSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists); public BaseParameterSyntax AddAttributeLists(params AttributeListSyntax[] items) => AddAttributeListsCore(items); internal abstract BaseParameterSyntax AddAttributeListsCore(params AttributeListSyntax[] items); /// <summary>Gets the modifier list.</summary> public abstract SyntaxTokenList Modifiers { get; } public BaseParameterSyntax WithModifiers(SyntaxTokenList modifiers) => WithModifiersCore(modifiers); internal abstract BaseParameterSyntax WithModifiersCore(SyntaxTokenList modifiers); public BaseParameterSyntax AddModifiers(params SyntaxToken[] items) => AddModifiersCore(items); internal abstract BaseParameterSyntax AddModifiersCore(params SyntaxToken[] items); public abstract TypeSyntax? Type { get; } public BaseParameterSyntax WithType(TypeSyntax? type) => WithTypeCore(type); internal abstract BaseParameterSyntax WithTypeCore(TypeSyntax? type); } /// <summary>Parameter syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.Parameter"/></description></item> /// </list> /// </remarks> public sealed partial class ParameterSyntax : BaseParameterSyntax { private SyntaxNode? attributeLists; private TypeSyntax? type; private EqualsValueClauseSyntax? @default; internal ParameterSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the attribute declaration list.</summary> public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); /// <summary>Gets the modifier list.</summary> public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public override TypeSyntax? Type => GetRed(ref this.type, 2); /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.ParameterSyntax)this.Green).identifier, GetChildPosition(3), GetChildIndex(3)); public EqualsValueClauseSyntax? Default => GetRed(ref this.@default, 4); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.type, 2), 4 => GetRed(ref this.@default, 4), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.type, 4 => this.@default, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitParameter(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitParameter(this); public ParameterSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, TypeSyntax? type, SyntaxToken identifier, EqualsValueClauseSyntax? @default) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || type != this.Type || identifier != this.Identifier || @default != this.Default) { var newNode = SyntaxFactory.Parameter(attributeLists, modifiers, type, identifier, @default); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override BaseParameterSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new ParameterSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.Type, this.Identifier, this.Default); internal override BaseParameterSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new ParameterSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.Type, this.Identifier, this.Default); internal override BaseParameterSyntax WithTypeCore(TypeSyntax? type) => WithType(type); public new ParameterSyntax WithType(TypeSyntax? type) => Update(this.AttributeLists, this.Modifiers, type, this.Identifier, this.Default); public ParameterSyntax WithIdentifier(SyntaxToken identifier) => Update(this.AttributeLists, this.Modifiers, this.Type, identifier, this.Default); public ParameterSyntax WithDefault(EqualsValueClauseSyntax? @default) => Update(this.AttributeLists, this.Modifiers, this.Type, this.Identifier, @default); internal override BaseParameterSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new ParameterSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override BaseParameterSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new ParameterSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); } /// <summary>Parameter syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.FunctionPointerParameter"/></description></item> /// </list> /// </remarks> public sealed partial class FunctionPointerParameterSyntax : BaseParameterSyntax { private SyntaxNode? attributeLists; private TypeSyntax? type; internal FunctionPointerParameterSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the attribute declaration list.</summary> public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); /// <summary>Gets the modifier list.</summary> public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public override TypeSyntax Type => GetRed(ref this.type, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.type, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.type, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitFunctionPointerParameter(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitFunctionPointerParameter(this); public FunctionPointerParameterSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, TypeSyntax type) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || type != this.Type) { var newNode = SyntaxFactory.FunctionPointerParameter(attributeLists, modifiers, type); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override BaseParameterSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new FunctionPointerParameterSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.Type); internal override BaseParameterSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new FunctionPointerParameterSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.Type); internal override BaseParameterSyntax WithTypeCore(TypeSyntax? type) => WithType(type ?? throw new ArgumentNullException(nameof(type))); public new FunctionPointerParameterSyntax WithType(TypeSyntax type) => Update(this.AttributeLists, this.Modifiers, type); internal override BaseParameterSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new FunctionPointerParameterSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override BaseParameterSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new FunctionPointerParameterSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.IncompleteMember"/></description></item> /// </list> /// </remarks> public sealed partial class IncompleteMemberSyntax : MemberDeclarationSyntax { private SyntaxNode? attributeLists; private TypeSyntax? type; internal IncompleteMemberSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public TypeSyntax? Type => GetRed(ref this.type, 2); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.type, 2), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.type, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitIncompleteMember(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitIncompleteMember(this); public IncompleteMemberSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, TypeSyntax? type) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || type != this.Type) { var newNode = SyntaxFactory.IncompleteMember(attributeLists, modifiers, type); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new IncompleteMemberSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.Type); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new IncompleteMemberSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.Type); public IncompleteMemberSyntax WithType(TypeSyntax? type) => Update(this.AttributeLists, this.Modifiers, type); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new IncompleteMemberSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new IncompleteMemberSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.SkippedTokensTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class SkippedTokensTriviaSyntax : StructuredTriviaSyntax { internal SkippedTokensTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxTokenList Tokens { get { var slot = this.Green.GetSlot(0); return slot != null ? new SyntaxTokenList(this, slot, Position, 0) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitSkippedTokensTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitSkippedTokensTrivia(this); public SkippedTokensTriviaSyntax Update(SyntaxTokenList tokens) { if (tokens != this.Tokens) { var newNode = SyntaxFactory.SkippedTokensTrivia(tokens); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public SkippedTokensTriviaSyntax WithTokens(SyntaxTokenList tokens) => Update(tokens); public SkippedTokensTriviaSyntax AddTokens(params SyntaxToken[] items) => WithTokens(this.Tokens.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.SingleLineDocumentationCommentTrivia"/></description></item> /// <item><description><see cref="SyntaxKind.MultiLineDocumentationCommentTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class DocumentationCommentTriviaSyntax : StructuredTriviaSyntax { private SyntaxNode? content; internal DocumentationCommentTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxList<XmlNodeSyntax> Content => new SyntaxList<XmlNodeSyntax>(GetRed(ref this.content, 0)); public SyntaxToken EndOfComment => new SyntaxToken(this, ((Syntax.InternalSyntax.DocumentationCommentTriviaSyntax)this.Green).endOfComment, GetChildPosition(1), GetChildIndex(1)); internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.content)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.content : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitDocumentationCommentTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitDocumentationCommentTrivia(this); public DocumentationCommentTriviaSyntax Update(SyntaxList<XmlNodeSyntax> content, SyntaxToken endOfComment) { if (content != this.Content || endOfComment != this.EndOfComment) { var newNode = SyntaxFactory.DocumentationCommentTrivia(this.Kind(), content, endOfComment); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public DocumentationCommentTriviaSyntax WithContent(SyntaxList<XmlNodeSyntax> content) => Update(content, this.EndOfComment); public DocumentationCommentTriviaSyntax WithEndOfComment(SyntaxToken endOfComment) => Update(this.Content, endOfComment); public DocumentationCommentTriviaSyntax AddContent(params XmlNodeSyntax[] items) => WithContent(this.Content.AddRange(items)); } /// <summary> /// A symbol referenced by a cref attribute (e.g. in a &lt;see&gt; or &lt;seealso&gt; documentation comment tag). /// For example, the M in &lt;see cref="M" /&gt;. /// </summary> public abstract partial class CrefSyntax : CSharpSyntaxNode { internal CrefSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } } /// <summary> /// A symbol reference that definitely refers to a type. /// For example, "int", "A::B", "A.B", "A&lt;T&gt;", but not "M()" (has parameter list) or "this" (indexer). /// NOTE: TypeCrefSyntax, QualifiedCrefSyntax, and MemberCrefSyntax overlap. The syntax in a TypeCrefSyntax /// will always be bound as type, so it's safer to use QualifiedCrefSyntax or MemberCrefSyntax if the symbol /// might be a non-type member. /// </summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.TypeCref"/></description></item> /// </list> /// </remarks> public sealed partial class TypeCrefSyntax : CrefSyntax { private TypeSyntax? type; internal TypeCrefSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public TypeSyntax Type => GetRedAtZero(ref this.type)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.type)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.type : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitTypeCref(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitTypeCref(this); public TypeCrefSyntax Update(TypeSyntax type) { if (type != this.Type) { var newNode = SyntaxFactory.TypeCref(type); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public TypeCrefSyntax WithType(TypeSyntax type) => Update(type); } /// <summary> /// A symbol reference to a type or non-type member that is qualified by an enclosing type or namespace. /// For example, cref="System.String.ToString()". /// NOTE: TypeCrefSyntax, QualifiedCrefSyntax, and MemberCrefSyntax overlap. The syntax in a TypeCrefSyntax /// will always be bound as type, so it's safer to use QualifiedCrefSyntax or MemberCrefSyntax if the symbol /// might be a non-type member. /// </summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.QualifiedCref"/></description></item> /// </list> /// </remarks> public sealed partial class QualifiedCrefSyntax : CrefSyntax { private TypeSyntax? container; private MemberCrefSyntax? member; internal QualifiedCrefSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public TypeSyntax Container => GetRedAtZero(ref this.container)!; public SyntaxToken DotToken => new SyntaxToken(this, ((Syntax.InternalSyntax.QualifiedCrefSyntax)this.Green).dotToken, GetChildPosition(1), GetChildIndex(1)); public MemberCrefSyntax Member => GetRed(ref this.member, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.container)!, 2 => GetRed(ref this.member, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.container, 2 => this.member, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitQualifiedCref(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitQualifiedCref(this); public QualifiedCrefSyntax Update(TypeSyntax container, SyntaxToken dotToken, MemberCrefSyntax member) { if (container != this.Container || dotToken != this.DotToken || member != this.Member) { var newNode = SyntaxFactory.QualifiedCref(container, dotToken, member); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public QualifiedCrefSyntax WithContainer(TypeSyntax container) => Update(container, this.DotToken, this.Member); public QualifiedCrefSyntax WithDotToken(SyntaxToken dotToken) => Update(this.Container, dotToken, this.Member); public QualifiedCrefSyntax WithMember(MemberCrefSyntax member) => Update(this.Container, this.DotToken, member); } /// <summary> /// The unqualified part of a CrefSyntax. /// For example, "ToString()" in "object.ToString()". /// NOTE: TypeCrefSyntax, QualifiedCrefSyntax, and MemberCrefSyntax overlap. The syntax in a TypeCrefSyntax /// will always be bound as type, so it's safer to use QualifiedCrefSyntax or MemberCrefSyntax if the symbol /// might be a non-type member. /// </summary> public abstract partial class MemberCrefSyntax : CrefSyntax { internal MemberCrefSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } } /// <summary> /// A MemberCrefSyntax specified by a name (an identifier, predefined type keyword, or an alias-qualified name, /// with an optional type parameter list) and an optional parameter list. /// For example, "M", "M&lt;T&gt;" or "M(int)". /// Also, "A::B()" or "string()". /// </summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.NameMemberCref"/></description></item> /// </list> /// </remarks> public sealed partial class NameMemberCrefSyntax : MemberCrefSyntax { private TypeSyntax? name; private CrefParameterListSyntax? parameters; internal NameMemberCrefSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public TypeSyntax Name => GetRedAtZero(ref this.name)!; public CrefParameterListSyntax? Parameters => GetRed(ref this.parameters, 1); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.name)!, 1 => GetRed(ref this.parameters, 1), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.name, 1 => this.parameters, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitNameMemberCref(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitNameMemberCref(this); public NameMemberCrefSyntax Update(TypeSyntax name, CrefParameterListSyntax? parameters) { if (name != this.Name || parameters != this.Parameters) { var newNode = SyntaxFactory.NameMemberCref(name, parameters); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public NameMemberCrefSyntax WithName(TypeSyntax name) => Update(name, this.Parameters); public NameMemberCrefSyntax WithParameters(CrefParameterListSyntax? parameters) => Update(this.Name, parameters); public NameMemberCrefSyntax AddParametersParameters(params CrefParameterSyntax[] items) { var parameters = this.Parameters ?? SyntaxFactory.CrefParameterList(); return WithParameters(parameters.WithParameters(parameters.Parameters.AddRange(items))); } } /// <summary> /// A MemberCrefSyntax specified by a this keyword and an optional parameter list. /// For example, "this" or "this[int]". /// </summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.IndexerMemberCref"/></description></item> /// </list> /// </remarks> public sealed partial class IndexerMemberCrefSyntax : MemberCrefSyntax { private CrefBracketedParameterListSyntax? parameters; internal IndexerMemberCrefSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken ThisKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.IndexerMemberCrefSyntax)this.Green).thisKeyword, Position, 0); public CrefBracketedParameterListSyntax? Parameters => GetRed(ref this.parameters, 1); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.parameters, 1) : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.parameters : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitIndexerMemberCref(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitIndexerMemberCref(this); public IndexerMemberCrefSyntax Update(SyntaxToken thisKeyword, CrefBracketedParameterListSyntax? parameters) { if (thisKeyword != this.ThisKeyword || parameters != this.Parameters) { var newNode = SyntaxFactory.IndexerMemberCref(thisKeyword, parameters); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public IndexerMemberCrefSyntax WithThisKeyword(SyntaxToken thisKeyword) => Update(thisKeyword, this.Parameters); public IndexerMemberCrefSyntax WithParameters(CrefBracketedParameterListSyntax? parameters) => Update(this.ThisKeyword, parameters); public IndexerMemberCrefSyntax AddParametersParameters(params CrefParameterSyntax[] items) { var parameters = this.Parameters ?? SyntaxFactory.CrefBracketedParameterList(); return WithParameters(parameters.WithParameters(parameters.Parameters.AddRange(items))); } } /// <summary> /// A MemberCrefSyntax specified by an operator keyword, an operator symbol and an optional parameter list. /// For example, "operator +" or "operator -[int]". /// NOTE: the operator must be overloadable. /// </summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.OperatorMemberCref"/></description></item> /// </list> /// </remarks> public sealed partial class OperatorMemberCrefSyntax : MemberCrefSyntax { private CrefParameterListSyntax? parameters; internal OperatorMemberCrefSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken OperatorKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.OperatorMemberCrefSyntax)this.Green).operatorKeyword, Position, 0); /// <summary>Gets the operator token.</summary> public SyntaxToken OperatorToken => new SyntaxToken(this, ((Syntax.InternalSyntax.OperatorMemberCrefSyntax)this.Green).operatorToken, GetChildPosition(1), GetChildIndex(1)); public CrefParameterListSyntax? Parameters => GetRed(ref this.parameters, 2); internal override SyntaxNode? GetNodeSlot(int index) => index == 2 ? GetRed(ref this.parameters, 2) : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 2 ? this.parameters : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitOperatorMemberCref(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitOperatorMemberCref(this); public OperatorMemberCrefSyntax Update(SyntaxToken operatorKeyword, SyntaxToken operatorToken, CrefParameterListSyntax? parameters) { if (operatorKeyword != this.OperatorKeyword || operatorToken != this.OperatorToken || parameters != this.Parameters) { var newNode = SyntaxFactory.OperatorMemberCref(operatorKeyword, operatorToken, parameters); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public OperatorMemberCrefSyntax WithOperatorKeyword(SyntaxToken operatorKeyword) => Update(operatorKeyword, this.OperatorToken, this.Parameters); public OperatorMemberCrefSyntax WithOperatorToken(SyntaxToken operatorToken) => Update(this.OperatorKeyword, operatorToken, this.Parameters); public OperatorMemberCrefSyntax WithParameters(CrefParameterListSyntax? parameters) => Update(this.OperatorKeyword, this.OperatorToken, parameters); public OperatorMemberCrefSyntax AddParametersParameters(params CrefParameterSyntax[] items) { var parameters = this.Parameters ?? SyntaxFactory.CrefParameterList(); return WithParameters(parameters.WithParameters(parameters.Parameters.AddRange(items))); } } /// <summary> /// A MemberCrefSyntax specified by an implicit or explicit keyword, an operator keyword, a destination type, and an optional parameter list. /// For example, "implicit operator int" or "explicit operator MyType(int)". /// </summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ConversionOperatorMemberCref"/></description></item> /// </list> /// </remarks> public sealed partial class ConversionOperatorMemberCrefSyntax : MemberCrefSyntax { private TypeSyntax? type; private CrefParameterListSyntax? parameters; internal ConversionOperatorMemberCrefSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken ImplicitOrExplicitKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ConversionOperatorMemberCrefSyntax)this.Green).implicitOrExplicitKeyword, Position, 0); public SyntaxToken OperatorKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ConversionOperatorMemberCrefSyntax)this.Green).operatorKeyword, GetChildPosition(1), GetChildIndex(1)); public TypeSyntax Type => GetRed(ref this.type, 2)!; public CrefParameterListSyntax? Parameters => GetRed(ref this.parameters, 3); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 2 => GetRed(ref this.type, 2)!, 3 => GetRed(ref this.parameters, 3), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 2 => this.type, 3 => this.parameters, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitConversionOperatorMemberCref(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitConversionOperatorMemberCref(this); public ConversionOperatorMemberCrefSyntax Update(SyntaxToken implicitOrExplicitKeyword, SyntaxToken operatorKeyword, TypeSyntax type, CrefParameterListSyntax? parameters) { if (implicitOrExplicitKeyword != this.ImplicitOrExplicitKeyword || operatorKeyword != this.OperatorKeyword || type != this.Type || parameters != this.Parameters) { var newNode = SyntaxFactory.ConversionOperatorMemberCref(implicitOrExplicitKeyword, operatorKeyword, type, parameters); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ConversionOperatorMemberCrefSyntax WithImplicitOrExplicitKeyword(SyntaxToken implicitOrExplicitKeyword) => Update(implicitOrExplicitKeyword, this.OperatorKeyword, this.Type, this.Parameters); public ConversionOperatorMemberCrefSyntax WithOperatorKeyword(SyntaxToken operatorKeyword) => Update(this.ImplicitOrExplicitKeyword, operatorKeyword, this.Type, this.Parameters); public ConversionOperatorMemberCrefSyntax WithType(TypeSyntax type) => Update(this.ImplicitOrExplicitKeyword, this.OperatorKeyword, type, this.Parameters); public ConversionOperatorMemberCrefSyntax WithParameters(CrefParameterListSyntax? parameters) => Update(this.ImplicitOrExplicitKeyword, this.OperatorKeyword, this.Type, parameters); public ConversionOperatorMemberCrefSyntax AddParametersParameters(params CrefParameterSyntax[] items) { var parameters = this.Parameters ?? SyntaxFactory.CrefParameterList(); return WithParameters(parameters.WithParameters(parameters.Parameters.AddRange(items))); } } /// <summary> /// A list of cref parameters with surrounding punctuation. /// Unlike regular parameters, cref parameters do not have names. /// </summary> public abstract partial class BaseCrefParameterListSyntax : CSharpSyntaxNode { internal BaseCrefParameterListSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the parameter list.</summary> public abstract SeparatedSyntaxList<CrefParameterSyntax> Parameters { get; } public BaseCrefParameterListSyntax WithParameters(SeparatedSyntaxList<CrefParameterSyntax> parameters) => WithParametersCore(parameters); internal abstract BaseCrefParameterListSyntax WithParametersCore(SeparatedSyntaxList<CrefParameterSyntax> parameters); public BaseCrefParameterListSyntax AddParameters(params CrefParameterSyntax[] items) => AddParametersCore(items); internal abstract BaseCrefParameterListSyntax AddParametersCore(params CrefParameterSyntax[] items); } /// <summary> /// A parenthesized list of cref parameters. /// </summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.CrefParameterList"/></description></item> /// </list> /// </remarks> public sealed partial class CrefParameterListSyntax : BaseCrefParameterListSyntax { private SyntaxNode? parameters; internal CrefParameterListSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the open paren token.</summary> public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.CrefParameterListSyntax)this.Green).openParenToken, Position, 0); public override SeparatedSyntaxList<CrefParameterSyntax> Parameters { get { var red = GetRed(ref this.parameters, 1); return red != null ? new SeparatedSyntaxList<CrefParameterSyntax>(red, GetChildIndex(1)) : default; } } /// <summary>Gets the close paren token.</summary> public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.CrefParameterListSyntax)this.Green).closeParenToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.parameters, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.parameters : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitCrefParameterList(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitCrefParameterList(this); public CrefParameterListSyntax Update(SyntaxToken openParenToken, SeparatedSyntaxList<CrefParameterSyntax> parameters, SyntaxToken closeParenToken) { if (openParenToken != this.OpenParenToken || parameters != this.Parameters || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.CrefParameterList(openParenToken, parameters, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public CrefParameterListSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(openParenToken, this.Parameters, this.CloseParenToken); internal override BaseCrefParameterListSyntax WithParametersCore(SeparatedSyntaxList<CrefParameterSyntax> parameters) => WithParameters(parameters); public new CrefParameterListSyntax WithParameters(SeparatedSyntaxList<CrefParameterSyntax> parameters) => Update(this.OpenParenToken, parameters, this.CloseParenToken); public CrefParameterListSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.OpenParenToken, this.Parameters, closeParenToken); internal override BaseCrefParameterListSyntax AddParametersCore(params CrefParameterSyntax[] items) => AddParameters(items); public new CrefParameterListSyntax AddParameters(params CrefParameterSyntax[] items) => WithParameters(this.Parameters.AddRange(items)); } /// <summary> /// A bracketed list of cref parameters. /// </summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.CrefBracketedParameterList"/></description></item> /// </list> /// </remarks> public sealed partial class CrefBracketedParameterListSyntax : BaseCrefParameterListSyntax { private SyntaxNode? parameters; internal CrefBracketedParameterListSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the open bracket token.</summary> public SyntaxToken OpenBracketToken => new SyntaxToken(this, ((Syntax.InternalSyntax.CrefBracketedParameterListSyntax)this.Green).openBracketToken, Position, 0); public override SeparatedSyntaxList<CrefParameterSyntax> Parameters { get { var red = GetRed(ref this.parameters, 1); return red != null ? new SeparatedSyntaxList<CrefParameterSyntax>(red, GetChildIndex(1)) : default; } } /// <summary>Gets the close bracket token.</summary> public SyntaxToken CloseBracketToken => new SyntaxToken(this, ((Syntax.InternalSyntax.CrefBracketedParameterListSyntax)this.Green).closeBracketToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.parameters, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.parameters : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitCrefBracketedParameterList(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitCrefBracketedParameterList(this); public CrefBracketedParameterListSyntax Update(SyntaxToken openBracketToken, SeparatedSyntaxList<CrefParameterSyntax> parameters, SyntaxToken closeBracketToken) { if (openBracketToken != this.OpenBracketToken || parameters != this.Parameters || closeBracketToken != this.CloseBracketToken) { var newNode = SyntaxFactory.CrefBracketedParameterList(openBracketToken, parameters, closeBracketToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public CrefBracketedParameterListSyntax WithOpenBracketToken(SyntaxToken openBracketToken) => Update(openBracketToken, this.Parameters, this.CloseBracketToken); internal override BaseCrefParameterListSyntax WithParametersCore(SeparatedSyntaxList<CrefParameterSyntax> parameters) => WithParameters(parameters); public new CrefBracketedParameterListSyntax WithParameters(SeparatedSyntaxList<CrefParameterSyntax> parameters) => Update(this.OpenBracketToken, parameters, this.CloseBracketToken); public CrefBracketedParameterListSyntax WithCloseBracketToken(SyntaxToken closeBracketToken) => Update(this.OpenBracketToken, this.Parameters, closeBracketToken); internal override BaseCrefParameterListSyntax AddParametersCore(params CrefParameterSyntax[] items) => AddParameters(items); public new CrefBracketedParameterListSyntax AddParameters(params CrefParameterSyntax[] items) => WithParameters(this.Parameters.AddRange(items)); } /// <summary> /// An element of a BaseCrefParameterListSyntax. /// Unlike a regular parameter, a cref parameter has only an optional ref or out keyword and a type - /// there is no name and there are no attributes or other modifiers. /// </summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.CrefParameter"/></description></item> /// </list> /// </remarks> public sealed partial class CrefParameterSyntax : CSharpSyntaxNode { private TypeSyntax? type; internal CrefParameterSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken RefKindKeyword { get { var slot = ((Syntax.InternalSyntax.CrefParameterSyntax)this.Green).refKindKeyword; return slot != null ? new SyntaxToken(this, slot, Position, 0) : default; } } public TypeSyntax Type => GetRed(ref this.type, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.type, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.type : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitCrefParameter(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitCrefParameter(this); public CrefParameterSyntax Update(SyntaxToken refKindKeyword, TypeSyntax type) { if (refKindKeyword != this.RefKindKeyword || type != this.Type) { var newNode = SyntaxFactory.CrefParameter(refKindKeyword, type); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public CrefParameterSyntax WithRefKindKeyword(SyntaxToken refKindKeyword) => Update(refKindKeyword, this.Type); public CrefParameterSyntax WithType(TypeSyntax type) => Update(this.RefKindKeyword, type); } public abstract partial class XmlNodeSyntax : CSharpSyntaxNode { internal XmlNodeSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.XmlElement"/></description></item> /// </list> /// </remarks> public sealed partial class XmlElementSyntax : XmlNodeSyntax { private XmlElementStartTagSyntax? startTag; private SyntaxNode? content; private XmlElementEndTagSyntax? endTag; internal XmlElementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public XmlElementStartTagSyntax StartTag => GetRedAtZero(ref this.startTag)!; public SyntaxList<XmlNodeSyntax> Content => new SyntaxList<XmlNodeSyntax>(GetRed(ref this.content, 1)); public XmlElementEndTagSyntax EndTag => GetRed(ref this.endTag, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.startTag)!, 1 => GetRed(ref this.content, 1)!, 2 => GetRed(ref this.endTag, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.startTag, 1 => this.content, 2 => this.endTag, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitXmlElement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitXmlElement(this); public XmlElementSyntax Update(XmlElementStartTagSyntax startTag, SyntaxList<XmlNodeSyntax> content, XmlElementEndTagSyntax endTag) { if (startTag != this.StartTag || content != this.Content || endTag != this.EndTag) { var newNode = SyntaxFactory.XmlElement(startTag, content, endTag); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public XmlElementSyntax WithStartTag(XmlElementStartTagSyntax startTag) => Update(startTag, this.Content, this.EndTag); public XmlElementSyntax WithContent(SyntaxList<XmlNodeSyntax> content) => Update(this.StartTag, content, this.EndTag); public XmlElementSyntax WithEndTag(XmlElementEndTagSyntax endTag) => Update(this.StartTag, this.Content, endTag); public XmlElementSyntax AddStartTagAttributes(params XmlAttributeSyntax[] items) => WithStartTag(this.StartTag.WithAttributes(this.StartTag.Attributes.AddRange(items))); public XmlElementSyntax AddContent(params XmlNodeSyntax[] items) => WithContent(this.Content.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.XmlElementStartTag"/></description></item> /// </list> /// </remarks> public sealed partial class XmlElementStartTagSyntax : CSharpSyntaxNode { private XmlNameSyntax? name; private SyntaxNode? attributes; internal XmlElementStartTagSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken LessThanToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlElementStartTagSyntax)this.Green).lessThanToken, Position, 0); public XmlNameSyntax Name => GetRed(ref this.name, 1)!; public SyntaxList<XmlAttributeSyntax> Attributes => new SyntaxList<XmlAttributeSyntax>(GetRed(ref this.attributes, 2)); public SyntaxToken GreaterThanToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlElementStartTagSyntax)this.Green).greaterThanToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 1 => GetRed(ref this.name, 1)!, 2 => GetRed(ref this.attributes, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 1 => this.name, 2 => this.attributes, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitXmlElementStartTag(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitXmlElementStartTag(this); public XmlElementStartTagSyntax Update(SyntaxToken lessThanToken, XmlNameSyntax name, SyntaxList<XmlAttributeSyntax> attributes, SyntaxToken greaterThanToken) { if (lessThanToken != this.LessThanToken || name != this.Name || attributes != this.Attributes || greaterThanToken != this.GreaterThanToken) { var newNode = SyntaxFactory.XmlElementStartTag(lessThanToken, name, attributes, greaterThanToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public XmlElementStartTagSyntax WithLessThanToken(SyntaxToken lessThanToken) => Update(lessThanToken, this.Name, this.Attributes, this.GreaterThanToken); public XmlElementStartTagSyntax WithName(XmlNameSyntax name) => Update(this.LessThanToken, name, this.Attributes, this.GreaterThanToken); public XmlElementStartTagSyntax WithAttributes(SyntaxList<XmlAttributeSyntax> attributes) => Update(this.LessThanToken, this.Name, attributes, this.GreaterThanToken); public XmlElementStartTagSyntax WithGreaterThanToken(SyntaxToken greaterThanToken) => Update(this.LessThanToken, this.Name, this.Attributes, greaterThanToken); public XmlElementStartTagSyntax AddAttributes(params XmlAttributeSyntax[] items) => WithAttributes(this.Attributes.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.XmlElementEndTag"/></description></item> /// </list> /// </remarks> public sealed partial class XmlElementEndTagSyntax : CSharpSyntaxNode { private XmlNameSyntax? name; internal XmlElementEndTagSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken LessThanSlashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlElementEndTagSyntax)this.Green).lessThanSlashToken, Position, 0); public XmlNameSyntax Name => GetRed(ref this.name, 1)!; public SyntaxToken GreaterThanToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlElementEndTagSyntax)this.Green).greaterThanToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.name, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.name : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitXmlElementEndTag(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitXmlElementEndTag(this); public XmlElementEndTagSyntax Update(SyntaxToken lessThanSlashToken, XmlNameSyntax name, SyntaxToken greaterThanToken) { if (lessThanSlashToken != this.LessThanSlashToken || name != this.Name || greaterThanToken != this.GreaterThanToken) { var newNode = SyntaxFactory.XmlElementEndTag(lessThanSlashToken, name, greaterThanToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public XmlElementEndTagSyntax WithLessThanSlashToken(SyntaxToken lessThanSlashToken) => Update(lessThanSlashToken, this.Name, this.GreaterThanToken); public XmlElementEndTagSyntax WithName(XmlNameSyntax name) => Update(this.LessThanSlashToken, name, this.GreaterThanToken); public XmlElementEndTagSyntax WithGreaterThanToken(SyntaxToken greaterThanToken) => Update(this.LessThanSlashToken, this.Name, greaterThanToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.XmlEmptyElement"/></description></item> /// </list> /// </remarks> public sealed partial class XmlEmptyElementSyntax : XmlNodeSyntax { private XmlNameSyntax? name; private SyntaxNode? attributes; internal XmlEmptyElementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken LessThanToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlEmptyElementSyntax)this.Green).lessThanToken, Position, 0); public XmlNameSyntax Name => GetRed(ref this.name, 1)!; public SyntaxList<XmlAttributeSyntax> Attributes => new SyntaxList<XmlAttributeSyntax>(GetRed(ref this.attributes, 2)); public SyntaxToken SlashGreaterThanToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlEmptyElementSyntax)this.Green).slashGreaterThanToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 1 => GetRed(ref this.name, 1)!, 2 => GetRed(ref this.attributes, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 1 => this.name, 2 => this.attributes, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitXmlEmptyElement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitXmlEmptyElement(this); public XmlEmptyElementSyntax Update(SyntaxToken lessThanToken, XmlNameSyntax name, SyntaxList<XmlAttributeSyntax> attributes, SyntaxToken slashGreaterThanToken) { if (lessThanToken != this.LessThanToken || name != this.Name || attributes != this.Attributes || slashGreaterThanToken != this.SlashGreaterThanToken) { var newNode = SyntaxFactory.XmlEmptyElement(lessThanToken, name, attributes, slashGreaterThanToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public XmlEmptyElementSyntax WithLessThanToken(SyntaxToken lessThanToken) => Update(lessThanToken, this.Name, this.Attributes, this.SlashGreaterThanToken); public XmlEmptyElementSyntax WithName(XmlNameSyntax name) => Update(this.LessThanToken, name, this.Attributes, this.SlashGreaterThanToken); public XmlEmptyElementSyntax WithAttributes(SyntaxList<XmlAttributeSyntax> attributes) => Update(this.LessThanToken, this.Name, attributes, this.SlashGreaterThanToken); public XmlEmptyElementSyntax WithSlashGreaterThanToken(SyntaxToken slashGreaterThanToken) => Update(this.LessThanToken, this.Name, this.Attributes, slashGreaterThanToken); public XmlEmptyElementSyntax AddAttributes(params XmlAttributeSyntax[] items) => WithAttributes(this.Attributes.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.XmlName"/></description></item> /// </list> /// </remarks> public sealed partial class XmlNameSyntax : CSharpSyntaxNode { private XmlPrefixSyntax? prefix; internal XmlNameSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public XmlPrefixSyntax? Prefix => GetRedAtZero(ref this.prefix); public SyntaxToken LocalName => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlNameSyntax)this.Green).localName, GetChildPosition(1), GetChildIndex(1)); internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.prefix) : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.prefix : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitXmlName(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitXmlName(this); public XmlNameSyntax Update(XmlPrefixSyntax? prefix, SyntaxToken localName) { if (prefix != this.Prefix || localName != this.LocalName) { var newNode = SyntaxFactory.XmlName(prefix, localName); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public XmlNameSyntax WithPrefix(XmlPrefixSyntax? prefix) => Update(prefix, this.LocalName); public XmlNameSyntax WithLocalName(SyntaxToken localName) => Update(this.Prefix, localName); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.XmlPrefix"/></description></item> /// </list> /// </remarks> public sealed partial class XmlPrefixSyntax : CSharpSyntaxNode { internal XmlPrefixSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken Prefix => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlPrefixSyntax)this.Green).prefix, Position, 0); public SyntaxToken ColonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlPrefixSyntax)this.Green).colonToken, GetChildPosition(1), GetChildIndex(1)); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitXmlPrefix(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitXmlPrefix(this); public XmlPrefixSyntax Update(SyntaxToken prefix, SyntaxToken colonToken) { if (prefix != this.Prefix || colonToken != this.ColonToken) { var newNode = SyntaxFactory.XmlPrefix(prefix, colonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public XmlPrefixSyntax WithPrefix(SyntaxToken prefix) => Update(prefix, this.ColonToken); public XmlPrefixSyntax WithColonToken(SyntaxToken colonToken) => Update(this.Prefix, colonToken); } public abstract partial class XmlAttributeSyntax : CSharpSyntaxNode { internal XmlAttributeSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public abstract XmlNameSyntax Name { get; } public XmlAttributeSyntax WithName(XmlNameSyntax name) => WithNameCore(name); internal abstract XmlAttributeSyntax WithNameCore(XmlNameSyntax name); public abstract SyntaxToken EqualsToken { get; } public XmlAttributeSyntax WithEqualsToken(SyntaxToken equalsToken) => WithEqualsTokenCore(equalsToken); internal abstract XmlAttributeSyntax WithEqualsTokenCore(SyntaxToken equalsToken); public abstract SyntaxToken StartQuoteToken { get; } public XmlAttributeSyntax WithStartQuoteToken(SyntaxToken startQuoteToken) => WithStartQuoteTokenCore(startQuoteToken); internal abstract XmlAttributeSyntax WithStartQuoteTokenCore(SyntaxToken startQuoteToken); public abstract SyntaxToken EndQuoteToken { get; } public XmlAttributeSyntax WithEndQuoteToken(SyntaxToken endQuoteToken) => WithEndQuoteTokenCore(endQuoteToken); internal abstract XmlAttributeSyntax WithEndQuoteTokenCore(SyntaxToken endQuoteToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.XmlTextAttribute"/></description></item> /// </list> /// </remarks> public sealed partial class XmlTextAttributeSyntax : XmlAttributeSyntax { private XmlNameSyntax? name; internal XmlTextAttributeSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override XmlNameSyntax Name => GetRedAtZero(ref this.name)!; public override SyntaxToken EqualsToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlTextAttributeSyntax)this.Green).equalsToken, GetChildPosition(1), GetChildIndex(1)); public override SyntaxToken StartQuoteToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlTextAttributeSyntax)this.Green).startQuoteToken, GetChildPosition(2), GetChildIndex(2)); public SyntaxTokenList TextTokens { get { var slot = this.Green.GetSlot(3); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(3), GetChildIndex(3)) : default; } } public override SyntaxToken EndQuoteToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlTextAttributeSyntax)this.Green).endQuoteToken, GetChildPosition(4), GetChildIndex(4)); internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.name)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.name : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitXmlTextAttribute(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitXmlTextAttribute(this); public XmlTextAttributeSyntax Update(XmlNameSyntax name, SyntaxToken equalsToken, SyntaxToken startQuoteToken, SyntaxTokenList textTokens, SyntaxToken endQuoteToken) { if (name != this.Name || equalsToken != this.EqualsToken || startQuoteToken != this.StartQuoteToken || textTokens != this.TextTokens || endQuoteToken != this.EndQuoteToken) { var newNode = SyntaxFactory.XmlTextAttribute(name, equalsToken, startQuoteToken, textTokens, endQuoteToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override XmlAttributeSyntax WithNameCore(XmlNameSyntax name) => WithName(name); public new XmlTextAttributeSyntax WithName(XmlNameSyntax name) => Update(name, this.EqualsToken, this.StartQuoteToken, this.TextTokens, this.EndQuoteToken); internal override XmlAttributeSyntax WithEqualsTokenCore(SyntaxToken equalsToken) => WithEqualsToken(equalsToken); public new XmlTextAttributeSyntax WithEqualsToken(SyntaxToken equalsToken) => Update(this.Name, equalsToken, this.StartQuoteToken, this.TextTokens, this.EndQuoteToken); internal override XmlAttributeSyntax WithStartQuoteTokenCore(SyntaxToken startQuoteToken) => WithStartQuoteToken(startQuoteToken); public new XmlTextAttributeSyntax WithStartQuoteToken(SyntaxToken startQuoteToken) => Update(this.Name, this.EqualsToken, startQuoteToken, this.TextTokens, this.EndQuoteToken); public XmlTextAttributeSyntax WithTextTokens(SyntaxTokenList textTokens) => Update(this.Name, this.EqualsToken, this.StartQuoteToken, textTokens, this.EndQuoteToken); internal override XmlAttributeSyntax WithEndQuoteTokenCore(SyntaxToken endQuoteToken) => WithEndQuoteToken(endQuoteToken); public new XmlTextAttributeSyntax WithEndQuoteToken(SyntaxToken endQuoteToken) => Update(this.Name, this.EqualsToken, this.StartQuoteToken, this.TextTokens, endQuoteToken); public XmlTextAttributeSyntax AddTextTokens(params SyntaxToken[] items) => WithTextTokens(this.TextTokens.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.XmlCrefAttribute"/></description></item> /// </list> /// </remarks> public sealed partial class XmlCrefAttributeSyntax : XmlAttributeSyntax { private XmlNameSyntax? name; private CrefSyntax? cref; internal XmlCrefAttributeSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override XmlNameSyntax Name => GetRedAtZero(ref this.name)!; public override SyntaxToken EqualsToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlCrefAttributeSyntax)this.Green).equalsToken, GetChildPosition(1), GetChildIndex(1)); public override SyntaxToken StartQuoteToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlCrefAttributeSyntax)this.Green).startQuoteToken, GetChildPosition(2), GetChildIndex(2)); public CrefSyntax Cref => GetRed(ref this.cref, 3)!; public override SyntaxToken EndQuoteToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlCrefAttributeSyntax)this.Green).endQuoteToken, GetChildPosition(4), GetChildIndex(4)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.name)!, 3 => GetRed(ref this.cref, 3)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.name, 3 => this.cref, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitXmlCrefAttribute(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitXmlCrefAttribute(this); public XmlCrefAttributeSyntax Update(XmlNameSyntax name, SyntaxToken equalsToken, SyntaxToken startQuoteToken, CrefSyntax cref, SyntaxToken endQuoteToken) { if (name != this.Name || equalsToken != this.EqualsToken || startQuoteToken != this.StartQuoteToken || cref != this.Cref || endQuoteToken != this.EndQuoteToken) { var newNode = SyntaxFactory.XmlCrefAttribute(name, equalsToken, startQuoteToken, cref, endQuoteToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override XmlAttributeSyntax WithNameCore(XmlNameSyntax name) => WithName(name); public new XmlCrefAttributeSyntax WithName(XmlNameSyntax name) => Update(name, this.EqualsToken, this.StartQuoteToken, this.Cref, this.EndQuoteToken); internal override XmlAttributeSyntax WithEqualsTokenCore(SyntaxToken equalsToken) => WithEqualsToken(equalsToken); public new XmlCrefAttributeSyntax WithEqualsToken(SyntaxToken equalsToken) => Update(this.Name, equalsToken, this.StartQuoteToken, this.Cref, this.EndQuoteToken); internal override XmlAttributeSyntax WithStartQuoteTokenCore(SyntaxToken startQuoteToken) => WithStartQuoteToken(startQuoteToken); public new XmlCrefAttributeSyntax WithStartQuoteToken(SyntaxToken startQuoteToken) => Update(this.Name, this.EqualsToken, startQuoteToken, this.Cref, this.EndQuoteToken); public XmlCrefAttributeSyntax WithCref(CrefSyntax cref) => Update(this.Name, this.EqualsToken, this.StartQuoteToken, cref, this.EndQuoteToken); internal override XmlAttributeSyntax WithEndQuoteTokenCore(SyntaxToken endQuoteToken) => WithEndQuoteToken(endQuoteToken); public new XmlCrefAttributeSyntax WithEndQuoteToken(SyntaxToken endQuoteToken) => Update(this.Name, this.EqualsToken, this.StartQuoteToken, this.Cref, endQuoteToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.XmlNameAttribute"/></description></item> /// </list> /// </remarks> public sealed partial class XmlNameAttributeSyntax : XmlAttributeSyntax { private XmlNameSyntax? name; private IdentifierNameSyntax? identifier; internal XmlNameAttributeSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override XmlNameSyntax Name => GetRedAtZero(ref this.name)!; public override SyntaxToken EqualsToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlNameAttributeSyntax)this.Green).equalsToken, GetChildPosition(1), GetChildIndex(1)); public override SyntaxToken StartQuoteToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlNameAttributeSyntax)this.Green).startQuoteToken, GetChildPosition(2), GetChildIndex(2)); public IdentifierNameSyntax Identifier => GetRed(ref this.identifier, 3)!; public override SyntaxToken EndQuoteToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlNameAttributeSyntax)this.Green).endQuoteToken, GetChildPosition(4), GetChildIndex(4)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.name)!, 3 => GetRed(ref this.identifier, 3)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.name, 3 => this.identifier, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitXmlNameAttribute(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitXmlNameAttribute(this); public XmlNameAttributeSyntax Update(XmlNameSyntax name, SyntaxToken equalsToken, SyntaxToken startQuoteToken, IdentifierNameSyntax identifier, SyntaxToken endQuoteToken) { if (name != this.Name || equalsToken != this.EqualsToken || startQuoteToken != this.StartQuoteToken || identifier != this.Identifier || endQuoteToken != this.EndQuoteToken) { var newNode = SyntaxFactory.XmlNameAttribute(name, equalsToken, startQuoteToken, identifier, endQuoteToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override XmlAttributeSyntax WithNameCore(XmlNameSyntax name) => WithName(name); public new XmlNameAttributeSyntax WithName(XmlNameSyntax name) => Update(name, this.EqualsToken, this.StartQuoteToken, this.Identifier, this.EndQuoteToken); internal override XmlAttributeSyntax WithEqualsTokenCore(SyntaxToken equalsToken) => WithEqualsToken(equalsToken); public new XmlNameAttributeSyntax WithEqualsToken(SyntaxToken equalsToken) => Update(this.Name, equalsToken, this.StartQuoteToken, this.Identifier, this.EndQuoteToken); internal override XmlAttributeSyntax WithStartQuoteTokenCore(SyntaxToken startQuoteToken) => WithStartQuoteToken(startQuoteToken); public new XmlNameAttributeSyntax WithStartQuoteToken(SyntaxToken startQuoteToken) => Update(this.Name, this.EqualsToken, startQuoteToken, this.Identifier, this.EndQuoteToken); public XmlNameAttributeSyntax WithIdentifier(IdentifierNameSyntax identifier) => Update(this.Name, this.EqualsToken, this.StartQuoteToken, identifier, this.EndQuoteToken); internal override XmlAttributeSyntax WithEndQuoteTokenCore(SyntaxToken endQuoteToken) => WithEndQuoteToken(endQuoteToken); public new XmlNameAttributeSyntax WithEndQuoteToken(SyntaxToken endQuoteToken) => Update(this.Name, this.EqualsToken, this.StartQuoteToken, this.Identifier, endQuoteToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.XmlText"/></description></item> /// </list> /// </remarks> public sealed partial class XmlTextSyntax : XmlNodeSyntax { internal XmlTextSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxTokenList TextTokens { get { var slot = this.Green.GetSlot(0); return slot != null ? new SyntaxTokenList(this, slot, Position, 0) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitXmlText(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitXmlText(this); public XmlTextSyntax Update(SyntaxTokenList textTokens) { if (textTokens != this.TextTokens) { var newNode = SyntaxFactory.XmlText(textTokens); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public XmlTextSyntax WithTextTokens(SyntaxTokenList textTokens) => Update(textTokens); public XmlTextSyntax AddTextTokens(params SyntaxToken[] items) => WithTextTokens(this.TextTokens.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.XmlCDataSection"/></description></item> /// </list> /// </remarks> public sealed partial class XmlCDataSectionSyntax : XmlNodeSyntax { internal XmlCDataSectionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken StartCDataToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlCDataSectionSyntax)this.Green).startCDataToken, Position, 0); public SyntaxTokenList TextTokens { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public SyntaxToken EndCDataToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlCDataSectionSyntax)this.Green).endCDataToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitXmlCDataSection(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitXmlCDataSection(this); public XmlCDataSectionSyntax Update(SyntaxToken startCDataToken, SyntaxTokenList textTokens, SyntaxToken endCDataToken) { if (startCDataToken != this.StartCDataToken || textTokens != this.TextTokens || endCDataToken != this.EndCDataToken) { var newNode = SyntaxFactory.XmlCDataSection(startCDataToken, textTokens, endCDataToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public XmlCDataSectionSyntax WithStartCDataToken(SyntaxToken startCDataToken) => Update(startCDataToken, this.TextTokens, this.EndCDataToken); public XmlCDataSectionSyntax WithTextTokens(SyntaxTokenList textTokens) => Update(this.StartCDataToken, textTokens, this.EndCDataToken); public XmlCDataSectionSyntax WithEndCDataToken(SyntaxToken endCDataToken) => Update(this.StartCDataToken, this.TextTokens, endCDataToken); public XmlCDataSectionSyntax AddTextTokens(params SyntaxToken[] items) => WithTextTokens(this.TextTokens.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.XmlProcessingInstruction"/></description></item> /// </list> /// </remarks> public sealed partial class XmlProcessingInstructionSyntax : XmlNodeSyntax { private XmlNameSyntax? name; internal XmlProcessingInstructionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken StartProcessingInstructionToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlProcessingInstructionSyntax)this.Green).startProcessingInstructionToken, Position, 0); public XmlNameSyntax Name => GetRed(ref this.name, 1)!; public SyntaxTokenList TextTokens { get { var slot = this.Green.GetSlot(2); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(2), GetChildIndex(2)) : default; } } public SyntaxToken EndProcessingInstructionToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlProcessingInstructionSyntax)this.Green).endProcessingInstructionToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.name, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.name : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitXmlProcessingInstruction(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitXmlProcessingInstruction(this); public XmlProcessingInstructionSyntax Update(SyntaxToken startProcessingInstructionToken, XmlNameSyntax name, SyntaxTokenList textTokens, SyntaxToken endProcessingInstructionToken) { if (startProcessingInstructionToken != this.StartProcessingInstructionToken || name != this.Name || textTokens != this.TextTokens || endProcessingInstructionToken != this.EndProcessingInstructionToken) { var newNode = SyntaxFactory.XmlProcessingInstruction(startProcessingInstructionToken, name, textTokens, endProcessingInstructionToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public XmlProcessingInstructionSyntax WithStartProcessingInstructionToken(SyntaxToken startProcessingInstructionToken) => Update(startProcessingInstructionToken, this.Name, this.TextTokens, this.EndProcessingInstructionToken); public XmlProcessingInstructionSyntax WithName(XmlNameSyntax name) => Update(this.StartProcessingInstructionToken, name, this.TextTokens, this.EndProcessingInstructionToken); public XmlProcessingInstructionSyntax WithTextTokens(SyntaxTokenList textTokens) => Update(this.StartProcessingInstructionToken, this.Name, textTokens, this.EndProcessingInstructionToken); public XmlProcessingInstructionSyntax WithEndProcessingInstructionToken(SyntaxToken endProcessingInstructionToken) => Update(this.StartProcessingInstructionToken, this.Name, this.TextTokens, endProcessingInstructionToken); public XmlProcessingInstructionSyntax AddTextTokens(params SyntaxToken[] items) => WithTextTokens(this.TextTokens.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.XmlComment"/></description></item> /// </list> /// </remarks> public sealed partial class XmlCommentSyntax : XmlNodeSyntax { internal XmlCommentSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken LessThanExclamationMinusMinusToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlCommentSyntax)this.Green).lessThanExclamationMinusMinusToken, Position, 0); public SyntaxTokenList TextTokens { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public SyntaxToken MinusMinusGreaterThanToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlCommentSyntax)this.Green).minusMinusGreaterThanToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitXmlComment(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitXmlComment(this); public XmlCommentSyntax Update(SyntaxToken lessThanExclamationMinusMinusToken, SyntaxTokenList textTokens, SyntaxToken minusMinusGreaterThanToken) { if (lessThanExclamationMinusMinusToken != this.LessThanExclamationMinusMinusToken || textTokens != this.TextTokens || minusMinusGreaterThanToken != this.MinusMinusGreaterThanToken) { var newNode = SyntaxFactory.XmlComment(lessThanExclamationMinusMinusToken, textTokens, minusMinusGreaterThanToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public XmlCommentSyntax WithLessThanExclamationMinusMinusToken(SyntaxToken lessThanExclamationMinusMinusToken) => Update(lessThanExclamationMinusMinusToken, this.TextTokens, this.MinusMinusGreaterThanToken); public XmlCommentSyntax WithTextTokens(SyntaxTokenList textTokens) => Update(this.LessThanExclamationMinusMinusToken, textTokens, this.MinusMinusGreaterThanToken); public XmlCommentSyntax WithMinusMinusGreaterThanToken(SyntaxToken minusMinusGreaterThanToken) => Update(this.LessThanExclamationMinusMinusToken, this.TextTokens, minusMinusGreaterThanToken); public XmlCommentSyntax AddTextTokens(params SyntaxToken[] items) => WithTextTokens(this.TextTokens.AddRange(items)); } public abstract partial class DirectiveTriviaSyntax : StructuredTriviaSyntax { internal DirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public abstract SyntaxToken HashToken { get; } public DirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => WithHashTokenCore(hashToken); internal abstract DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken); public abstract SyntaxToken EndOfDirectiveToken { get; } public DirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveTokenCore(endOfDirectiveToken); internal abstract DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken); public abstract bool IsActive { get; } } public abstract partial class BranchingDirectiveTriviaSyntax : DirectiveTriviaSyntax { internal BranchingDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public abstract bool BranchTaken { get; } public new BranchingDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => (BranchingDirectiveTriviaSyntax)WithHashTokenCore(hashToken); public new BranchingDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => (BranchingDirectiveTriviaSyntax)WithEndOfDirectiveTokenCore(endOfDirectiveToken); } public abstract partial class ConditionalDirectiveTriviaSyntax : BranchingDirectiveTriviaSyntax { internal ConditionalDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public abstract ExpressionSyntax Condition { get; } public ConditionalDirectiveTriviaSyntax WithCondition(ExpressionSyntax condition) => WithConditionCore(condition); internal abstract ConditionalDirectiveTriviaSyntax WithConditionCore(ExpressionSyntax condition); public abstract bool ConditionValue { get; } } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.IfDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class IfDirectiveTriviaSyntax : ConditionalDirectiveTriviaSyntax { private ExpressionSyntax? condition; internal IfDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.IfDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public SyntaxToken IfKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.IfDirectiveTriviaSyntax)this.Green).ifKeyword, GetChildPosition(1), GetChildIndex(1)); public override ExpressionSyntax Condition => GetRed(ref this.condition, 2)!; public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.IfDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(3), GetChildIndex(3)); public override bool IsActive => ((Syntax.InternalSyntax.IfDirectiveTriviaSyntax)this.Green).IsActive; public override bool BranchTaken => ((Syntax.InternalSyntax.IfDirectiveTriviaSyntax)this.Green).BranchTaken; public override bool ConditionValue => ((Syntax.InternalSyntax.IfDirectiveTriviaSyntax)this.Green).ConditionValue; internal override SyntaxNode? GetNodeSlot(int index) => index == 2 ? GetRed(ref this.condition, 2)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 2 ? this.condition : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitIfDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitIfDirectiveTrivia(this); public IfDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken ifKeyword, ExpressionSyntax condition, SyntaxToken endOfDirectiveToken, bool isActive, bool branchTaken, bool conditionValue) { if (hashToken != this.HashToken || ifKeyword != this.IfKeyword || condition != this.Condition || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.IfDirectiveTrivia(hashToken, ifKeyword, condition, endOfDirectiveToken, isActive, branchTaken, conditionValue); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new IfDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.IfKeyword, this.Condition, this.EndOfDirectiveToken, this.IsActive, this.BranchTaken, this.ConditionValue); public IfDirectiveTriviaSyntax WithIfKeyword(SyntaxToken ifKeyword) => Update(this.HashToken, ifKeyword, this.Condition, this.EndOfDirectiveToken, this.IsActive, this.BranchTaken, this.ConditionValue); internal override ConditionalDirectiveTriviaSyntax WithConditionCore(ExpressionSyntax condition) => WithCondition(condition); public new IfDirectiveTriviaSyntax WithCondition(ExpressionSyntax condition) => Update(this.HashToken, this.IfKeyword, condition, this.EndOfDirectiveToken, this.IsActive, this.BranchTaken, this.ConditionValue); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new IfDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.IfKeyword, this.Condition, endOfDirectiveToken, this.IsActive, this.BranchTaken, this.ConditionValue); public IfDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.IfKeyword, this.Condition, this.EndOfDirectiveToken, isActive, this.BranchTaken, this.ConditionValue); public IfDirectiveTriviaSyntax WithBranchTaken(bool branchTaken) => Update(this.HashToken, this.IfKeyword, this.Condition, this.EndOfDirectiveToken, this.IsActive, branchTaken, this.ConditionValue); public IfDirectiveTriviaSyntax WithConditionValue(bool conditionValue) => Update(this.HashToken, this.IfKeyword, this.Condition, this.EndOfDirectiveToken, this.IsActive, this.BranchTaken, conditionValue); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ElifDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class ElifDirectiveTriviaSyntax : ConditionalDirectiveTriviaSyntax { private ExpressionSyntax? condition; internal ElifDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ElifDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public SyntaxToken ElifKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ElifDirectiveTriviaSyntax)this.Green).elifKeyword, GetChildPosition(1), GetChildIndex(1)); public override ExpressionSyntax Condition => GetRed(ref this.condition, 2)!; public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ElifDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(3), GetChildIndex(3)); public override bool IsActive => ((Syntax.InternalSyntax.ElifDirectiveTriviaSyntax)this.Green).IsActive; public override bool BranchTaken => ((Syntax.InternalSyntax.ElifDirectiveTriviaSyntax)this.Green).BranchTaken; public override bool ConditionValue => ((Syntax.InternalSyntax.ElifDirectiveTriviaSyntax)this.Green).ConditionValue; internal override SyntaxNode? GetNodeSlot(int index) => index == 2 ? GetRed(ref this.condition, 2)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 2 ? this.condition : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitElifDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitElifDirectiveTrivia(this); public ElifDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken elifKeyword, ExpressionSyntax condition, SyntaxToken endOfDirectiveToken, bool isActive, bool branchTaken, bool conditionValue) { if (hashToken != this.HashToken || elifKeyword != this.ElifKeyword || condition != this.Condition || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.ElifDirectiveTrivia(hashToken, elifKeyword, condition, endOfDirectiveToken, isActive, branchTaken, conditionValue); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new ElifDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.ElifKeyword, this.Condition, this.EndOfDirectiveToken, this.IsActive, this.BranchTaken, this.ConditionValue); public ElifDirectiveTriviaSyntax WithElifKeyword(SyntaxToken elifKeyword) => Update(this.HashToken, elifKeyword, this.Condition, this.EndOfDirectiveToken, this.IsActive, this.BranchTaken, this.ConditionValue); internal override ConditionalDirectiveTriviaSyntax WithConditionCore(ExpressionSyntax condition) => WithCondition(condition); public new ElifDirectiveTriviaSyntax WithCondition(ExpressionSyntax condition) => Update(this.HashToken, this.ElifKeyword, condition, this.EndOfDirectiveToken, this.IsActive, this.BranchTaken, this.ConditionValue); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new ElifDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.ElifKeyword, this.Condition, endOfDirectiveToken, this.IsActive, this.BranchTaken, this.ConditionValue); public ElifDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.ElifKeyword, this.Condition, this.EndOfDirectiveToken, isActive, this.BranchTaken, this.ConditionValue); public ElifDirectiveTriviaSyntax WithBranchTaken(bool branchTaken) => Update(this.HashToken, this.ElifKeyword, this.Condition, this.EndOfDirectiveToken, this.IsActive, branchTaken, this.ConditionValue); public ElifDirectiveTriviaSyntax WithConditionValue(bool conditionValue) => Update(this.HashToken, this.ElifKeyword, this.Condition, this.EndOfDirectiveToken, this.IsActive, this.BranchTaken, conditionValue); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ElseDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class ElseDirectiveTriviaSyntax : BranchingDirectiveTriviaSyntax { internal ElseDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ElseDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public SyntaxToken ElseKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ElseDirectiveTriviaSyntax)this.Green).elseKeyword, GetChildPosition(1), GetChildIndex(1)); public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ElseDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(2), GetChildIndex(2)); public override bool IsActive => ((Syntax.InternalSyntax.ElseDirectiveTriviaSyntax)this.Green).IsActive; public override bool BranchTaken => ((Syntax.InternalSyntax.ElseDirectiveTriviaSyntax)this.Green).BranchTaken; internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitElseDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitElseDirectiveTrivia(this); public ElseDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken elseKeyword, SyntaxToken endOfDirectiveToken, bool isActive, bool branchTaken) { if (hashToken != this.HashToken || elseKeyword != this.ElseKeyword || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.ElseDirectiveTrivia(hashToken, elseKeyword, endOfDirectiveToken, isActive, branchTaken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new ElseDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.ElseKeyword, this.EndOfDirectiveToken, this.IsActive, this.BranchTaken); public ElseDirectiveTriviaSyntax WithElseKeyword(SyntaxToken elseKeyword) => Update(this.HashToken, elseKeyword, this.EndOfDirectiveToken, this.IsActive, this.BranchTaken); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new ElseDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.ElseKeyword, endOfDirectiveToken, this.IsActive, this.BranchTaken); public ElseDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.ElseKeyword, this.EndOfDirectiveToken, isActive, this.BranchTaken); public ElseDirectiveTriviaSyntax WithBranchTaken(bool branchTaken) => Update(this.HashToken, this.ElseKeyword, this.EndOfDirectiveToken, this.IsActive, branchTaken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.EndIfDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class EndIfDirectiveTriviaSyntax : DirectiveTriviaSyntax { internal EndIfDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.EndIfDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public SyntaxToken EndIfKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.EndIfDirectiveTriviaSyntax)this.Green).endIfKeyword, GetChildPosition(1), GetChildIndex(1)); public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.EndIfDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(2), GetChildIndex(2)); public override bool IsActive => ((Syntax.InternalSyntax.EndIfDirectiveTriviaSyntax)this.Green).IsActive; internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitEndIfDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitEndIfDirectiveTrivia(this); public EndIfDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken endIfKeyword, SyntaxToken endOfDirectiveToken, bool isActive) { if (hashToken != this.HashToken || endIfKeyword != this.EndIfKeyword || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.EndIfDirectiveTrivia(hashToken, endIfKeyword, endOfDirectiveToken, isActive); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new EndIfDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.EndIfKeyword, this.EndOfDirectiveToken, this.IsActive); public EndIfDirectiveTriviaSyntax WithEndIfKeyword(SyntaxToken endIfKeyword) => Update(this.HashToken, endIfKeyword, this.EndOfDirectiveToken, this.IsActive); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new EndIfDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.EndIfKeyword, endOfDirectiveToken, this.IsActive); public EndIfDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.EndIfKeyword, this.EndOfDirectiveToken, isActive); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.RegionDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class RegionDirectiveTriviaSyntax : DirectiveTriviaSyntax { internal RegionDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.RegionDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public SyntaxToken RegionKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.RegionDirectiveTriviaSyntax)this.Green).regionKeyword, GetChildPosition(1), GetChildIndex(1)); public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.RegionDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(2), GetChildIndex(2)); public override bool IsActive => ((Syntax.InternalSyntax.RegionDirectiveTriviaSyntax)this.Green).IsActive; internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitRegionDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitRegionDirectiveTrivia(this); public RegionDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken regionKeyword, SyntaxToken endOfDirectiveToken, bool isActive) { if (hashToken != this.HashToken || regionKeyword != this.RegionKeyword || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.RegionDirectiveTrivia(hashToken, regionKeyword, endOfDirectiveToken, isActive); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new RegionDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.RegionKeyword, this.EndOfDirectiveToken, this.IsActive); public RegionDirectiveTriviaSyntax WithRegionKeyword(SyntaxToken regionKeyword) => Update(this.HashToken, regionKeyword, this.EndOfDirectiveToken, this.IsActive); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new RegionDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.RegionKeyword, endOfDirectiveToken, this.IsActive); public RegionDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.RegionKeyword, this.EndOfDirectiveToken, isActive); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.EndRegionDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class EndRegionDirectiveTriviaSyntax : DirectiveTriviaSyntax { internal EndRegionDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.EndRegionDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public SyntaxToken EndRegionKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.EndRegionDirectiveTriviaSyntax)this.Green).endRegionKeyword, GetChildPosition(1), GetChildIndex(1)); public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.EndRegionDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(2), GetChildIndex(2)); public override bool IsActive => ((Syntax.InternalSyntax.EndRegionDirectiveTriviaSyntax)this.Green).IsActive; internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitEndRegionDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitEndRegionDirectiveTrivia(this); public EndRegionDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken endRegionKeyword, SyntaxToken endOfDirectiveToken, bool isActive) { if (hashToken != this.HashToken || endRegionKeyword != this.EndRegionKeyword || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.EndRegionDirectiveTrivia(hashToken, endRegionKeyword, endOfDirectiveToken, isActive); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new EndRegionDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.EndRegionKeyword, this.EndOfDirectiveToken, this.IsActive); public EndRegionDirectiveTriviaSyntax WithEndRegionKeyword(SyntaxToken endRegionKeyword) => Update(this.HashToken, endRegionKeyword, this.EndOfDirectiveToken, this.IsActive); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new EndRegionDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.EndRegionKeyword, endOfDirectiveToken, this.IsActive); public EndRegionDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.EndRegionKeyword, this.EndOfDirectiveToken, isActive); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ErrorDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class ErrorDirectiveTriviaSyntax : DirectiveTriviaSyntax { internal ErrorDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ErrorDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public SyntaxToken ErrorKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ErrorDirectiveTriviaSyntax)this.Green).errorKeyword, GetChildPosition(1), GetChildIndex(1)); public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ErrorDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(2), GetChildIndex(2)); public override bool IsActive => ((Syntax.InternalSyntax.ErrorDirectiveTriviaSyntax)this.Green).IsActive; internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitErrorDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitErrorDirectiveTrivia(this); public ErrorDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken errorKeyword, SyntaxToken endOfDirectiveToken, bool isActive) { if (hashToken != this.HashToken || errorKeyword != this.ErrorKeyword || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.ErrorDirectiveTrivia(hashToken, errorKeyword, endOfDirectiveToken, isActive); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new ErrorDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.ErrorKeyword, this.EndOfDirectiveToken, this.IsActive); public ErrorDirectiveTriviaSyntax WithErrorKeyword(SyntaxToken errorKeyword) => Update(this.HashToken, errorKeyword, this.EndOfDirectiveToken, this.IsActive); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new ErrorDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.ErrorKeyword, endOfDirectiveToken, this.IsActive); public ErrorDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.ErrorKeyword, this.EndOfDirectiveToken, isActive); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.WarningDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class WarningDirectiveTriviaSyntax : DirectiveTriviaSyntax { internal WarningDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.WarningDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public SyntaxToken WarningKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.WarningDirectiveTriviaSyntax)this.Green).warningKeyword, GetChildPosition(1), GetChildIndex(1)); public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.WarningDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(2), GetChildIndex(2)); public override bool IsActive => ((Syntax.InternalSyntax.WarningDirectiveTriviaSyntax)this.Green).IsActive; internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitWarningDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitWarningDirectiveTrivia(this); public WarningDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken warningKeyword, SyntaxToken endOfDirectiveToken, bool isActive) { if (hashToken != this.HashToken || warningKeyword != this.WarningKeyword || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.WarningDirectiveTrivia(hashToken, warningKeyword, endOfDirectiveToken, isActive); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new WarningDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.WarningKeyword, this.EndOfDirectiveToken, this.IsActive); public WarningDirectiveTriviaSyntax WithWarningKeyword(SyntaxToken warningKeyword) => Update(this.HashToken, warningKeyword, this.EndOfDirectiveToken, this.IsActive); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new WarningDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.WarningKeyword, endOfDirectiveToken, this.IsActive); public WarningDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.WarningKeyword, this.EndOfDirectiveToken, isActive); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.BadDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class BadDirectiveTriviaSyntax : DirectiveTriviaSyntax { internal BadDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.BadDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.BadDirectiveTriviaSyntax)this.Green).identifier, GetChildPosition(1), GetChildIndex(1)); public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.BadDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(2), GetChildIndex(2)); public override bool IsActive => ((Syntax.InternalSyntax.BadDirectiveTriviaSyntax)this.Green).IsActive; internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitBadDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitBadDirectiveTrivia(this); public BadDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken identifier, SyntaxToken endOfDirectiveToken, bool isActive) { if (hashToken != this.HashToken || identifier != this.Identifier || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.BadDirectiveTrivia(hashToken, identifier, endOfDirectiveToken, isActive); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new BadDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.Identifier, this.EndOfDirectiveToken, this.IsActive); public BadDirectiveTriviaSyntax WithIdentifier(SyntaxToken identifier) => Update(this.HashToken, identifier, this.EndOfDirectiveToken, this.IsActive); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new BadDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.Identifier, endOfDirectiveToken, this.IsActive); public BadDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.Identifier, this.EndOfDirectiveToken, isActive); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.DefineDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class DefineDirectiveTriviaSyntax : DirectiveTriviaSyntax { internal DefineDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.DefineDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public SyntaxToken DefineKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.DefineDirectiveTriviaSyntax)this.Green).defineKeyword, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken Name => new SyntaxToken(this, ((Syntax.InternalSyntax.DefineDirectiveTriviaSyntax)this.Green).name, GetChildPosition(2), GetChildIndex(2)); public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.DefineDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(3), GetChildIndex(3)); public override bool IsActive => ((Syntax.InternalSyntax.DefineDirectiveTriviaSyntax)this.Green).IsActive; internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitDefineDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitDefineDirectiveTrivia(this); public DefineDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken defineKeyword, SyntaxToken name, SyntaxToken endOfDirectiveToken, bool isActive) { if (hashToken != this.HashToken || defineKeyword != this.DefineKeyword || name != this.Name || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.DefineDirectiveTrivia(hashToken, defineKeyword, name, endOfDirectiveToken, isActive); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new DefineDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.DefineKeyword, this.Name, this.EndOfDirectiveToken, this.IsActive); public DefineDirectiveTriviaSyntax WithDefineKeyword(SyntaxToken defineKeyword) => Update(this.HashToken, defineKeyword, this.Name, this.EndOfDirectiveToken, this.IsActive); public DefineDirectiveTriviaSyntax WithName(SyntaxToken name) => Update(this.HashToken, this.DefineKeyword, name, this.EndOfDirectiveToken, this.IsActive); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new DefineDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.DefineKeyword, this.Name, endOfDirectiveToken, this.IsActive); public DefineDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.DefineKeyword, this.Name, this.EndOfDirectiveToken, isActive); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.UndefDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class UndefDirectiveTriviaSyntax : DirectiveTriviaSyntax { internal UndefDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.UndefDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public SyntaxToken UndefKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.UndefDirectiveTriviaSyntax)this.Green).undefKeyword, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken Name => new SyntaxToken(this, ((Syntax.InternalSyntax.UndefDirectiveTriviaSyntax)this.Green).name, GetChildPosition(2), GetChildIndex(2)); public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.UndefDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(3), GetChildIndex(3)); public override bool IsActive => ((Syntax.InternalSyntax.UndefDirectiveTriviaSyntax)this.Green).IsActive; internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitUndefDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitUndefDirectiveTrivia(this); public UndefDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken undefKeyword, SyntaxToken name, SyntaxToken endOfDirectiveToken, bool isActive) { if (hashToken != this.HashToken || undefKeyword != this.UndefKeyword || name != this.Name || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.UndefDirectiveTrivia(hashToken, undefKeyword, name, endOfDirectiveToken, isActive); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new UndefDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.UndefKeyword, this.Name, this.EndOfDirectiveToken, this.IsActive); public UndefDirectiveTriviaSyntax WithUndefKeyword(SyntaxToken undefKeyword) => Update(this.HashToken, undefKeyword, this.Name, this.EndOfDirectiveToken, this.IsActive); public UndefDirectiveTriviaSyntax WithName(SyntaxToken name) => Update(this.HashToken, this.UndefKeyword, name, this.EndOfDirectiveToken, this.IsActive); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new UndefDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.UndefKeyword, this.Name, endOfDirectiveToken, this.IsActive); public UndefDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.UndefKeyword, this.Name, this.EndOfDirectiveToken, isActive); } public abstract partial class LineOrSpanDirectiveTriviaSyntax : DirectiveTriviaSyntax { internal LineOrSpanDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public abstract SyntaxToken LineKeyword { get; } public LineOrSpanDirectiveTriviaSyntax WithLineKeyword(SyntaxToken lineKeyword) => WithLineKeywordCore(lineKeyword); internal abstract LineOrSpanDirectiveTriviaSyntax WithLineKeywordCore(SyntaxToken lineKeyword); public abstract SyntaxToken File { get; } public LineOrSpanDirectiveTriviaSyntax WithFile(SyntaxToken file) => WithFileCore(file); internal abstract LineOrSpanDirectiveTriviaSyntax WithFileCore(SyntaxToken file); public new LineOrSpanDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => (LineOrSpanDirectiveTriviaSyntax)WithHashTokenCore(hashToken); public new LineOrSpanDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => (LineOrSpanDirectiveTriviaSyntax)WithEndOfDirectiveTokenCore(endOfDirectiveToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.LineDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class LineDirectiveTriviaSyntax : LineOrSpanDirectiveTriviaSyntax { internal LineDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.LineDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public override SyntaxToken LineKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.LineDirectiveTriviaSyntax)this.Green).lineKeyword, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken Line => new SyntaxToken(this, ((Syntax.InternalSyntax.LineDirectiveTriviaSyntax)this.Green).line, GetChildPosition(2), GetChildIndex(2)); public override SyntaxToken File { get { var slot = ((Syntax.InternalSyntax.LineDirectiveTriviaSyntax)this.Green).file; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(3), GetChildIndex(3)) : default; } } public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.LineDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(4), GetChildIndex(4)); public override bool IsActive => ((Syntax.InternalSyntax.LineDirectiveTriviaSyntax)this.Green).IsActive; internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitLineDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitLineDirectiveTrivia(this); public LineDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken lineKeyword, SyntaxToken line, SyntaxToken file, SyntaxToken endOfDirectiveToken, bool isActive) { if (hashToken != this.HashToken || lineKeyword != this.LineKeyword || line != this.Line || file != this.File || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.LineDirectiveTrivia(hashToken, lineKeyword, line, file, endOfDirectiveToken, isActive); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new LineDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.LineKeyword, this.Line, this.File, this.EndOfDirectiveToken, this.IsActive); internal override LineOrSpanDirectiveTriviaSyntax WithLineKeywordCore(SyntaxToken lineKeyword) => WithLineKeyword(lineKeyword); public new LineDirectiveTriviaSyntax WithLineKeyword(SyntaxToken lineKeyword) => Update(this.HashToken, lineKeyword, this.Line, this.File, this.EndOfDirectiveToken, this.IsActive); public LineDirectiveTriviaSyntax WithLine(SyntaxToken line) => Update(this.HashToken, this.LineKeyword, line, this.File, this.EndOfDirectiveToken, this.IsActive); internal override LineOrSpanDirectiveTriviaSyntax WithFileCore(SyntaxToken file) => WithFile(file); public new LineDirectiveTriviaSyntax WithFile(SyntaxToken file) => Update(this.HashToken, this.LineKeyword, this.Line, file, this.EndOfDirectiveToken, this.IsActive); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new LineDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.LineKeyword, this.Line, this.File, endOfDirectiveToken, this.IsActive); public LineDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.LineKeyword, this.Line, this.File, this.EndOfDirectiveToken, isActive); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.LineDirectivePosition"/></description></item> /// </list> /// </remarks> public sealed partial class LineDirectivePositionSyntax : CSharpSyntaxNode { internal LineDirectivePositionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.LineDirectivePositionSyntax)this.Green).openParenToken, Position, 0); public SyntaxToken Line => new SyntaxToken(this, ((Syntax.InternalSyntax.LineDirectivePositionSyntax)this.Green).line, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken CommaToken => new SyntaxToken(this, ((Syntax.InternalSyntax.LineDirectivePositionSyntax)this.Green).commaToken, GetChildPosition(2), GetChildIndex(2)); public SyntaxToken Character => new SyntaxToken(this, ((Syntax.InternalSyntax.LineDirectivePositionSyntax)this.Green).character, GetChildPosition(3), GetChildIndex(3)); public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.LineDirectivePositionSyntax)this.Green).closeParenToken, GetChildPosition(4), GetChildIndex(4)); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitLineDirectivePosition(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitLineDirectivePosition(this); public LineDirectivePositionSyntax Update(SyntaxToken openParenToken, SyntaxToken line, SyntaxToken commaToken, SyntaxToken character, SyntaxToken closeParenToken) { if (openParenToken != this.OpenParenToken || line != this.Line || commaToken != this.CommaToken || character != this.Character || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.LineDirectivePosition(openParenToken, line, commaToken, character, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public LineDirectivePositionSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(openParenToken, this.Line, this.CommaToken, this.Character, this.CloseParenToken); public LineDirectivePositionSyntax WithLine(SyntaxToken line) => Update(this.OpenParenToken, line, this.CommaToken, this.Character, this.CloseParenToken); public LineDirectivePositionSyntax WithCommaToken(SyntaxToken commaToken) => Update(this.OpenParenToken, this.Line, commaToken, this.Character, this.CloseParenToken); public LineDirectivePositionSyntax WithCharacter(SyntaxToken character) => Update(this.OpenParenToken, this.Line, this.CommaToken, character, this.CloseParenToken); public LineDirectivePositionSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.OpenParenToken, this.Line, this.CommaToken, this.Character, closeParenToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.LineSpanDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class LineSpanDirectiveTriviaSyntax : LineOrSpanDirectiveTriviaSyntax { private LineDirectivePositionSyntax? start; private LineDirectivePositionSyntax? end; internal LineSpanDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.LineSpanDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public override SyntaxToken LineKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.LineSpanDirectiveTriviaSyntax)this.Green).lineKeyword, GetChildPosition(1), GetChildIndex(1)); public LineDirectivePositionSyntax Start => GetRed(ref this.start, 2)!; public SyntaxToken MinusToken => new SyntaxToken(this, ((Syntax.InternalSyntax.LineSpanDirectiveTriviaSyntax)this.Green).minusToken, GetChildPosition(3), GetChildIndex(3)); public LineDirectivePositionSyntax End => GetRed(ref this.end, 4)!; public SyntaxToken CharacterOffset { get { var slot = ((Syntax.InternalSyntax.LineSpanDirectiveTriviaSyntax)this.Green).characterOffset; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(5), GetChildIndex(5)) : default; } } public override SyntaxToken File => new SyntaxToken(this, ((Syntax.InternalSyntax.LineSpanDirectiveTriviaSyntax)this.Green).file, GetChildPosition(6), GetChildIndex(6)); public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.LineSpanDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(7), GetChildIndex(7)); public override bool IsActive => ((Syntax.InternalSyntax.LineSpanDirectiveTriviaSyntax)this.Green).IsActive; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 2 => GetRed(ref this.start, 2)!, 4 => GetRed(ref this.end, 4)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 2 => this.start, 4 => this.end, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitLineSpanDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitLineSpanDirectiveTrivia(this); public LineSpanDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken lineKeyword, LineDirectivePositionSyntax start, SyntaxToken minusToken, LineDirectivePositionSyntax end, SyntaxToken characterOffset, SyntaxToken file, SyntaxToken endOfDirectiveToken, bool isActive) { if (hashToken != this.HashToken || lineKeyword != this.LineKeyword || start != this.Start || minusToken != this.MinusToken || end != this.End || characterOffset != this.CharacterOffset || file != this.File || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.LineSpanDirectiveTrivia(hashToken, lineKeyword, start, minusToken, end, characterOffset, file, endOfDirectiveToken, isActive); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new LineSpanDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.LineKeyword, this.Start, this.MinusToken, this.End, this.CharacterOffset, this.File, this.EndOfDirectiveToken, this.IsActive); internal override LineOrSpanDirectiveTriviaSyntax WithLineKeywordCore(SyntaxToken lineKeyword) => WithLineKeyword(lineKeyword); public new LineSpanDirectiveTriviaSyntax WithLineKeyword(SyntaxToken lineKeyword) => Update(this.HashToken, lineKeyword, this.Start, this.MinusToken, this.End, this.CharacterOffset, this.File, this.EndOfDirectiveToken, this.IsActive); public LineSpanDirectiveTriviaSyntax WithStart(LineDirectivePositionSyntax start) => Update(this.HashToken, this.LineKeyword, start, this.MinusToken, this.End, this.CharacterOffset, this.File, this.EndOfDirectiveToken, this.IsActive); public LineSpanDirectiveTriviaSyntax WithMinusToken(SyntaxToken minusToken) => Update(this.HashToken, this.LineKeyword, this.Start, minusToken, this.End, this.CharacterOffset, this.File, this.EndOfDirectiveToken, this.IsActive); public LineSpanDirectiveTriviaSyntax WithEnd(LineDirectivePositionSyntax end) => Update(this.HashToken, this.LineKeyword, this.Start, this.MinusToken, end, this.CharacterOffset, this.File, this.EndOfDirectiveToken, this.IsActive); public LineSpanDirectiveTriviaSyntax WithCharacterOffset(SyntaxToken characterOffset) => Update(this.HashToken, this.LineKeyword, this.Start, this.MinusToken, this.End, characterOffset, this.File, this.EndOfDirectiveToken, this.IsActive); internal override LineOrSpanDirectiveTriviaSyntax WithFileCore(SyntaxToken file) => WithFile(file); public new LineSpanDirectiveTriviaSyntax WithFile(SyntaxToken file) => Update(this.HashToken, this.LineKeyword, this.Start, this.MinusToken, this.End, this.CharacterOffset, file, this.EndOfDirectiveToken, this.IsActive); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new LineSpanDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.LineKeyword, this.Start, this.MinusToken, this.End, this.CharacterOffset, this.File, endOfDirectiveToken, this.IsActive); public LineSpanDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.LineKeyword, this.Start, this.MinusToken, this.End, this.CharacterOffset, this.File, this.EndOfDirectiveToken, isActive); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.PragmaWarningDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class PragmaWarningDirectiveTriviaSyntax : DirectiveTriviaSyntax { private SyntaxNode? errorCodes; internal PragmaWarningDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.PragmaWarningDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public SyntaxToken PragmaKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.PragmaWarningDirectiveTriviaSyntax)this.Green).pragmaKeyword, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken WarningKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.PragmaWarningDirectiveTriviaSyntax)this.Green).warningKeyword, GetChildPosition(2), GetChildIndex(2)); public SyntaxToken DisableOrRestoreKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.PragmaWarningDirectiveTriviaSyntax)this.Green).disableOrRestoreKeyword, GetChildPosition(3), GetChildIndex(3)); public SeparatedSyntaxList<ExpressionSyntax> ErrorCodes { get { var red = GetRed(ref this.errorCodes, 4); return red != null ? new SeparatedSyntaxList<ExpressionSyntax>(red, GetChildIndex(4)) : default; } } public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.PragmaWarningDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(5), GetChildIndex(5)); public override bool IsActive => ((Syntax.InternalSyntax.PragmaWarningDirectiveTriviaSyntax)this.Green).IsActive; internal override SyntaxNode? GetNodeSlot(int index) => index == 4 ? GetRed(ref this.errorCodes, 4)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 4 ? this.errorCodes : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitPragmaWarningDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitPragmaWarningDirectiveTrivia(this); public PragmaWarningDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken pragmaKeyword, SyntaxToken warningKeyword, SyntaxToken disableOrRestoreKeyword, SeparatedSyntaxList<ExpressionSyntax> errorCodes, SyntaxToken endOfDirectiveToken, bool isActive) { if (hashToken != this.HashToken || pragmaKeyword != this.PragmaKeyword || warningKeyword != this.WarningKeyword || disableOrRestoreKeyword != this.DisableOrRestoreKeyword || errorCodes != this.ErrorCodes || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.PragmaWarningDirectiveTrivia(hashToken, pragmaKeyword, warningKeyword, disableOrRestoreKeyword, errorCodes, endOfDirectiveToken, isActive); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new PragmaWarningDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.PragmaKeyword, this.WarningKeyword, this.DisableOrRestoreKeyword, this.ErrorCodes, this.EndOfDirectiveToken, this.IsActive); public PragmaWarningDirectiveTriviaSyntax WithPragmaKeyword(SyntaxToken pragmaKeyword) => Update(this.HashToken, pragmaKeyword, this.WarningKeyword, this.DisableOrRestoreKeyword, this.ErrorCodes, this.EndOfDirectiveToken, this.IsActive); public PragmaWarningDirectiveTriviaSyntax WithWarningKeyword(SyntaxToken warningKeyword) => Update(this.HashToken, this.PragmaKeyword, warningKeyword, this.DisableOrRestoreKeyword, this.ErrorCodes, this.EndOfDirectiveToken, this.IsActive); public PragmaWarningDirectiveTriviaSyntax WithDisableOrRestoreKeyword(SyntaxToken disableOrRestoreKeyword) => Update(this.HashToken, this.PragmaKeyword, this.WarningKeyword, disableOrRestoreKeyword, this.ErrorCodes, this.EndOfDirectiveToken, this.IsActive); public PragmaWarningDirectiveTriviaSyntax WithErrorCodes(SeparatedSyntaxList<ExpressionSyntax> errorCodes) => Update(this.HashToken, this.PragmaKeyword, this.WarningKeyword, this.DisableOrRestoreKeyword, errorCodes, this.EndOfDirectiveToken, this.IsActive); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new PragmaWarningDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.PragmaKeyword, this.WarningKeyword, this.DisableOrRestoreKeyword, this.ErrorCodes, endOfDirectiveToken, this.IsActive); public PragmaWarningDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.PragmaKeyword, this.WarningKeyword, this.DisableOrRestoreKeyword, this.ErrorCodes, this.EndOfDirectiveToken, isActive); public PragmaWarningDirectiveTriviaSyntax AddErrorCodes(params ExpressionSyntax[] items) => WithErrorCodes(this.ErrorCodes.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.PragmaChecksumDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class PragmaChecksumDirectiveTriviaSyntax : DirectiveTriviaSyntax { internal PragmaChecksumDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.PragmaChecksumDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public SyntaxToken PragmaKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.PragmaChecksumDirectiveTriviaSyntax)this.Green).pragmaKeyword, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken ChecksumKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.PragmaChecksumDirectiveTriviaSyntax)this.Green).checksumKeyword, GetChildPosition(2), GetChildIndex(2)); public SyntaxToken File => new SyntaxToken(this, ((Syntax.InternalSyntax.PragmaChecksumDirectiveTriviaSyntax)this.Green).file, GetChildPosition(3), GetChildIndex(3)); public SyntaxToken Guid => new SyntaxToken(this, ((Syntax.InternalSyntax.PragmaChecksumDirectiveTriviaSyntax)this.Green).guid, GetChildPosition(4), GetChildIndex(4)); public SyntaxToken Bytes => new SyntaxToken(this, ((Syntax.InternalSyntax.PragmaChecksumDirectiveTriviaSyntax)this.Green).bytes, GetChildPosition(5), GetChildIndex(5)); public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.PragmaChecksumDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(6), GetChildIndex(6)); public override bool IsActive => ((Syntax.InternalSyntax.PragmaChecksumDirectiveTriviaSyntax)this.Green).IsActive; internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitPragmaChecksumDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitPragmaChecksumDirectiveTrivia(this); public PragmaChecksumDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken pragmaKeyword, SyntaxToken checksumKeyword, SyntaxToken file, SyntaxToken guid, SyntaxToken bytes, SyntaxToken endOfDirectiveToken, bool isActive) { if (hashToken != this.HashToken || pragmaKeyword != this.PragmaKeyword || checksumKeyword != this.ChecksumKeyword || file != this.File || guid != this.Guid || bytes != this.Bytes || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.PragmaChecksumDirectiveTrivia(hashToken, pragmaKeyword, checksumKeyword, file, guid, bytes, endOfDirectiveToken, isActive); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new PragmaChecksumDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.PragmaKeyword, this.ChecksumKeyword, this.File, this.Guid, this.Bytes, this.EndOfDirectiveToken, this.IsActive); public PragmaChecksumDirectiveTriviaSyntax WithPragmaKeyword(SyntaxToken pragmaKeyword) => Update(this.HashToken, pragmaKeyword, this.ChecksumKeyword, this.File, this.Guid, this.Bytes, this.EndOfDirectiveToken, this.IsActive); public PragmaChecksumDirectiveTriviaSyntax WithChecksumKeyword(SyntaxToken checksumKeyword) => Update(this.HashToken, this.PragmaKeyword, checksumKeyword, this.File, this.Guid, this.Bytes, this.EndOfDirectiveToken, this.IsActive); public PragmaChecksumDirectiveTriviaSyntax WithFile(SyntaxToken file) => Update(this.HashToken, this.PragmaKeyword, this.ChecksumKeyword, file, this.Guid, this.Bytes, this.EndOfDirectiveToken, this.IsActive); public PragmaChecksumDirectiveTriviaSyntax WithGuid(SyntaxToken guid) => Update(this.HashToken, this.PragmaKeyword, this.ChecksumKeyword, this.File, guid, this.Bytes, this.EndOfDirectiveToken, this.IsActive); public PragmaChecksumDirectiveTriviaSyntax WithBytes(SyntaxToken bytes) => Update(this.HashToken, this.PragmaKeyword, this.ChecksumKeyword, this.File, this.Guid, bytes, this.EndOfDirectiveToken, this.IsActive); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new PragmaChecksumDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.PragmaKeyword, this.ChecksumKeyword, this.File, this.Guid, this.Bytes, endOfDirectiveToken, this.IsActive); public PragmaChecksumDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.PragmaKeyword, this.ChecksumKeyword, this.File, this.Guid, this.Bytes, this.EndOfDirectiveToken, isActive); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ReferenceDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class ReferenceDirectiveTriviaSyntax : DirectiveTriviaSyntax { internal ReferenceDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ReferenceDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public SyntaxToken ReferenceKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ReferenceDirectiveTriviaSyntax)this.Green).referenceKeyword, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken File => new SyntaxToken(this, ((Syntax.InternalSyntax.ReferenceDirectiveTriviaSyntax)this.Green).file, GetChildPosition(2), GetChildIndex(2)); public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ReferenceDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(3), GetChildIndex(3)); public override bool IsActive => ((Syntax.InternalSyntax.ReferenceDirectiveTriviaSyntax)this.Green).IsActive; internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitReferenceDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitReferenceDirectiveTrivia(this); public ReferenceDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken referenceKeyword, SyntaxToken file, SyntaxToken endOfDirectiveToken, bool isActive) { if (hashToken != this.HashToken || referenceKeyword != this.ReferenceKeyword || file != this.File || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.ReferenceDirectiveTrivia(hashToken, referenceKeyword, file, endOfDirectiveToken, isActive); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new ReferenceDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.ReferenceKeyword, this.File, this.EndOfDirectiveToken, this.IsActive); public ReferenceDirectiveTriviaSyntax WithReferenceKeyword(SyntaxToken referenceKeyword) => Update(this.HashToken, referenceKeyword, this.File, this.EndOfDirectiveToken, this.IsActive); public ReferenceDirectiveTriviaSyntax WithFile(SyntaxToken file) => Update(this.HashToken, this.ReferenceKeyword, file, this.EndOfDirectiveToken, this.IsActive); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new ReferenceDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.ReferenceKeyword, this.File, endOfDirectiveToken, this.IsActive); public ReferenceDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.ReferenceKeyword, this.File, this.EndOfDirectiveToken, isActive); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.LoadDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class LoadDirectiveTriviaSyntax : DirectiveTriviaSyntax { internal LoadDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.LoadDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public SyntaxToken LoadKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.LoadDirectiveTriviaSyntax)this.Green).loadKeyword, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken File => new SyntaxToken(this, ((Syntax.InternalSyntax.LoadDirectiveTriviaSyntax)this.Green).file, GetChildPosition(2), GetChildIndex(2)); public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.LoadDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(3), GetChildIndex(3)); public override bool IsActive => ((Syntax.InternalSyntax.LoadDirectiveTriviaSyntax)this.Green).IsActive; internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitLoadDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitLoadDirectiveTrivia(this); public LoadDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken loadKeyword, SyntaxToken file, SyntaxToken endOfDirectiveToken, bool isActive) { if (hashToken != this.HashToken || loadKeyword != this.LoadKeyword || file != this.File || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.LoadDirectiveTrivia(hashToken, loadKeyword, file, endOfDirectiveToken, isActive); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new LoadDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.LoadKeyword, this.File, this.EndOfDirectiveToken, this.IsActive); public LoadDirectiveTriviaSyntax WithLoadKeyword(SyntaxToken loadKeyword) => Update(this.HashToken, loadKeyword, this.File, this.EndOfDirectiveToken, this.IsActive); public LoadDirectiveTriviaSyntax WithFile(SyntaxToken file) => Update(this.HashToken, this.LoadKeyword, file, this.EndOfDirectiveToken, this.IsActive); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new LoadDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.LoadKeyword, this.File, endOfDirectiveToken, this.IsActive); public LoadDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.LoadKeyword, this.File, this.EndOfDirectiveToken, isActive); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ShebangDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class ShebangDirectiveTriviaSyntax : DirectiveTriviaSyntax { internal ShebangDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ShebangDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public SyntaxToken ExclamationToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ShebangDirectiveTriviaSyntax)this.Green).exclamationToken, GetChildPosition(1), GetChildIndex(1)); public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ShebangDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(2), GetChildIndex(2)); public override bool IsActive => ((Syntax.InternalSyntax.ShebangDirectiveTriviaSyntax)this.Green).IsActive; internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitShebangDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitShebangDirectiveTrivia(this); public ShebangDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken exclamationToken, SyntaxToken endOfDirectiveToken, bool isActive) { if (hashToken != this.HashToken || exclamationToken != this.ExclamationToken || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.ShebangDirectiveTrivia(hashToken, exclamationToken, endOfDirectiveToken, isActive); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new ShebangDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.ExclamationToken, this.EndOfDirectiveToken, this.IsActive); public ShebangDirectiveTriviaSyntax WithExclamationToken(SyntaxToken exclamationToken) => Update(this.HashToken, exclamationToken, this.EndOfDirectiveToken, this.IsActive); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new ShebangDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.ExclamationToken, endOfDirectiveToken, this.IsActive); public ShebangDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.ExclamationToken, this.EndOfDirectiveToken, isActive); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.NullableDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class NullableDirectiveTriviaSyntax : DirectiveTriviaSyntax { internal NullableDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.NullableDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public SyntaxToken NullableKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.NullableDirectiveTriviaSyntax)this.Green).nullableKeyword, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken SettingToken => new SyntaxToken(this, ((Syntax.InternalSyntax.NullableDirectiveTriviaSyntax)this.Green).settingToken, GetChildPosition(2), GetChildIndex(2)); public SyntaxToken TargetToken { get { var slot = ((Syntax.InternalSyntax.NullableDirectiveTriviaSyntax)this.Green).targetToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(3), GetChildIndex(3)) : default; } } public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.NullableDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(4), GetChildIndex(4)); public override bool IsActive => ((Syntax.InternalSyntax.NullableDirectiveTriviaSyntax)this.Green).IsActive; internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitNullableDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitNullableDirectiveTrivia(this); public NullableDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken nullableKeyword, SyntaxToken settingToken, SyntaxToken targetToken, SyntaxToken endOfDirectiveToken, bool isActive) { if (hashToken != this.HashToken || nullableKeyword != this.NullableKeyword || settingToken != this.SettingToken || targetToken != this.TargetToken || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.NullableDirectiveTrivia(hashToken, nullableKeyword, settingToken, targetToken, endOfDirectiveToken, isActive); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new NullableDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.NullableKeyword, this.SettingToken, this.TargetToken, this.EndOfDirectiveToken, this.IsActive); public NullableDirectiveTriviaSyntax WithNullableKeyword(SyntaxToken nullableKeyword) => Update(this.HashToken, nullableKeyword, this.SettingToken, this.TargetToken, this.EndOfDirectiveToken, this.IsActive); public NullableDirectiveTriviaSyntax WithSettingToken(SyntaxToken settingToken) => Update(this.HashToken, this.NullableKeyword, settingToken, this.TargetToken, this.EndOfDirectiveToken, this.IsActive); public NullableDirectiveTriviaSyntax WithTargetToken(SyntaxToken targetToken) => Update(this.HashToken, this.NullableKeyword, this.SettingToken, targetToken, this.EndOfDirectiveToken, this.IsActive); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new NullableDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.NullableKeyword, this.SettingToken, this.TargetToken, endOfDirectiveToken, this.IsActive); public NullableDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.NullableKeyword, this.SettingToken, this.TargetToken, this.EndOfDirectiveToken, isActive); } }
// <auto-generated /> #nullable enable using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.Syntax.InternalSyntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Syntax { /// <summary>Provides the base class from which the classes that represent name syntax nodes are derived. This is an abstract class.</summary> public abstract partial class NameSyntax : TypeSyntax { internal NameSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } } /// <summary>Provides the base class from which the classes that represent simple name syntax nodes are derived. This is an abstract class.</summary> public abstract partial class SimpleNameSyntax : NameSyntax { internal SimpleNameSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the identifier of the simple name.</summary> public abstract SyntaxToken Identifier { get; } public SimpleNameSyntax WithIdentifier(SyntaxToken identifier) => WithIdentifierCore(identifier); internal abstract SimpleNameSyntax WithIdentifierCore(SyntaxToken identifier); } /// <summary>Class which represents the syntax node for identifier name.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.IdentifierName"/></description></item> /// </list> /// </remarks> public sealed partial class IdentifierNameSyntax : SimpleNameSyntax { internal IdentifierNameSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the keyword for the kind of the identifier name.</summary> public override SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.IdentifierNameSyntax)this.Green).identifier, Position, 0); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitIdentifierName(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitIdentifierName(this); public IdentifierNameSyntax Update(SyntaxToken identifier) { if (identifier != this.Identifier) { var newNode = SyntaxFactory.IdentifierName(identifier); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override SimpleNameSyntax WithIdentifierCore(SyntaxToken identifier) => WithIdentifier(identifier); public new IdentifierNameSyntax WithIdentifier(SyntaxToken identifier) => Update(identifier); } /// <summary>Class which represents the syntax node for qualified name.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.QualifiedName"/></description></item> /// </list> /// </remarks> public sealed partial class QualifiedNameSyntax : NameSyntax { private NameSyntax? left; private SimpleNameSyntax? right; internal QualifiedNameSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>NameSyntax node representing the name on the left side of the dot token of the qualified name.</summary> public NameSyntax Left => GetRedAtZero(ref this.left)!; /// <summary>SyntaxToken representing the dot.</summary> public SyntaxToken DotToken => new SyntaxToken(this, ((Syntax.InternalSyntax.QualifiedNameSyntax)this.Green).dotToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>SimpleNameSyntax node representing the name on the right side of the dot token of the qualified name.</summary> public SimpleNameSyntax Right => GetRed(ref this.right, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.left)!, 2 => GetRed(ref this.right, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.left, 2 => this.right, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitQualifiedName(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitQualifiedName(this); public QualifiedNameSyntax Update(NameSyntax left, SyntaxToken dotToken, SimpleNameSyntax right) { if (left != this.Left || dotToken != this.DotToken || right != this.Right) { var newNode = SyntaxFactory.QualifiedName(left, dotToken, right); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public QualifiedNameSyntax WithLeft(NameSyntax left) => Update(left, this.DotToken, this.Right); public QualifiedNameSyntax WithDotToken(SyntaxToken dotToken) => Update(this.Left, dotToken, this.Right); public QualifiedNameSyntax WithRight(SimpleNameSyntax right) => Update(this.Left, this.DotToken, right); } /// <summary>Class which represents the syntax node for generic name.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.GenericName"/></description></item> /// </list> /// </remarks> public sealed partial class GenericNameSyntax : SimpleNameSyntax { private TypeArgumentListSyntax? typeArgumentList; internal GenericNameSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the name of the identifier of the generic name.</summary> public override SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.GenericNameSyntax)this.Green).identifier, Position, 0); /// <summary>TypeArgumentListSyntax node representing the list of type arguments of the generic name.</summary> public TypeArgumentListSyntax TypeArgumentList => GetRed(ref this.typeArgumentList, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.typeArgumentList, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.typeArgumentList : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitGenericName(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitGenericName(this); public GenericNameSyntax Update(SyntaxToken identifier, TypeArgumentListSyntax typeArgumentList) { if (identifier != this.Identifier || typeArgumentList != this.TypeArgumentList) { var newNode = SyntaxFactory.GenericName(identifier, typeArgumentList); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override SimpleNameSyntax WithIdentifierCore(SyntaxToken identifier) => WithIdentifier(identifier); public new GenericNameSyntax WithIdentifier(SyntaxToken identifier) => Update(identifier, this.TypeArgumentList); public GenericNameSyntax WithTypeArgumentList(TypeArgumentListSyntax typeArgumentList) => Update(this.Identifier, typeArgumentList); public GenericNameSyntax AddTypeArgumentListArguments(params TypeSyntax[] items) => WithTypeArgumentList(this.TypeArgumentList.WithArguments(this.TypeArgumentList.Arguments.AddRange(items))); } /// <summary>Class which represents the syntax node for type argument list.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.TypeArgumentList"/></description></item> /// </list> /// </remarks> public sealed partial class TypeArgumentListSyntax : CSharpSyntaxNode { private SyntaxNode? arguments; internal TypeArgumentListSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing less than.</summary> public SyntaxToken LessThanToken => new SyntaxToken(this, ((Syntax.InternalSyntax.TypeArgumentListSyntax)this.Green).lessThanToken, Position, 0); /// <summary>SeparatedSyntaxList of TypeSyntax node representing the type arguments.</summary> public SeparatedSyntaxList<TypeSyntax> Arguments { get { var red = GetRed(ref this.arguments, 1); return red != null ? new SeparatedSyntaxList<TypeSyntax>(red, GetChildIndex(1)) : default; } } /// <summary>SyntaxToken representing greater than.</summary> public SyntaxToken GreaterThanToken => new SyntaxToken(this, ((Syntax.InternalSyntax.TypeArgumentListSyntax)this.Green).greaterThanToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.arguments, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.arguments : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitTypeArgumentList(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitTypeArgumentList(this); public TypeArgumentListSyntax Update(SyntaxToken lessThanToken, SeparatedSyntaxList<TypeSyntax> arguments, SyntaxToken greaterThanToken) { if (lessThanToken != this.LessThanToken || arguments != this.Arguments || greaterThanToken != this.GreaterThanToken) { var newNode = SyntaxFactory.TypeArgumentList(lessThanToken, arguments, greaterThanToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public TypeArgumentListSyntax WithLessThanToken(SyntaxToken lessThanToken) => Update(lessThanToken, this.Arguments, this.GreaterThanToken); public TypeArgumentListSyntax WithArguments(SeparatedSyntaxList<TypeSyntax> arguments) => Update(this.LessThanToken, arguments, this.GreaterThanToken); public TypeArgumentListSyntax WithGreaterThanToken(SyntaxToken greaterThanToken) => Update(this.LessThanToken, this.Arguments, greaterThanToken); public TypeArgumentListSyntax AddArguments(params TypeSyntax[] items) => WithArguments(this.Arguments.AddRange(items)); } /// <summary>Class which represents the syntax node for alias qualified name.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.AliasQualifiedName"/></description></item> /// </list> /// </remarks> public sealed partial class AliasQualifiedNameSyntax : NameSyntax { private IdentifierNameSyntax? alias; private SimpleNameSyntax? name; internal AliasQualifiedNameSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>IdentifierNameSyntax node representing the name of the alias</summary> public IdentifierNameSyntax Alias => GetRedAtZero(ref this.alias)!; /// <summary>SyntaxToken representing colon colon.</summary> public SyntaxToken ColonColonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.AliasQualifiedNameSyntax)this.Green).colonColonToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>SimpleNameSyntax node representing the name that is being alias qualified.</summary> public SimpleNameSyntax Name => GetRed(ref this.name, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.alias)!, 2 => GetRed(ref this.name, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.alias, 2 => this.name, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitAliasQualifiedName(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitAliasQualifiedName(this); public AliasQualifiedNameSyntax Update(IdentifierNameSyntax alias, SyntaxToken colonColonToken, SimpleNameSyntax name) { if (alias != this.Alias || colonColonToken != this.ColonColonToken || name != this.Name) { var newNode = SyntaxFactory.AliasQualifiedName(alias, colonColonToken, name); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public AliasQualifiedNameSyntax WithAlias(IdentifierNameSyntax alias) => Update(alias, this.ColonColonToken, this.Name); public AliasQualifiedNameSyntax WithColonColonToken(SyntaxToken colonColonToken) => Update(this.Alias, colonColonToken, this.Name); public AliasQualifiedNameSyntax WithName(SimpleNameSyntax name) => Update(this.Alias, this.ColonColonToken, name); } /// <summary>Provides the base class from which the classes that represent type syntax nodes are derived. This is an abstract class.</summary> public abstract partial class TypeSyntax : ExpressionSyntax { internal TypeSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } } /// <summary>Class which represents the syntax node for predefined types.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.PredefinedType"/></description></item> /// </list> /// </remarks> public sealed partial class PredefinedTypeSyntax : TypeSyntax { internal PredefinedTypeSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken which represents the keyword corresponding to the predefined type.</summary> public SyntaxToken Keyword => new SyntaxToken(this, ((Syntax.InternalSyntax.PredefinedTypeSyntax)this.Green).keyword, Position, 0); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitPredefinedType(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitPredefinedType(this); public PredefinedTypeSyntax Update(SyntaxToken keyword) { if (keyword != this.Keyword) { var newNode = SyntaxFactory.PredefinedType(keyword); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public PredefinedTypeSyntax WithKeyword(SyntaxToken keyword) => Update(keyword); } /// <summary>Class which represents the syntax node for the array type.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ArrayType"/></description></item> /// </list> /// </remarks> public sealed partial class ArrayTypeSyntax : TypeSyntax { private TypeSyntax? elementType; private SyntaxNode? rankSpecifiers; internal ArrayTypeSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>TypeSyntax node representing the type of the element of the array.</summary> public TypeSyntax ElementType => GetRedAtZero(ref this.elementType)!; /// <summary>SyntaxList of ArrayRankSpecifierSyntax nodes representing the list of rank specifiers for the array.</summary> public SyntaxList<ArrayRankSpecifierSyntax> RankSpecifiers => new SyntaxList<ArrayRankSpecifierSyntax>(GetRed(ref this.rankSpecifiers, 1)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.elementType)!, 1 => GetRed(ref this.rankSpecifiers, 1)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.elementType, 1 => this.rankSpecifiers, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitArrayType(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitArrayType(this); public ArrayTypeSyntax Update(TypeSyntax elementType, SyntaxList<ArrayRankSpecifierSyntax> rankSpecifiers) { if (elementType != this.ElementType || rankSpecifiers != this.RankSpecifiers) { var newNode = SyntaxFactory.ArrayType(elementType, rankSpecifiers); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ArrayTypeSyntax WithElementType(TypeSyntax elementType) => Update(elementType, this.RankSpecifiers); public ArrayTypeSyntax WithRankSpecifiers(SyntaxList<ArrayRankSpecifierSyntax> rankSpecifiers) => Update(this.ElementType, rankSpecifiers); public ArrayTypeSyntax AddRankSpecifiers(params ArrayRankSpecifierSyntax[] items) => WithRankSpecifiers(this.RankSpecifiers.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ArrayRankSpecifier"/></description></item> /// </list> /// </remarks> public sealed partial class ArrayRankSpecifierSyntax : CSharpSyntaxNode { private SyntaxNode? sizes; internal ArrayRankSpecifierSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken OpenBracketToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ArrayRankSpecifierSyntax)this.Green).openBracketToken, Position, 0); public SeparatedSyntaxList<ExpressionSyntax> Sizes { get { var red = GetRed(ref this.sizes, 1); return red != null ? new SeparatedSyntaxList<ExpressionSyntax>(red, GetChildIndex(1)) : default; } } public SyntaxToken CloseBracketToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ArrayRankSpecifierSyntax)this.Green).closeBracketToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.sizes, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.sizes : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitArrayRankSpecifier(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitArrayRankSpecifier(this); public ArrayRankSpecifierSyntax Update(SyntaxToken openBracketToken, SeparatedSyntaxList<ExpressionSyntax> sizes, SyntaxToken closeBracketToken) { if (openBracketToken != this.OpenBracketToken || sizes != this.Sizes || closeBracketToken != this.CloseBracketToken) { var newNode = SyntaxFactory.ArrayRankSpecifier(openBracketToken, sizes, closeBracketToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ArrayRankSpecifierSyntax WithOpenBracketToken(SyntaxToken openBracketToken) => Update(openBracketToken, this.Sizes, this.CloseBracketToken); public ArrayRankSpecifierSyntax WithSizes(SeparatedSyntaxList<ExpressionSyntax> sizes) => Update(this.OpenBracketToken, sizes, this.CloseBracketToken); public ArrayRankSpecifierSyntax WithCloseBracketToken(SyntaxToken closeBracketToken) => Update(this.OpenBracketToken, this.Sizes, closeBracketToken); public ArrayRankSpecifierSyntax AddSizes(params ExpressionSyntax[] items) => WithSizes(this.Sizes.AddRange(items)); } /// <summary>Class which represents the syntax node for pointer type.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.PointerType"/></description></item> /// </list> /// </remarks> public sealed partial class PointerTypeSyntax : TypeSyntax { private TypeSyntax? elementType; internal PointerTypeSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>TypeSyntax node that represents the element type of the pointer.</summary> public TypeSyntax ElementType => GetRedAtZero(ref this.elementType)!; /// <summary>SyntaxToken representing the asterisk.</summary> public SyntaxToken AsteriskToken => new SyntaxToken(this, ((Syntax.InternalSyntax.PointerTypeSyntax)this.Green).asteriskToken, GetChildPosition(1), GetChildIndex(1)); internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.elementType)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.elementType : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitPointerType(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitPointerType(this); public PointerTypeSyntax Update(TypeSyntax elementType, SyntaxToken asteriskToken) { if (elementType != this.ElementType || asteriskToken != this.AsteriskToken) { var newNode = SyntaxFactory.PointerType(elementType, asteriskToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public PointerTypeSyntax WithElementType(TypeSyntax elementType) => Update(elementType, this.AsteriskToken); public PointerTypeSyntax WithAsteriskToken(SyntaxToken asteriskToken) => Update(this.ElementType, asteriskToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.FunctionPointerType"/></description></item> /// </list> /// </remarks> public sealed partial class FunctionPointerTypeSyntax : TypeSyntax { private FunctionPointerCallingConventionSyntax? callingConvention; private FunctionPointerParameterListSyntax? parameterList; internal FunctionPointerTypeSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the delegate keyword.</summary> public SyntaxToken DelegateKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.FunctionPointerTypeSyntax)this.Green).delegateKeyword, Position, 0); /// <summary>SyntaxToken representing the asterisk.</summary> public SyntaxToken AsteriskToken => new SyntaxToken(this, ((Syntax.InternalSyntax.FunctionPointerTypeSyntax)this.Green).asteriskToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>Node representing the optional calling convention.</summary> public FunctionPointerCallingConventionSyntax? CallingConvention => GetRed(ref this.callingConvention, 2); /// <summary>List of the parameter types and return type of the function pointer.</summary> public FunctionPointerParameterListSyntax ParameterList => GetRed(ref this.parameterList, 3)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 2 => GetRed(ref this.callingConvention, 2), 3 => GetRed(ref this.parameterList, 3)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 2 => this.callingConvention, 3 => this.parameterList, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitFunctionPointerType(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitFunctionPointerType(this); public FunctionPointerTypeSyntax Update(SyntaxToken delegateKeyword, SyntaxToken asteriskToken, FunctionPointerCallingConventionSyntax? callingConvention, FunctionPointerParameterListSyntax parameterList) { if (delegateKeyword != this.DelegateKeyword || asteriskToken != this.AsteriskToken || callingConvention != this.CallingConvention || parameterList != this.ParameterList) { var newNode = SyntaxFactory.FunctionPointerType(delegateKeyword, asteriskToken, callingConvention, parameterList); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public FunctionPointerTypeSyntax WithDelegateKeyword(SyntaxToken delegateKeyword) => Update(delegateKeyword, this.AsteriskToken, this.CallingConvention, this.ParameterList); public FunctionPointerTypeSyntax WithAsteriskToken(SyntaxToken asteriskToken) => Update(this.DelegateKeyword, asteriskToken, this.CallingConvention, this.ParameterList); public FunctionPointerTypeSyntax WithCallingConvention(FunctionPointerCallingConventionSyntax? callingConvention) => Update(this.DelegateKeyword, this.AsteriskToken, callingConvention, this.ParameterList); public FunctionPointerTypeSyntax WithParameterList(FunctionPointerParameterListSyntax parameterList) => Update(this.DelegateKeyword, this.AsteriskToken, this.CallingConvention, parameterList); public FunctionPointerTypeSyntax AddParameterListParameters(params FunctionPointerParameterSyntax[] items) => WithParameterList(this.ParameterList.WithParameters(this.ParameterList.Parameters.AddRange(items))); } /// <summary>Function pointer parameter list syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.FunctionPointerParameterList"/></description></item> /// </list> /// </remarks> public sealed partial class FunctionPointerParameterListSyntax : CSharpSyntaxNode { private SyntaxNode? parameters; internal FunctionPointerParameterListSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the less than token.</summary> public SyntaxToken LessThanToken => new SyntaxToken(this, ((Syntax.InternalSyntax.FunctionPointerParameterListSyntax)this.Green).lessThanToken, Position, 0); /// <summary>SeparatedSyntaxList of ParameterSyntaxes representing the list of parameters and return type.</summary> public SeparatedSyntaxList<FunctionPointerParameterSyntax> Parameters { get { var red = GetRed(ref this.parameters, 1); return red != null ? new SeparatedSyntaxList<FunctionPointerParameterSyntax>(red, GetChildIndex(1)) : default; } } /// <summary>SyntaxToken representing the greater than token.</summary> public SyntaxToken GreaterThanToken => new SyntaxToken(this, ((Syntax.InternalSyntax.FunctionPointerParameterListSyntax)this.Green).greaterThanToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.parameters, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.parameters : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitFunctionPointerParameterList(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitFunctionPointerParameterList(this); public FunctionPointerParameterListSyntax Update(SyntaxToken lessThanToken, SeparatedSyntaxList<FunctionPointerParameterSyntax> parameters, SyntaxToken greaterThanToken) { if (lessThanToken != this.LessThanToken || parameters != this.Parameters || greaterThanToken != this.GreaterThanToken) { var newNode = SyntaxFactory.FunctionPointerParameterList(lessThanToken, parameters, greaterThanToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public FunctionPointerParameterListSyntax WithLessThanToken(SyntaxToken lessThanToken) => Update(lessThanToken, this.Parameters, this.GreaterThanToken); public FunctionPointerParameterListSyntax WithParameters(SeparatedSyntaxList<FunctionPointerParameterSyntax> parameters) => Update(this.LessThanToken, parameters, this.GreaterThanToken); public FunctionPointerParameterListSyntax WithGreaterThanToken(SyntaxToken greaterThanToken) => Update(this.LessThanToken, this.Parameters, greaterThanToken); public FunctionPointerParameterListSyntax AddParameters(params FunctionPointerParameterSyntax[] items) => WithParameters(this.Parameters.AddRange(items)); } /// <summary>Function pointer calling convention syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.FunctionPointerCallingConvention"/></description></item> /// </list> /// </remarks> public sealed partial class FunctionPointerCallingConventionSyntax : CSharpSyntaxNode { private FunctionPointerUnmanagedCallingConventionListSyntax? unmanagedCallingConventionList; internal FunctionPointerCallingConventionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing whether the calling convention is managed or unmanaged.</summary> public SyntaxToken ManagedOrUnmanagedKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.FunctionPointerCallingConventionSyntax)this.Green).managedOrUnmanagedKeyword, Position, 0); /// <summary>Optional list of identifiers that will contribute to an unmanaged calling convention.</summary> public FunctionPointerUnmanagedCallingConventionListSyntax? UnmanagedCallingConventionList => GetRed(ref this.unmanagedCallingConventionList, 1); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.unmanagedCallingConventionList, 1) : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.unmanagedCallingConventionList : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitFunctionPointerCallingConvention(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitFunctionPointerCallingConvention(this); public FunctionPointerCallingConventionSyntax Update(SyntaxToken managedOrUnmanagedKeyword, FunctionPointerUnmanagedCallingConventionListSyntax? unmanagedCallingConventionList) { if (managedOrUnmanagedKeyword != this.ManagedOrUnmanagedKeyword || unmanagedCallingConventionList != this.UnmanagedCallingConventionList) { var newNode = SyntaxFactory.FunctionPointerCallingConvention(managedOrUnmanagedKeyword, unmanagedCallingConventionList); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public FunctionPointerCallingConventionSyntax WithManagedOrUnmanagedKeyword(SyntaxToken managedOrUnmanagedKeyword) => Update(managedOrUnmanagedKeyword, this.UnmanagedCallingConventionList); public FunctionPointerCallingConventionSyntax WithUnmanagedCallingConventionList(FunctionPointerUnmanagedCallingConventionListSyntax? unmanagedCallingConventionList) => Update(this.ManagedOrUnmanagedKeyword, unmanagedCallingConventionList); public FunctionPointerCallingConventionSyntax AddUnmanagedCallingConventionListCallingConventions(params FunctionPointerUnmanagedCallingConventionSyntax[] items) { var unmanagedCallingConventionList = this.UnmanagedCallingConventionList ?? SyntaxFactory.FunctionPointerUnmanagedCallingConventionList(); return WithUnmanagedCallingConventionList(unmanagedCallingConventionList.WithCallingConventions(unmanagedCallingConventionList.CallingConventions.AddRange(items))); } } /// <summary>Function pointer calling convention syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.FunctionPointerUnmanagedCallingConventionList"/></description></item> /// </list> /// </remarks> public sealed partial class FunctionPointerUnmanagedCallingConventionListSyntax : CSharpSyntaxNode { private SyntaxNode? callingConventions; internal FunctionPointerUnmanagedCallingConventionListSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing open bracket.</summary> public SyntaxToken OpenBracketToken => new SyntaxToken(this, ((Syntax.InternalSyntax.FunctionPointerUnmanagedCallingConventionListSyntax)this.Green).openBracketToken, Position, 0); /// <summary>SeparatedSyntaxList of calling convention identifiers.</summary> public SeparatedSyntaxList<FunctionPointerUnmanagedCallingConventionSyntax> CallingConventions { get { var red = GetRed(ref this.callingConventions, 1); return red != null ? new SeparatedSyntaxList<FunctionPointerUnmanagedCallingConventionSyntax>(red, GetChildIndex(1)) : default; } } /// <summary>SyntaxToken representing close bracket.</summary> public SyntaxToken CloseBracketToken => new SyntaxToken(this, ((Syntax.InternalSyntax.FunctionPointerUnmanagedCallingConventionListSyntax)this.Green).closeBracketToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.callingConventions, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.callingConventions : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitFunctionPointerUnmanagedCallingConventionList(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitFunctionPointerUnmanagedCallingConventionList(this); public FunctionPointerUnmanagedCallingConventionListSyntax Update(SyntaxToken openBracketToken, SeparatedSyntaxList<FunctionPointerUnmanagedCallingConventionSyntax> callingConventions, SyntaxToken closeBracketToken) { if (openBracketToken != this.OpenBracketToken || callingConventions != this.CallingConventions || closeBracketToken != this.CloseBracketToken) { var newNode = SyntaxFactory.FunctionPointerUnmanagedCallingConventionList(openBracketToken, callingConventions, closeBracketToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public FunctionPointerUnmanagedCallingConventionListSyntax WithOpenBracketToken(SyntaxToken openBracketToken) => Update(openBracketToken, this.CallingConventions, this.CloseBracketToken); public FunctionPointerUnmanagedCallingConventionListSyntax WithCallingConventions(SeparatedSyntaxList<FunctionPointerUnmanagedCallingConventionSyntax> callingConventions) => Update(this.OpenBracketToken, callingConventions, this.CloseBracketToken); public FunctionPointerUnmanagedCallingConventionListSyntax WithCloseBracketToken(SyntaxToken closeBracketToken) => Update(this.OpenBracketToken, this.CallingConventions, closeBracketToken); public FunctionPointerUnmanagedCallingConventionListSyntax AddCallingConventions(params FunctionPointerUnmanagedCallingConventionSyntax[] items) => WithCallingConventions(this.CallingConventions.AddRange(items)); } /// <summary>Individual function pointer unmanaged calling convention.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.FunctionPointerUnmanagedCallingConvention"/></description></item> /// </list> /// </remarks> public sealed partial class FunctionPointerUnmanagedCallingConventionSyntax : CSharpSyntaxNode { internal FunctionPointerUnmanagedCallingConventionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the calling convention identifier.</summary> public SyntaxToken Name => new SyntaxToken(this, ((Syntax.InternalSyntax.FunctionPointerUnmanagedCallingConventionSyntax)this.Green).name, Position, 0); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitFunctionPointerUnmanagedCallingConvention(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitFunctionPointerUnmanagedCallingConvention(this); public FunctionPointerUnmanagedCallingConventionSyntax Update(SyntaxToken name) { if (name != this.Name) { var newNode = SyntaxFactory.FunctionPointerUnmanagedCallingConvention(name); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public FunctionPointerUnmanagedCallingConventionSyntax WithName(SyntaxToken name) => Update(name); } /// <summary>Class which represents the syntax node for a nullable type.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.NullableType"/></description></item> /// </list> /// </remarks> public sealed partial class NullableTypeSyntax : TypeSyntax { private TypeSyntax? elementType; internal NullableTypeSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>TypeSyntax node representing the type of the element.</summary> public TypeSyntax ElementType => GetRedAtZero(ref this.elementType)!; /// <summary>SyntaxToken representing the question mark.</summary> public SyntaxToken QuestionToken => new SyntaxToken(this, ((Syntax.InternalSyntax.NullableTypeSyntax)this.Green).questionToken, GetChildPosition(1), GetChildIndex(1)); internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.elementType)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.elementType : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitNullableType(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitNullableType(this); public NullableTypeSyntax Update(TypeSyntax elementType, SyntaxToken questionToken) { if (elementType != this.ElementType || questionToken != this.QuestionToken) { var newNode = SyntaxFactory.NullableType(elementType, questionToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public NullableTypeSyntax WithElementType(TypeSyntax elementType) => Update(elementType, this.QuestionToken); public NullableTypeSyntax WithQuestionToken(SyntaxToken questionToken) => Update(this.ElementType, questionToken); } /// <summary>Class which represents the syntax node for tuple type.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.TupleType"/></description></item> /// </list> /// </remarks> public sealed partial class TupleTypeSyntax : TypeSyntax { private SyntaxNode? elements; internal TupleTypeSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the open parenthesis.</summary> public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.TupleTypeSyntax)this.Green).openParenToken, Position, 0); public SeparatedSyntaxList<TupleElementSyntax> Elements { get { var red = GetRed(ref this.elements, 1); return red != null ? new SeparatedSyntaxList<TupleElementSyntax>(red, GetChildIndex(1)) : default; } } /// <summary>SyntaxToken representing the close parenthesis.</summary> public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.TupleTypeSyntax)this.Green).closeParenToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.elements, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.elements : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitTupleType(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitTupleType(this); public TupleTypeSyntax Update(SyntaxToken openParenToken, SeparatedSyntaxList<TupleElementSyntax> elements, SyntaxToken closeParenToken) { if (openParenToken != this.OpenParenToken || elements != this.Elements || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.TupleType(openParenToken, elements, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public TupleTypeSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(openParenToken, this.Elements, this.CloseParenToken); public TupleTypeSyntax WithElements(SeparatedSyntaxList<TupleElementSyntax> elements) => Update(this.OpenParenToken, elements, this.CloseParenToken); public TupleTypeSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.OpenParenToken, this.Elements, closeParenToken); public TupleTypeSyntax AddElements(params TupleElementSyntax[] items) => WithElements(this.Elements.AddRange(items)); } /// <summary>Tuple type element.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.TupleElement"/></description></item> /// </list> /// </remarks> public sealed partial class TupleElementSyntax : CSharpSyntaxNode { private TypeSyntax? type; internal TupleElementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the type of the tuple element.</summary> public TypeSyntax Type => GetRedAtZero(ref this.type)!; /// <summary>Gets the name of the tuple element.</summary> public SyntaxToken Identifier { get { var slot = ((Syntax.InternalSyntax.TupleElementSyntax)this.Green).identifier; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.type)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.type : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitTupleElement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitTupleElement(this); public TupleElementSyntax Update(TypeSyntax type, SyntaxToken identifier) { if (type != this.Type || identifier != this.Identifier) { var newNode = SyntaxFactory.TupleElement(type, identifier); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public TupleElementSyntax WithType(TypeSyntax type) => Update(type, this.Identifier); public TupleElementSyntax WithIdentifier(SyntaxToken identifier) => Update(this.Type, identifier); } /// <summary>Class which represents a placeholder in the type argument list of an unbound generic type.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.OmittedTypeArgument"/></description></item> /// </list> /// </remarks> public sealed partial class OmittedTypeArgumentSyntax : TypeSyntax { internal OmittedTypeArgumentSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the omitted type argument.</summary> public SyntaxToken OmittedTypeArgumentToken => new SyntaxToken(this, ((Syntax.InternalSyntax.OmittedTypeArgumentSyntax)this.Green).omittedTypeArgumentToken, Position, 0); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitOmittedTypeArgument(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitOmittedTypeArgument(this); public OmittedTypeArgumentSyntax Update(SyntaxToken omittedTypeArgumentToken) { if (omittedTypeArgumentToken != this.OmittedTypeArgumentToken) { var newNode = SyntaxFactory.OmittedTypeArgument(omittedTypeArgumentToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public OmittedTypeArgumentSyntax WithOmittedTypeArgumentToken(SyntaxToken omittedTypeArgumentToken) => Update(omittedTypeArgumentToken); } /// <summary>The ref modifier of a method's return value or a local.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.RefType"/></description></item> /// </list> /// </remarks> public sealed partial class RefTypeSyntax : TypeSyntax { private TypeSyntax? type; internal RefTypeSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken RefKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.RefTypeSyntax)this.Green).refKeyword, Position, 0); /// <summary>Gets the optional "readonly" keyword.</summary> public SyntaxToken ReadOnlyKeyword { get { var slot = ((Syntax.InternalSyntax.RefTypeSyntax)this.Green).readOnlyKeyword; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public TypeSyntax Type => GetRed(ref this.type, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 2 ? GetRed(ref this.type, 2)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 2 ? this.type : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitRefType(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitRefType(this); public RefTypeSyntax Update(SyntaxToken refKeyword, SyntaxToken readOnlyKeyword, TypeSyntax type) { if (refKeyword != this.RefKeyword || readOnlyKeyword != this.ReadOnlyKeyword || type != this.Type) { var newNode = SyntaxFactory.RefType(refKeyword, readOnlyKeyword, type); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public RefTypeSyntax WithRefKeyword(SyntaxToken refKeyword) => Update(refKeyword, this.ReadOnlyKeyword, this.Type); public RefTypeSyntax WithReadOnlyKeyword(SyntaxToken readOnlyKeyword) => Update(this.RefKeyword, readOnlyKeyword, this.Type); public RefTypeSyntax WithType(TypeSyntax type) => Update(this.RefKeyword, this.ReadOnlyKeyword, type); } public abstract partial class ExpressionOrPatternSyntax : CSharpSyntaxNode { internal ExpressionOrPatternSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } } /// <summary>Provides the base class from which the classes that represent expression syntax nodes are derived. This is an abstract class.</summary> public abstract partial class ExpressionSyntax : ExpressionOrPatternSyntax { internal ExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } } /// <summary>Class which represents the syntax node for parenthesized expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ParenthesizedExpression"/></description></item> /// </list> /// </remarks> public sealed partial class ParenthesizedExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? expression; internal ParenthesizedExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the open parenthesis.</summary> public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ParenthesizedExpressionSyntax)this.Green).openParenToken, Position, 0); /// <summary>ExpressionSyntax node representing the expression enclosed within the parenthesis.</summary> public ExpressionSyntax Expression => GetRed(ref this.expression, 1)!; /// <summary>SyntaxToken representing the close parenthesis.</summary> public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ParenthesizedExpressionSyntax)this.Green).closeParenToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.expression, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.expression : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitParenthesizedExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitParenthesizedExpression(this); public ParenthesizedExpressionSyntax Update(SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken) { if (openParenToken != this.OpenParenToken || expression != this.Expression || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.ParenthesizedExpression(openParenToken, expression, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ParenthesizedExpressionSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(openParenToken, this.Expression, this.CloseParenToken); public ParenthesizedExpressionSyntax WithExpression(ExpressionSyntax expression) => Update(this.OpenParenToken, expression, this.CloseParenToken); public ParenthesizedExpressionSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.OpenParenToken, this.Expression, closeParenToken); } /// <summary>Class which represents the syntax node for tuple expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.TupleExpression"/></description></item> /// </list> /// </remarks> public sealed partial class TupleExpressionSyntax : ExpressionSyntax { private SyntaxNode? arguments; internal TupleExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the open parenthesis.</summary> public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.TupleExpressionSyntax)this.Green).openParenToken, Position, 0); /// <summary>SeparatedSyntaxList of ArgumentSyntax representing the list of arguments.</summary> public SeparatedSyntaxList<ArgumentSyntax> Arguments { get { var red = GetRed(ref this.arguments, 1); return red != null ? new SeparatedSyntaxList<ArgumentSyntax>(red, GetChildIndex(1)) : default; } } /// <summary>SyntaxToken representing the close parenthesis.</summary> public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.TupleExpressionSyntax)this.Green).closeParenToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.arguments, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.arguments : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitTupleExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitTupleExpression(this); public TupleExpressionSyntax Update(SyntaxToken openParenToken, SeparatedSyntaxList<ArgumentSyntax> arguments, SyntaxToken closeParenToken) { if (openParenToken != this.OpenParenToken || arguments != this.Arguments || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.TupleExpression(openParenToken, arguments, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public TupleExpressionSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(openParenToken, this.Arguments, this.CloseParenToken); public TupleExpressionSyntax WithArguments(SeparatedSyntaxList<ArgumentSyntax> arguments) => Update(this.OpenParenToken, arguments, this.CloseParenToken); public TupleExpressionSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.OpenParenToken, this.Arguments, closeParenToken); public TupleExpressionSyntax AddArguments(params ArgumentSyntax[] items) => WithArguments(this.Arguments.AddRange(items)); } /// <summary>Class which represents the syntax node for prefix unary expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.UnaryPlusExpression"/></description></item> /// <item><description><see cref="SyntaxKind.UnaryMinusExpression"/></description></item> /// <item><description><see cref="SyntaxKind.BitwiseNotExpression"/></description></item> /// <item><description><see cref="SyntaxKind.LogicalNotExpression"/></description></item> /// <item><description><see cref="SyntaxKind.PreIncrementExpression"/></description></item> /// <item><description><see cref="SyntaxKind.PreDecrementExpression"/></description></item> /// <item><description><see cref="SyntaxKind.AddressOfExpression"/></description></item> /// <item><description><see cref="SyntaxKind.PointerIndirectionExpression"/></description></item> /// <item><description><see cref="SyntaxKind.IndexExpression"/></description></item> /// </list> /// </remarks> public sealed partial class PrefixUnaryExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? operand; internal PrefixUnaryExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the kind of the operator of the prefix unary expression.</summary> public SyntaxToken OperatorToken => new SyntaxToken(this, ((Syntax.InternalSyntax.PrefixUnaryExpressionSyntax)this.Green).operatorToken, Position, 0); /// <summary>ExpressionSyntax representing the operand of the prefix unary expression.</summary> public ExpressionSyntax Operand => GetRed(ref this.operand, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.operand, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.operand : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitPrefixUnaryExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitPrefixUnaryExpression(this); public PrefixUnaryExpressionSyntax Update(SyntaxToken operatorToken, ExpressionSyntax operand) { if (operatorToken != this.OperatorToken || operand != this.Operand) { var newNode = SyntaxFactory.PrefixUnaryExpression(this.Kind(), operatorToken, operand); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public PrefixUnaryExpressionSyntax WithOperatorToken(SyntaxToken operatorToken) => Update(operatorToken, this.Operand); public PrefixUnaryExpressionSyntax WithOperand(ExpressionSyntax operand) => Update(this.OperatorToken, operand); } /// <summary>Class which represents the syntax node for an "await" expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.AwaitExpression"/></description></item> /// </list> /// </remarks> public sealed partial class AwaitExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? expression; internal AwaitExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the kind "await" keyword.</summary> public SyntaxToken AwaitKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.AwaitExpressionSyntax)this.Green).awaitKeyword, Position, 0); /// <summary>ExpressionSyntax representing the operand of the "await" operator.</summary> public ExpressionSyntax Expression => GetRed(ref this.expression, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.expression, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.expression : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitAwaitExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitAwaitExpression(this); public AwaitExpressionSyntax Update(SyntaxToken awaitKeyword, ExpressionSyntax expression) { if (awaitKeyword != this.AwaitKeyword || expression != this.Expression) { var newNode = SyntaxFactory.AwaitExpression(awaitKeyword, expression); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public AwaitExpressionSyntax WithAwaitKeyword(SyntaxToken awaitKeyword) => Update(awaitKeyword, this.Expression); public AwaitExpressionSyntax WithExpression(ExpressionSyntax expression) => Update(this.AwaitKeyword, expression); } /// <summary>Class which represents the syntax node for postfix unary expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.PostIncrementExpression"/></description></item> /// <item><description><see cref="SyntaxKind.PostDecrementExpression"/></description></item> /// <item><description><see cref="SyntaxKind.SuppressNullableWarningExpression"/></description></item> /// </list> /// </remarks> public sealed partial class PostfixUnaryExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? operand; internal PostfixUnaryExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>ExpressionSyntax representing the operand of the postfix unary expression.</summary> public ExpressionSyntax Operand => GetRedAtZero(ref this.operand)!; /// <summary>SyntaxToken representing the kind of the operator of the postfix unary expression.</summary> public SyntaxToken OperatorToken => new SyntaxToken(this, ((Syntax.InternalSyntax.PostfixUnaryExpressionSyntax)this.Green).operatorToken, GetChildPosition(1), GetChildIndex(1)); internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.operand)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.operand : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitPostfixUnaryExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitPostfixUnaryExpression(this); public PostfixUnaryExpressionSyntax Update(ExpressionSyntax operand, SyntaxToken operatorToken) { if (operand != this.Operand || operatorToken != this.OperatorToken) { var newNode = SyntaxFactory.PostfixUnaryExpression(this.Kind(), operand, operatorToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public PostfixUnaryExpressionSyntax WithOperand(ExpressionSyntax operand) => Update(operand, this.OperatorToken); public PostfixUnaryExpressionSyntax WithOperatorToken(SyntaxToken operatorToken) => Update(this.Operand, operatorToken); } /// <summary>Class which represents the syntax node for member access expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.SimpleMemberAccessExpression"/></description></item> /// <item><description><see cref="SyntaxKind.PointerMemberAccessExpression"/></description></item> /// </list> /// </remarks> public sealed partial class MemberAccessExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? expression; private SimpleNameSyntax? name; internal MemberAccessExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>ExpressionSyntax node representing the object that the member belongs to.</summary> public ExpressionSyntax Expression => GetRedAtZero(ref this.expression)!; /// <summary>SyntaxToken representing the kind of the operator in the member access expression.</summary> public SyntaxToken OperatorToken => new SyntaxToken(this, ((Syntax.InternalSyntax.MemberAccessExpressionSyntax)this.Green).operatorToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>SimpleNameSyntax node representing the member being accessed.</summary> public SimpleNameSyntax Name => GetRed(ref this.name, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.expression)!, 2 => GetRed(ref this.name, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.expression, 2 => this.name, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitMemberAccessExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitMemberAccessExpression(this); public MemberAccessExpressionSyntax Update(ExpressionSyntax expression, SyntaxToken operatorToken, SimpleNameSyntax name) { if (expression != this.Expression || operatorToken != this.OperatorToken || name != this.Name) { var newNode = SyntaxFactory.MemberAccessExpression(this.Kind(), expression, operatorToken, name); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public MemberAccessExpressionSyntax WithExpression(ExpressionSyntax expression) => Update(expression, this.OperatorToken, this.Name); public MemberAccessExpressionSyntax WithOperatorToken(SyntaxToken operatorToken) => Update(this.Expression, operatorToken, this.Name); public MemberAccessExpressionSyntax WithName(SimpleNameSyntax name) => Update(this.Expression, this.OperatorToken, name); } /// <summary>Class which represents the syntax node for conditional access expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ConditionalAccessExpression"/></description></item> /// </list> /// </remarks> public sealed partial class ConditionalAccessExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? expression; private ExpressionSyntax? whenNotNull; internal ConditionalAccessExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>ExpressionSyntax node representing the object conditionally accessed.</summary> public ExpressionSyntax Expression => GetRedAtZero(ref this.expression)!; /// <summary>SyntaxToken representing the question mark.</summary> public SyntaxToken OperatorToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ConditionalAccessExpressionSyntax)this.Green).operatorToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>ExpressionSyntax node representing the access expression to be executed when the object is not null.</summary> public ExpressionSyntax WhenNotNull => GetRed(ref this.whenNotNull, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.expression)!, 2 => GetRed(ref this.whenNotNull, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.expression, 2 => this.whenNotNull, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitConditionalAccessExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitConditionalAccessExpression(this); public ConditionalAccessExpressionSyntax Update(ExpressionSyntax expression, SyntaxToken operatorToken, ExpressionSyntax whenNotNull) { if (expression != this.Expression || operatorToken != this.OperatorToken || whenNotNull != this.WhenNotNull) { var newNode = SyntaxFactory.ConditionalAccessExpression(expression, operatorToken, whenNotNull); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ConditionalAccessExpressionSyntax WithExpression(ExpressionSyntax expression) => Update(expression, this.OperatorToken, this.WhenNotNull); public ConditionalAccessExpressionSyntax WithOperatorToken(SyntaxToken operatorToken) => Update(this.Expression, operatorToken, this.WhenNotNull); public ConditionalAccessExpressionSyntax WithWhenNotNull(ExpressionSyntax whenNotNull) => Update(this.Expression, this.OperatorToken, whenNotNull); } /// <summary>Class which represents the syntax node for member binding expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.MemberBindingExpression"/></description></item> /// </list> /// </remarks> public sealed partial class MemberBindingExpressionSyntax : ExpressionSyntax { private SimpleNameSyntax? name; internal MemberBindingExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing dot.</summary> public SyntaxToken OperatorToken => new SyntaxToken(this, ((Syntax.InternalSyntax.MemberBindingExpressionSyntax)this.Green).operatorToken, Position, 0); /// <summary>SimpleNameSyntax node representing the member being bound to.</summary> public SimpleNameSyntax Name => GetRed(ref this.name, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.name, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.name : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitMemberBindingExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitMemberBindingExpression(this); public MemberBindingExpressionSyntax Update(SyntaxToken operatorToken, SimpleNameSyntax name) { if (operatorToken != this.OperatorToken || name != this.Name) { var newNode = SyntaxFactory.MemberBindingExpression(operatorToken, name); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public MemberBindingExpressionSyntax WithOperatorToken(SyntaxToken operatorToken) => Update(operatorToken, this.Name); public MemberBindingExpressionSyntax WithName(SimpleNameSyntax name) => Update(this.OperatorToken, name); } /// <summary>Class which represents the syntax node for element binding expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ElementBindingExpression"/></description></item> /// </list> /// </remarks> public sealed partial class ElementBindingExpressionSyntax : ExpressionSyntax { private BracketedArgumentListSyntax? argumentList; internal ElementBindingExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>BracketedArgumentListSyntax node representing the list of arguments of the element binding expression.</summary> public BracketedArgumentListSyntax ArgumentList => GetRedAtZero(ref this.argumentList)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.argumentList)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.argumentList : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitElementBindingExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitElementBindingExpression(this); public ElementBindingExpressionSyntax Update(BracketedArgumentListSyntax argumentList) { if (argumentList != this.ArgumentList) { var newNode = SyntaxFactory.ElementBindingExpression(argumentList); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ElementBindingExpressionSyntax WithArgumentList(BracketedArgumentListSyntax argumentList) => Update(argumentList); public ElementBindingExpressionSyntax AddArgumentListArguments(params ArgumentSyntax[] items) => WithArgumentList(this.ArgumentList.WithArguments(this.ArgumentList.Arguments.AddRange(items))); } /// <summary>Class which represents the syntax node for a range expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.RangeExpression"/></description></item> /// </list> /// </remarks> public sealed partial class RangeExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? leftOperand; private ExpressionSyntax? rightOperand; internal RangeExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>ExpressionSyntax node representing the expression on the left of the range operator.</summary> public ExpressionSyntax? LeftOperand => GetRedAtZero(ref this.leftOperand); /// <summary>SyntaxToken representing the operator of the range expression.</summary> public SyntaxToken OperatorToken => new SyntaxToken(this, ((Syntax.InternalSyntax.RangeExpressionSyntax)this.Green).operatorToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>ExpressionSyntax node representing the expression on the right of the range operator.</summary> public ExpressionSyntax? RightOperand => GetRed(ref this.rightOperand, 2); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.leftOperand), 2 => GetRed(ref this.rightOperand, 2), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.leftOperand, 2 => this.rightOperand, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitRangeExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitRangeExpression(this); public RangeExpressionSyntax Update(ExpressionSyntax? leftOperand, SyntaxToken operatorToken, ExpressionSyntax? rightOperand) { if (leftOperand != this.LeftOperand || operatorToken != this.OperatorToken || rightOperand != this.RightOperand) { var newNode = SyntaxFactory.RangeExpression(leftOperand, operatorToken, rightOperand); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public RangeExpressionSyntax WithLeftOperand(ExpressionSyntax? leftOperand) => Update(leftOperand, this.OperatorToken, this.RightOperand); public RangeExpressionSyntax WithOperatorToken(SyntaxToken operatorToken) => Update(this.LeftOperand, operatorToken, this.RightOperand); public RangeExpressionSyntax WithRightOperand(ExpressionSyntax? rightOperand) => Update(this.LeftOperand, this.OperatorToken, rightOperand); } /// <summary>Class which represents the syntax node for implicit element access expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ImplicitElementAccess"/></description></item> /// </list> /// </remarks> public sealed partial class ImplicitElementAccessSyntax : ExpressionSyntax { private BracketedArgumentListSyntax? argumentList; internal ImplicitElementAccessSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>BracketedArgumentListSyntax node representing the list of arguments of the implicit element access expression.</summary> public BracketedArgumentListSyntax ArgumentList => GetRedAtZero(ref this.argumentList)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.argumentList)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.argumentList : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitImplicitElementAccess(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitImplicitElementAccess(this); public ImplicitElementAccessSyntax Update(BracketedArgumentListSyntax argumentList) { if (argumentList != this.ArgumentList) { var newNode = SyntaxFactory.ImplicitElementAccess(argumentList); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ImplicitElementAccessSyntax WithArgumentList(BracketedArgumentListSyntax argumentList) => Update(argumentList); public ImplicitElementAccessSyntax AddArgumentListArguments(params ArgumentSyntax[] items) => WithArgumentList(this.ArgumentList.WithArguments(this.ArgumentList.Arguments.AddRange(items))); } /// <summary>Class which represents an expression that has a binary operator.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.AddExpression"/></description></item> /// <item><description><see cref="SyntaxKind.SubtractExpression"/></description></item> /// <item><description><see cref="SyntaxKind.MultiplyExpression"/></description></item> /// <item><description><see cref="SyntaxKind.DivideExpression"/></description></item> /// <item><description><see cref="SyntaxKind.ModuloExpression"/></description></item> /// <item><description><see cref="SyntaxKind.LeftShiftExpression"/></description></item> /// <item><description><see cref="SyntaxKind.RightShiftExpression"/></description></item> /// <item><description><see cref="SyntaxKind.LogicalOrExpression"/></description></item> /// <item><description><see cref="SyntaxKind.LogicalAndExpression"/></description></item> /// <item><description><see cref="SyntaxKind.BitwiseOrExpression"/></description></item> /// <item><description><see cref="SyntaxKind.BitwiseAndExpression"/></description></item> /// <item><description><see cref="SyntaxKind.ExclusiveOrExpression"/></description></item> /// <item><description><see cref="SyntaxKind.EqualsExpression"/></description></item> /// <item><description><see cref="SyntaxKind.NotEqualsExpression"/></description></item> /// <item><description><see cref="SyntaxKind.LessThanExpression"/></description></item> /// <item><description><see cref="SyntaxKind.LessThanOrEqualExpression"/></description></item> /// <item><description><see cref="SyntaxKind.GreaterThanExpression"/></description></item> /// <item><description><see cref="SyntaxKind.GreaterThanOrEqualExpression"/></description></item> /// <item><description><see cref="SyntaxKind.IsExpression"/></description></item> /// <item><description><see cref="SyntaxKind.AsExpression"/></description></item> /// <item><description><see cref="SyntaxKind.CoalesceExpression"/></description></item> /// </list> /// </remarks> public sealed partial class BinaryExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? left; private ExpressionSyntax? right; internal BinaryExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>ExpressionSyntax node representing the expression on the left of the binary operator.</summary> public ExpressionSyntax Left => GetRedAtZero(ref this.left)!; /// <summary>SyntaxToken representing the operator of the binary expression.</summary> public SyntaxToken OperatorToken => new SyntaxToken(this, ((Syntax.InternalSyntax.BinaryExpressionSyntax)this.Green).operatorToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>ExpressionSyntax node representing the expression on the right of the binary operator.</summary> public ExpressionSyntax Right => GetRed(ref this.right, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.left)!, 2 => GetRed(ref this.right, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.left, 2 => this.right, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitBinaryExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitBinaryExpression(this); public BinaryExpressionSyntax Update(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) { if (left != this.Left || operatorToken != this.OperatorToken || right != this.Right) { var newNode = SyntaxFactory.BinaryExpression(this.Kind(), left, operatorToken, right); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public BinaryExpressionSyntax WithLeft(ExpressionSyntax left) => Update(left, this.OperatorToken, this.Right); public BinaryExpressionSyntax WithOperatorToken(SyntaxToken operatorToken) => Update(this.Left, operatorToken, this.Right); public BinaryExpressionSyntax WithRight(ExpressionSyntax right) => Update(this.Left, this.OperatorToken, right); } /// <summary>Class which represents an expression that has an assignment operator.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.SimpleAssignmentExpression"/></description></item> /// <item><description><see cref="SyntaxKind.AddAssignmentExpression"/></description></item> /// <item><description><see cref="SyntaxKind.SubtractAssignmentExpression"/></description></item> /// <item><description><see cref="SyntaxKind.MultiplyAssignmentExpression"/></description></item> /// <item><description><see cref="SyntaxKind.DivideAssignmentExpression"/></description></item> /// <item><description><see cref="SyntaxKind.ModuloAssignmentExpression"/></description></item> /// <item><description><see cref="SyntaxKind.AndAssignmentExpression"/></description></item> /// <item><description><see cref="SyntaxKind.ExclusiveOrAssignmentExpression"/></description></item> /// <item><description><see cref="SyntaxKind.OrAssignmentExpression"/></description></item> /// <item><description><see cref="SyntaxKind.LeftShiftAssignmentExpression"/></description></item> /// <item><description><see cref="SyntaxKind.RightShiftAssignmentExpression"/></description></item> /// <item><description><see cref="SyntaxKind.CoalesceAssignmentExpression"/></description></item> /// </list> /// </remarks> public sealed partial class AssignmentExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? left; private ExpressionSyntax? right; internal AssignmentExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>ExpressionSyntax node representing the expression on the left of the assignment operator.</summary> public ExpressionSyntax Left => GetRedAtZero(ref this.left)!; /// <summary>SyntaxToken representing the operator of the assignment expression.</summary> public SyntaxToken OperatorToken => new SyntaxToken(this, ((Syntax.InternalSyntax.AssignmentExpressionSyntax)this.Green).operatorToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>ExpressionSyntax node representing the expression on the right of the assignment operator.</summary> public ExpressionSyntax Right => GetRed(ref this.right, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.left)!, 2 => GetRed(ref this.right, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.left, 2 => this.right, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitAssignmentExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitAssignmentExpression(this); public AssignmentExpressionSyntax Update(ExpressionSyntax left, SyntaxToken operatorToken, ExpressionSyntax right) { if (left != this.Left || operatorToken != this.OperatorToken || right != this.Right) { var newNode = SyntaxFactory.AssignmentExpression(this.Kind(), left, operatorToken, right); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public AssignmentExpressionSyntax WithLeft(ExpressionSyntax left) => Update(left, this.OperatorToken, this.Right); public AssignmentExpressionSyntax WithOperatorToken(SyntaxToken operatorToken) => Update(this.Left, operatorToken, this.Right); public AssignmentExpressionSyntax WithRight(ExpressionSyntax right) => Update(this.Left, this.OperatorToken, right); } /// <summary>Class which represents the syntax node for conditional expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ConditionalExpression"/></description></item> /// </list> /// </remarks> public sealed partial class ConditionalExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? condition; private ExpressionSyntax? whenTrue; private ExpressionSyntax? whenFalse; internal ConditionalExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>ExpressionSyntax node representing the condition of the conditional expression.</summary> public ExpressionSyntax Condition => GetRedAtZero(ref this.condition)!; /// <summary>SyntaxToken representing the question mark.</summary> public SyntaxToken QuestionToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ConditionalExpressionSyntax)this.Green).questionToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>ExpressionSyntax node representing the expression to be executed when the condition is true.</summary> public ExpressionSyntax WhenTrue => GetRed(ref this.whenTrue, 2)!; /// <summary>SyntaxToken representing the colon.</summary> public SyntaxToken ColonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ConditionalExpressionSyntax)this.Green).colonToken, GetChildPosition(3), GetChildIndex(3)); /// <summary>ExpressionSyntax node representing the expression to be executed when the condition is false.</summary> public ExpressionSyntax WhenFalse => GetRed(ref this.whenFalse, 4)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.condition)!, 2 => GetRed(ref this.whenTrue, 2)!, 4 => GetRed(ref this.whenFalse, 4)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.condition, 2 => this.whenTrue, 4 => this.whenFalse, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitConditionalExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitConditionalExpression(this); public ConditionalExpressionSyntax Update(ExpressionSyntax condition, SyntaxToken questionToken, ExpressionSyntax whenTrue, SyntaxToken colonToken, ExpressionSyntax whenFalse) { if (condition != this.Condition || questionToken != this.QuestionToken || whenTrue != this.WhenTrue || colonToken != this.ColonToken || whenFalse != this.WhenFalse) { var newNode = SyntaxFactory.ConditionalExpression(condition, questionToken, whenTrue, colonToken, whenFalse); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ConditionalExpressionSyntax WithCondition(ExpressionSyntax condition) => Update(condition, this.QuestionToken, this.WhenTrue, this.ColonToken, this.WhenFalse); public ConditionalExpressionSyntax WithQuestionToken(SyntaxToken questionToken) => Update(this.Condition, questionToken, this.WhenTrue, this.ColonToken, this.WhenFalse); public ConditionalExpressionSyntax WithWhenTrue(ExpressionSyntax whenTrue) => Update(this.Condition, this.QuestionToken, whenTrue, this.ColonToken, this.WhenFalse); public ConditionalExpressionSyntax WithColonToken(SyntaxToken colonToken) => Update(this.Condition, this.QuestionToken, this.WhenTrue, colonToken, this.WhenFalse); public ConditionalExpressionSyntax WithWhenFalse(ExpressionSyntax whenFalse) => Update(this.Condition, this.QuestionToken, this.WhenTrue, this.ColonToken, whenFalse); } /// <summary>Provides the base class from which the classes that represent instance expression syntax nodes are derived. This is an abstract class.</summary> public abstract partial class InstanceExpressionSyntax : ExpressionSyntax { internal InstanceExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } } /// <summary>Class which represents the syntax node for a this expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ThisExpression"/></description></item> /// </list> /// </remarks> public sealed partial class ThisExpressionSyntax : InstanceExpressionSyntax { internal ThisExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the this keyword.</summary> public SyntaxToken Token => new SyntaxToken(this, ((Syntax.InternalSyntax.ThisExpressionSyntax)this.Green).token, Position, 0); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitThisExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitThisExpression(this); public ThisExpressionSyntax Update(SyntaxToken token) { if (token != this.Token) { var newNode = SyntaxFactory.ThisExpression(token); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ThisExpressionSyntax WithToken(SyntaxToken token) => Update(token); } /// <summary>Class which represents the syntax node for a base expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.BaseExpression"/></description></item> /// </list> /// </remarks> public sealed partial class BaseExpressionSyntax : InstanceExpressionSyntax { internal BaseExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the base keyword.</summary> public SyntaxToken Token => new SyntaxToken(this, ((Syntax.InternalSyntax.BaseExpressionSyntax)this.Green).token, Position, 0); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitBaseExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitBaseExpression(this); public BaseExpressionSyntax Update(SyntaxToken token) { if (token != this.Token) { var newNode = SyntaxFactory.BaseExpression(token); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public BaseExpressionSyntax WithToken(SyntaxToken token) => Update(token); } /// <summary>Class which represents the syntax node for a literal expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ArgListExpression"/></description></item> /// <item><description><see cref="SyntaxKind.NumericLiteralExpression"/></description></item> /// <item><description><see cref="SyntaxKind.StringLiteralExpression"/></description></item> /// <item><description><see cref="SyntaxKind.CharacterLiteralExpression"/></description></item> /// <item><description><see cref="SyntaxKind.TrueLiteralExpression"/></description></item> /// <item><description><see cref="SyntaxKind.FalseLiteralExpression"/></description></item> /// <item><description><see cref="SyntaxKind.NullLiteralExpression"/></description></item> /// <item><description><see cref="SyntaxKind.DefaultLiteralExpression"/></description></item> /// </list> /// </remarks> public sealed partial class LiteralExpressionSyntax : ExpressionSyntax { internal LiteralExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the keyword corresponding to the kind of the literal expression.</summary> public SyntaxToken Token => new SyntaxToken(this, ((Syntax.InternalSyntax.LiteralExpressionSyntax)this.Green).token, Position, 0); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitLiteralExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitLiteralExpression(this); public LiteralExpressionSyntax Update(SyntaxToken token) { if (token != this.Token) { var newNode = SyntaxFactory.LiteralExpression(this.Kind(), token); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public LiteralExpressionSyntax WithToken(SyntaxToken token) => Update(token); } /// <summary>Class which represents the syntax node for MakeRef expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.MakeRefExpression"/></description></item> /// </list> /// </remarks> public sealed partial class MakeRefExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? expression; internal MakeRefExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the MakeRefKeyword.</summary> public SyntaxToken Keyword => new SyntaxToken(this, ((Syntax.InternalSyntax.MakeRefExpressionSyntax)this.Green).keyword, Position, 0); /// <summary>SyntaxToken representing open parenthesis.</summary> public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.MakeRefExpressionSyntax)this.Green).openParenToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>Argument of the primary function.</summary> public ExpressionSyntax Expression => GetRed(ref this.expression, 2)!; /// <summary>SyntaxToken representing close parenthesis.</summary> public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.MakeRefExpressionSyntax)this.Green).closeParenToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => index == 2 ? GetRed(ref this.expression, 2)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 2 ? this.expression : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitMakeRefExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitMakeRefExpression(this); public MakeRefExpressionSyntax Update(SyntaxToken keyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken) { if (keyword != this.Keyword || openParenToken != this.OpenParenToken || expression != this.Expression || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.MakeRefExpression(keyword, openParenToken, expression, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public MakeRefExpressionSyntax WithKeyword(SyntaxToken keyword) => Update(keyword, this.OpenParenToken, this.Expression, this.CloseParenToken); public MakeRefExpressionSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.Keyword, openParenToken, this.Expression, this.CloseParenToken); public MakeRefExpressionSyntax WithExpression(ExpressionSyntax expression) => Update(this.Keyword, this.OpenParenToken, expression, this.CloseParenToken); public MakeRefExpressionSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.Keyword, this.OpenParenToken, this.Expression, closeParenToken); } /// <summary>Class which represents the syntax node for RefType expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.RefTypeExpression"/></description></item> /// </list> /// </remarks> public sealed partial class RefTypeExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? expression; internal RefTypeExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the RefTypeKeyword.</summary> public SyntaxToken Keyword => new SyntaxToken(this, ((Syntax.InternalSyntax.RefTypeExpressionSyntax)this.Green).keyword, Position, 0); /// <summary>SyntaxToken representing open parenthesis.</summary> public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.RefTypeExpressionSyntax)this.Green).openParenToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>Argument of the primary function.</summary> public ExpressionSyntax Expression => GetRed(ref this.expression, 2)!; /// <summary>SyntaxToken representing close parenthesis.</summary> public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.RefTypeExpressionSyntax)this.Green).closeParenToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => index == 2 ? GetRed(ref this.expression, 2)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 2 ? this.expression : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitRefTypeExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitRefTypeExpression(this); public RefTypeExpressionSyntax Update(SyntaxToken keyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken) { if (keyword != this.Keyword || openParenToken != this.OpenParenToken || expression != this.Expression || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.RefTypeExpression(keyword, openParenToken, expression, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public RefTypeExpressionSyntax WithKeyword(SyntaxToken keyword) => Update(keyword, this.OpenParenToken, this.Expression, this.CloseParenToken); public RefTypeExpressionSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.Keyword, openParenToken, this.Expression, this.CloseParenToken); public RefTypeExpressionSyntax WithExpression(ExpressionSyntax expression) => Update(this.Keyword, this.OpenParenToken, expression, this.CloseParenToken); public RefTypeExpressionSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.Keyword, this.OpenParenToken, this.Expression, closeParenToken); } /// <summary>Class which represents the syntax node for RefValue expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.RefValueExpression"/></description></item> /// </list> /// </remarks> public sealed partial class RefValueExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? expression; private TypeSyntax? type; internal RefValueExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the RefValueKeyword.</summary> public SyntaxToken Keyword => new SyntaxToken(this, ((Syntax.InternalSyntax.RefValueExpressionSyntax)this.Green).keyword, Position, 0); /// <summary>SyntaxToken representing open parenthesis.</summary> public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.RefValueExpressionSyntax)this.Green).openParenToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>Typed reference expression.</summary> public ExpressionSyntax Expression => GetRed(ref this.expression, 2)!; /// <summary>Comma separating the arguments.</summary> public SyntaxToken Comma => new SyntaxToken(this, ((Syntax.InternalSyntax.RefValueExpressionSyntax)this.Green).comma, GetChildPosition(3), GetChildIndex(3)); /// <summary>The type of the value.</summary> public TypeSyntax Type => GetRed(ref this.type, 4)!; /// <summary>SyntaxToken representing close parenthesis.</summary> public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.RefValueExpressionSyntax)this.Green).closeParenToken, GetChildPosition(5), GetChildIndex(5)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 2 => GetRed(ref this.expression, 2)!, 4 => GetRed(ref this.type, 4)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 2 => this.expression, 4 => this.type, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitRefValueExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitRefValueExpression(this); public RefValueExpressionSyntax Update(SyntaxToken keyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken comma, TypeSyntax type, SyntaxToken closeParenToken) { if (keyword != this.Keyword || openParenToken != this.OpenParenToken || expression != this.Expression || comma != this.Comma || type != this.Type || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.RefValueExpression(keyword, openParenToken, expression, comma, type, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public RefValueExpressionSyntax WithKeyword(SyntaxToken keyword) => Update(keyword, this.OpenParenToken, this.Expression, this.Comma, this.Type, this.CloseParenToken); public RefValueExpressionSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.Keyword, openParenToken, this.Expression, this.Comma, this.Type, this.CloseParenToken); public RefValueExpressionSyntax WithExpression(ExpressionSyntax expression) => Update(this.Keyword, this.OpenParenToken, expression, this.Comma, this.Type, this.CloseParenToken); public RefValueExpressionSyntax WithComma(SyntaxToken comma) => Update(this.Keyword, this.OpenParenToken, this.Expression, comma, this.Type, this.CloseParenToken); public RefValueExpressionSyntax WithType(TypeSyntax type) => Update(this.Keyword, this.OpenParenToken, this.Expression, this.Comma, type, this.CloseParenToken); public RefValueExpressionSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.Keyword, this.OpenParenToken, this.Expression, this.Comma, this.Type, closeParenToken); } /// <summary>Class which represents the syntax node for Checked or Unchecked expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.CheckedExpression"/></description></item> /// <item><description><see cref="SyntaxKind.UncheckedExpression"/></description></item> /// </list> /// </remarks> public sealed partial class CheckedExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? expression; internal CheckedExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the checked or unchecked keyword.</summary> public SyntaxToken Keyword => new SyntaxToken(this, ((Syntax.InternalSyntax.CheckedExpressionSyntax)this.Green).keyword, Position, 0); /// <summary>SyntaxToken representing open parenthesis.</summary> public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.CheckedExpressionSyntax)this.Green).openParenToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>Argument of the primary function.</summary> public ExpressionSyntax Expression => GetRed(ref this.expression, 2)!; /// <summary>SyntaxToken representing close parenthesis.</summary> public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.CheckedExpressionSyntax)this.Green).closeParenToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => index == 2 ? GetRed(ref this.expression, 2)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 2 ? this.expression : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitCheckedExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitCheckedExpression(this); public CheckedExpressionSyntax Update(SyntaxToken keyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken) { if (keyword != this.Keyword || openParenToken != this.OpenParenToken || expression != this.Expression || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.CheckedExpression(this.Kind(), keyword, openParenToken, expression, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public CheckedExpressionSyntax WithKeyword(SyntaxToken keyword) => Update(keyword, this.OpenParenToken, this.Expression, this.CloseParenToken); public CheckedExpressionSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.Keyword, openParenToken, this.Expression, this.CloseParenToken); public CheckedExpressionSyntax WithExpression(ExpressionSyntax expression) => Update(this.Keyword, this.OpenParenToken, expression, this.CloseParenToken); public CheckedExpressionSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.Keyword, this.OpenParenToken, this.Expression, closeParenToken); } /// <summary>Class which represents the syntax node for Default expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.DefaultExpression"/></description></item> /// </list> /// </remarks> public sealed partial class DefaultExpressionSyntax : ExpressionSyntax { private TypeSyntax? type; internal DefaultExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the DefaultKeyword.</summary> public SyntaxToken Keyword => new SyntaxToken(this, ((Syntax.InternalSyntax.DefaultExpressionSyntax)this.Green).keyword, Position, 0); /// <summary>SyntaxToken representing open parenthesis.</summary> public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.DefaultExpressionSyntax)this.Green).openParenToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>Argument of the primary function.</summary> public TypeSyntax Type => GetRed(ref this.type, 2)!; /// <summary>SyntaxToken representing close parenthesis.</summary> public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.DefaultExpressionSyntax)this.Green).closeParenToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => index == 2 ? GetRed(ref this.type, 2)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 2 ? this.type : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitDefaultExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitDefaultExpression(this); public DefaultExpressionSyntax Update(SyntaxToken keyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken closeParenToken) { if (keyword != this.Keyword || openParenToken != this.OpenParenToken || type != this.Type || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.DefaultExpression(keyword, openParenToken, type, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public DefaultExpressionSyntax WithKeyword(SyntaxToken keyword) => Update(keyword, this.OpenParenToken, this.Type, this.CloseParenToken); public DefaultExpressionSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.Keyword, openParenToken, this.Type, this.CloseParenToken); public DefaultExpressionSyntax WithType(TypeSyntax type) => Update(this.Keyword, this.OpenParenToken, type, this.CloseParenToken); public DefaultExpressionSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.Keyword, this.OpenParenToken, this.Type, closeParenToken); } /// <summary>Class which represents the syntax node for TypeOf expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.TypeOfExpression"/></description></item> /// </list> /// </remarks> public sealed partial class TypeOfExpressionSyntax : ExpressionSyntax { private TypeSyntax? type; internal TypeOfExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the TypeOfKeyword.</summary> public SyntaxToken Keyword => new SyntaxToken(this, ((Syntax.InternalSyntax.TypeOfExpressionSyntax)this.Green).keyword, Position, 0); /// <summary>SyntaxToken representing open parenthesis.</summary> public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.TypeOfExpressionSyntax)this.Green).openParenToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>The expression to return type of.</summary> public TypeSyntax Type => GetRed(ref this.type, 2)!; /// <summary>SyntaxToken representing close parenthesis.</summary> public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.TypeOfExpressionSyntax)this.Green).closeParenToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => index == 2 ? GetRed(ref this.type, 2)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 2 ? this.type : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitTypeOfExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitTypeOfExpression(this); public TypeOfExpressionSyntax Update(SyntaxToken keyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken closeParenToken) { if (keyword != this.Keyword || openParenToken != this.OpenParenToken || type != this.Type || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.TypeOfExpression(keyword, openParenToken, type, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public TypeOfExpressionSyntax WithKeyword(SyntaxToken keyword) => Update(keyword, this.OpenParenToken, this.Type, this.CloseParenToken); public TypeOfExpressionSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.Keyword, openParenToken, this.Type, this.CloseParenToken); public TypeOfExpressionSyntax WithType(TypeSyntax type) => Update(this.Keyword, this.OpenParenToken, type, this.CloseParenToken); public TypeOfExpressionSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.Keyword, this.OpenParenToken, this.Type, closeParenToken); } /// <summary>Class which represents the syntax node for SizeOf expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.SizeOfExpression"/></description></item> /// </list> /// </remarks> public sealed partial class SizeOfExpressionSyntax : ExpressionSyntax { private TypeSyntax? type; internal SizeOfExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the SizeOfKeyword.</summary> public SyntaxToken Keyword => new SyntaxToken(this, ((Syntax.InternalSyntax.SizeOfExpressionSyntax)this.Green).keyword, Position, 0); /// <summary>SyntaxToken representing open parenthesis.</summary> public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.SizeOfExpressionSyntax)this.Green).openParenToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>Argument of the primary function.</summary> public TypeSyntax Type => GetRed(ref this.type, 2)!; /// <summary>SyntaxToken representing close parenthesis.</summary> public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.SizeOfExpressionSyntax)this.Green).closeParenToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => index == 2 ? GetRed(ref this.type, 2)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 2 ? this.type : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitSizeOfExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitSizeOfExpression(this); public SizeOfExpressionSyntax Update(SyntaxToken keyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken closeParenToken) { if (keyword != this.Keyword || openParenToken != this.OpenParenToken || type != this.Type || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.SizeOfExpression(keyword, openParenToken, type, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public SizeOfExpressionSyntax WithKeyword(SyntaxToken keyword) => Update(keyword, this.OpenParenToken, this.Type, this.CloseParenToken); public SizeOfExpressionSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.Keyword, openParenToken, this.Type, this.CloseParenToken); public SizeOfExpressionSyntax WithType(TypeSyntax type) => Update(this.Keyword, this.OpenParenToken, type, this.CloseParenToken); public SizeOfExpressionSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.Keyword, this.OpenParenToken, this.Type, closeParenToken); } /// <summary>Class which represents the syntax node for invocation expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.InvocationExpression"/></description></item> /// </list> /// </remarks> public sealed partial class InvocationExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? expression; private ArgumentListSyntax? argumentList; internal InvocationExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>ExpressionSyntax node representing the expression part of the invocation.</summary> public ExpressionSyntax Expression => GetRedAtZero(ref this.expression)!; /// <summary>ArgumentListSyntax node representing the list of arguments of the invocation expression.</summary> public ArgumentListSyntax ArgumentList => GetRed(ref this.argumentList, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.expression)!, 1 => GetRed(ref this.argumentList, 1)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.expression, 1 => this.argumentList, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitInvocationExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitInvocationExpression(this); public InvocationExpressionSyntax Update(ExpressionSyntax expression, ArgumentListSyntax argumentList) { if (expression != this.Expression || argumentList != this.ArgumentList) { var newNode = SyntaxFactory.InvocationExpression(expression, argumentList); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public InvocationExpressionSyntax WithExpression(ExpressionSyntax expression) => Update(expression, this.ArgumentList); public InvocationExpressionSyntax WithArgumentList(ArgumentListSyntax argumentList) => Update(this.Expression, argumentList); public InvocationExpressionSyntax AddArgumentListArguments(params ArgumentSyntax[] items) => WithArgumentList(this.ArgumentList.WithArguments(this.ArgumentList.Arguments.AddRange(items))); } /// <summary>Class which represents the syntax node for element access expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ElementAccessExpression"/></description></item> /// </list> /// </remarks> public sealed partial class ElementAccessExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? expression; private BracketedArgumentListSyntax? argumentList; internal ElementAccessExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>ExpressionSyntax node representing the expression which is accessing the element.</summary> public ExpressionSyntax Expression => GetRedAtZero(ref this.expression)!; /// <summary>BracketedArgumentListSyntax node representing the list of arguments of the element access expression.</summary> public BracketedArgumentListSyntax ArgumentList => GetRed(ref this.argumentList, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.expression)!, 1 => GetRed(ref this.argumentList, 1)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.expression, 1 => this.argumentList, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitElementAccessExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitElementAccessExpression(this); public ElementAccessExpressionSyntax Update(ExpressionSyntax expression, BracketedArgumentListSyntax argumentList) { if (expression != this.Expression || argumentList != this.ArgumentList) { var newNode = SyntaxFactory.ElementAccessExpression(expression, argumentList); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ElementAccessExpressionSyntax WithExpression(ExpressionSyntax expression) => Update(expression, this.ArgumentList); public ElementAccessExpressionSyntax WithArgumentList(BracketedArgumentListSyntax argumentList) => Update(this.Expression, argumentList); public ElementAccessExpressionSyntax AddArgumentListArguments(params ArgumentSyntax[] items) => WithArgumentList(this.ArgumentList.WithArguments(this.ArgumentList.Arguments.AddRange(items))); } /// <summary>Provides the base class from which the classes that represent argument list syntax nodes are derived. This is an abstract class.</summary> public abstract partial class BaseArgumentListSyntax : CSharpSyntaxNode { internal BaseArgumentListSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SeparatedSyntaxList of ArgumentSyntax nodes representing the list of arguments.</summary> public abstract SeparatedSyntaxList<ArgumentSyntax> Arguments { get; } public BaseArgumentListSyntax WithArguments(SeparatedSyntaxList<ArgumentSyntax> arguments) => WithArgumentsCore(arguments); internal abstract BaseArgumentListSyntax WithArgumentsCore(SeparatedSyntaxList<ArgumentSyntax> arguments); public BaseArgumentListSyntax AddArguments(params ArgumentSyntax[] items) => AddArgumentsCore(items); internal abstract BaseArgumentListSyntax AddArgumentsCore(params ArgumentSyntax[] items); } /// <summary>Class which represents the syntax node for the list of arguments.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ArgumentList"/></description></item> /// </list> /// </remarks> public sealed partial class ArgumentListSyntax : BaseArgumentListSyntax { private SyntaxNode? arguments; internal ArgumentListSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing open parenthesis.</summary> public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ArgumentListSyntax)this.Green).openParenToken, Position, 0); /// <summary>SeparatedSyntaxList of ArgumentSyntax representing the list of arguments.</summary> public override SeparatedSyntaxList<ArgumentSyntax> Arguments { get { var red = GetRed(ref this.arguments, 1); return red != null ? new SeparatedSyntaxList<ArgumentSyntax>(red, GetChildIndex(1)) : default; } } /// <summary>SyntaxToken representing close parenthesis.</summary> public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ArgumentListSyntax)this.Green).closeParenToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.arguments, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.arguments : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitArgumentList(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitArgumentList(this); public ArgumentListSyntax Update(SyntaxToken openParenToken, SeparatedSyntaxList<ArgumentSyntax> arguments, SyntaxToken closeParenToken) { if (openParenToken != this.OpenParenToken || arguments != this.Arguments || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.ArgumentList(openParenToken, arguments, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ArgumentListSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(openParenToken, this.Arguments, this.CloseParenToken); internal override BaseArgumentListSyntax WithArgumentsCore(SeparatedSyntaxList<ArgumentSyntax> arguments) => WithArguments(arguments); public new ArgumentListSyntax WithArguments(SeparatedSyntaxList<ArgumentSyntax> arguments) => Update(this.OpenParenToken, arguments, this.CloseParenToken); public ArgumentListSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.OpenParenToken, this.Arguments, closeParenToken); internal override BaseArgumentListSyntax AddArgumentsCore(params ArgumentSyntax[] items) => AddArguments(items); public new ArgumentListSyntax AddArguments(params ArgumentSyntax[] items) => WithArguments(this.Arguments.AddRange(items)); } /// <summary>Class which represents the syntax node for bracketed argument list.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.BracketedArgumentList"/></description></item> /// </list> /// </remarks> public sealed partial class BracketedArgumentListSyntax : BaseArgumentListSyntax { private SyntaxNode? arguments; internal BracketedArgumentListSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing open bracket.</summary> public SyntaxToken OpenBracketToken => new SyntaxToken(this, ((Syntax.InternalSyntax.BracketedArgumentListSyntax)this.Green).openBracketToken, Position, 0); /// <summary>SeparatedSyntaxList of ArgumentSyntax representing the list of arguments.</summary> public override SeparatedSyntaxList<ArgumentSyntax> Arguments { get { var red = GetRed(ref this.arguments, 1); return red != null ? new SeparatedSyntaxList<ArgumentSyntax>(red, GetChildIndex(1)) : default; } } /// <summary>SyntaxToken representing close bracket.</summary> public SyntaxToken CloseBracketToken => new SyntaxToken(this, ((Syntax.InternalSyntax.BracketedArgumentListSyntax)this.Green).closeBracketToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.arguments, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.arguments : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitBracketedArgumentList(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitBracketedArgumentList(this); public BracketedArgumentListSyntax Update(SyntaxToken openBracketToken, SeparatedSyntaxList<ArgumentSyntax> arguments, SyntaxToken closeBracketToken) { if (openBracketToken != this.OpenBracketToken || arguments != this.Arguments || closeBracketToken != this.CloseBracketToken) { var newNode = SyntaxFactory.BracketedArgumentList(openBracketToken, arguments, closeBracketToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public BracketedArgumentListSyntax WithOpenBracketToken(SyntaxToken openBracketToken) => Update(openBracketToken, this.Arguments, this.CloseBracketToken); internal override BaseArgumentListSyntax WithArgumentsCore(SeparatedSyntaxList<ArgumentSyntax> arguments) => WithArguments(arguments); public new BracketedArgumentListSyntax WithArguments(SeparatedSyntaxList<ArgumentSyntax> arguments) => Update(this.OpenBracketToken, arguments, this.CloseBracketToken); public BracketedArgumentListSyntax WithCloseBracketToken(SyntaxToken closeBracketToken) => Update(this.OpenBracketToken, this.Arguments, closeBracketToken); internal override BaseArgumentListSyntax AddArgumentsCore(params ArgumentSyntax[] items) => AddArguments(items); public new BracketedArgumentListSyntax AddArguments(params ArgumentSyntax[] items) => WithArguments(this.Arguments.AddRange(items)); } /// <summary>Class which represents the syntax node for argument.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.Argument"/></description></item> /// </list> /// </remarks> public sealed partial class ArgumentSyntax : CSharpSyntaxNode { private NameColonSyntax? nameColon; private ExpressionSyntax? expression; internal ArgumentSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>NameColonSyntax node representing the optional name arguments.</summary> public NameColonSyntax? NameColon => GetRedAtZero(ref this.nameColon); /// <summary>SyntaxToken representing the optional ref or out keyword.</summary> public SyntaxToken RefKindKeyword { get { var slot = ((Syntax.InternalSyntax.ArgumentSyntax)this.Green).refKindKeyword; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } /// <summary>ExpressionSyntax node representing the argument.</summary> public ExpressionSyntax Expression => GetRed(ref this.expression, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.nameColon), 2 => GetRed(ref this.expression, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.nameColon, 2 => this.expression, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitArgument(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitArgument(this); public ArgumentSyntax Update(NameColonSyntax? nameColon, SyntaxToken refKindKeyword, ExpressionSyntax expression) { if (nameColon != this.NameColon || refKindKeyword != this.RefKindKeyword || expression != this.Expression) { var newNode = SyntaxFactory.Argument(nameColon, refKindKeyword, expression); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ArgumentSyntax WithNameColon(NameColonSyntax? nameColon) => Update(nameColon, this.RefKindKeyword, this.Expression); public ArgumentSyntax WithRefKindKeyword(SyntaxToken refKindKeyword) => Update(this.NameColon, refKindKeyword, this.Expression); public ArgumentSyntax WithExpression(ExpressionSyntax expression) => Update(this.NameColon, this.RefKindKeyword, expression); } public abstract partial class BaseExpressionColonSyntax : CSharpSyntaxNode { internal BaseExpressionColonSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public abstract ExpressionSyntax Expression { get; } public BaseExpressionColonSyntax WithExpression(ExpressionSyntax expression) => WithExpressionCore(expression); internal abstract BaseExpressionColonSyntax WithExpressionCore(ExpressionSyntax expression); public abstract SyntaxToken ColonToken { get; } public BaseExpressionColonSyntax WithColonToken(SyntaxToken colonToken) => WithColonTokenCore(colonToken); internal abstract BaseExpressionColonSyntax WithColonTokenCore(SyntaxToken colonToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ExpressionColon"/></description></item> /// </list> /// </remarks> public sealed partial class ExpressionColonSyntax : BaseExpressionColonSyntax { private ExpressionSyntax? expression; internal ExpressionColonSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override ExpressionSyntax Expression => GetRedAtZero(ref this.expression)!; public override SyntaxToken ColonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ExpressionColonSyntax)this.Green).colonToken, GetChildPosition(1), GetChildIndex(1)); internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.expression)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.expression : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitExpressionColon(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitExpressionColon(this); public ExpressionColonSyntax Update(ExpressionSyntax expression, SyntaxToken colonToken) { if (expression != this.Expression || colonToken != this.ColonToken) { var newNode = SyntaxFactory.ExpressionColon(expression, colonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override BaseExpressionColonSyntax WithExpressionCore(ExpressionSyntax expression) => WithExpression(expression); public new ExpressionColonSyntax WithExpression(ExpressionSyntax expression) => Update(expression, this.ColonToken); internal override BaseExpressionColonSyntax WithColonTokenCore(SyntaxToken colonToken) => WithColonToken(colonToken); public new ExpressionColonSyntax WithColonToken(SyntaxToken colonToken) => Update(this.Expression, colonToken); } /// <summary>Class which represents the syntax node for name colon syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.NameColon"/></description></item> /// </list> /// </remarks> public sealed partial class NameColonSyntax : BaseExpressionColonSyntax { private IdentifierNameSyntax? name; internal NameColonSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>IdentifierNameSyntax representing the identifier name.</summary> public IdentifierNameSyntax Name => GetRedAtZero(ref this.name)!; /// <summary>SyntaxToken representing colon.</summary> public override SyntaxToken ColonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.NameColonSyntax)this.Green).colonToken, GetChildPosition(1), GetChildIndex(1)); internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.name)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.name : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitNameColon(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitNameColon(this); public NameColonSyntax Update(IdentifierNameSyntax name, SyntaxToken colonToken) { if (name != this.Name || colonToken != this.ColonToken) { var newNode = SyntaxFactory.NameColon(name, colonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public NameColonSyntax WithName(IdentifierNameSyntax name) => Update(name, this.ColonToken); internal override BaseExpressionColonSyntax WithColonTokenCore(SyntaxToken colonToken) => WithColonToken(colonToken); public new NameColonSyntax WithColonToken(SyntaxToken colonToken) => Update(this.Name, colonToken); } /// <summary>Class which represents the syntax node for the variable declaration in an out var declaration or a deconstruction declaration.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.DeclarationExpression"/></description></item> /// </list> /// </remarks> public sealed partial class DeclarationExpressionSyntax : ExpressionSyntax { private TypeSyntax? type; private VariableDesignationSyntax? designation; internal DeclarationExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public TypeSyntax Type => GetRedAtZero(ref this.type)!; /// <summary>Declaration representing the variable declared in an out parameter or deconstruction.</summary> public VariableDesignationSyntax Designation => GetRed(ref this.designation, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.type)!, 1 => GetRed(ref this.designation, 1)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.type, 1 => this.designation, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitDeclarationExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitDeclarationExpression(this); public DeclarationExpressionSyntax Update(TypeSyntax type, VariableDesignationSyntax designation) { if (type != this.Type || designation != this.Designation) { var newNode = SyntaxFactory.DeclarationExpression(type, designation); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public DeclarationExpressionSyntax WithType(TypeSyntax type) => Update(type, this.Designation); public DeclarationExpressionSyntax WithDesignation(VariableDesignationSyntax designation) => Update(this.Type, designation); } /// <summary>Class which represents the syntax node for cast expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.CastExpression"/></description></item> /// </list> /// </remarks> public sealed partial class CastExpressionSyntax : ExpressionSyntax { private TypeSyntax? type; private ExpressionSyntax? expression; internal CastExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the open parenthesis.</summary> public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.CastExpressionSyntax)this.Green).openParenToken, Position, 0); /// <summary>TypeSyntax node representing the type to which the expression is being cast.</summary> public TypeSyntax Type => GetRed(ref this.type, 1)!; /// <summary>SyntaxToken representing the close parenthesis.</summary> public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.CastExpressionSyntax)this.Green).closeParenToken, GetChildPosition(2), GetChildIndex(2)); /// <summary>ExpressionSyntax node representing the expression that is being casted.</summary> public ExpressionSyntax Expression => GetRed(ref this.expression, 3)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 1 => GetRed(ref this.type, 1)!, 3 => GetRed(ref this.expression, 3)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 1 => this.type, 3 => this.expression, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitCastExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitCastExpression(this); public CastExpressionSyntax Update(SyntaxToken openParenToken, TypeSyntax type, SyntaxToken closeParenToken, ExpressionSyntax expression) { if (openParenToken != this.OpenParenToken || type != this.Type || closeParenToken != this.CloseParenToken || expression != this.Expression) { var newNode = SyntaxFactory.CastExpression(openParenToken, type, closeParenToken, expression); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public CastExpressionSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(openParenToken, this.Type, this.CloseParenToken, this.Expression); public CastExpressionSyntax WithType(TypeSyntax type) => Update(this.OpenParenToken, type, this.CloseParenToken, this.Expression); public CastExpressionSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.OpenParenToken, this.Type, closeParenToken, this.Expression); public CastExpressionSyntax WithExpression(ExpressionSyntax expression) => Update(this.OpenParenToken, this.Type, this.CloseParenToken, expression); } /// <summary>Provides the base class from which the classes that represent anonymous function expressions are derived.</summary> public abstract partial class AnonymousFunctionExpressionSyntax : ExpressionSyntax { internal AnonymousFunctionExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public abstract SyntaxTokenList Modifiers { get; } public AnonymousFunctionExpressionSyntax WithModifiers(SyntaxTokenList modifiers) => WithModifiersCore(modifiers); internal abstract AnonymousFunctionExpressionSyntax WithModifiersCore(SyntaxTokenList modifiers); public AnonymousFunctionExpressionSyntax AddModifiers(params SyntaxToken[] items) => AddModifiersCore(items); internal abstract AnonymousFunctionExpressionSyntax AddModifiersCore(params SyntaxToken[] items); /// <summary> /// BlockSyntax node representing the body of the anonymous function. /// Only one of Block or ExpressionBody will be non-null. /// </summary> public abstract BlockSyntax? Block { get; } public AnonymousFunctionExpressionSyntax WithBlock(BlockSyntax? block) => WithBlockCore(block); internal abstract AnonymousFunctionExpressionSyntax WithBlockCore(BlockSyntax? block); public AnonymousFunctionExpressionSyntax AddBlockAttributeLists(params AttributeListSyntax[] items) => AddBlockAttributeListsCore(items); internal abstract AnonymousFunctionExpressionSyntax AddBlockAttributeListsCore(params AttributeListSyntax[] items); public AnonymousFunctionExpressionSyntax AddBlockStatements(params StatementSyntax[] items) => AddBlockStatementsCore(items); internal abstract AnonymousFunctionExpressionSyntax AddBlockStatementsCore(params StatementSyntax[] items); /// <summary> /// ExpressionSyntax node representing the body of the anonymous function. /// Only one of Block or ExpressionBody will be non-null. /// </summary> public abstract ExpressionSyntax? ExpressionBody { get; } public AnonymousFunctionExpressionSyntax WithExpressionBody(ExpressionSyntax? expressionBody) => WithExpressionBodyCore(expressionBody); internal abstract AnonymousFunctionExpressionSyntax WithExpressionBodyCore(ExpressionSyntax? expressionBody); } /// <summary>Class which represents the syntax node for anonymous method expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.AnonymousMethodExpression"/></description></item> /// </list> /// </remarks> public sealed partial class AnonymousMethodExpressionSyntax : AnonymousFunctionExpressionSyntax { private ParameterListSyntax? parameterList; private BlockSyntax? block; private ExpressionSyntax? expressionBody; internal AnonymousMethodExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(0); return slot != null ? new SyntaxTokenList(this, slot, Position, 0) : default; } } /// <summary>SyntaxToken representing the delegate keyword.</summary> public SyntaxToken DelegateKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.AnonymousMethodExpressionSyntax)this.Green).delegateKeyword, GetChildPosition(1), GetChildIndex(1)); /// <summary>List of parameters of the anonymous method expression, or null if there no parameters are specified.</summary> public ParameterListSyntax? ParameterList => GetRed(ref this.parameterList, 2); /// <summary> /// BlockSyntax node representing the body of the anonymous function. /// This will never be null. /// </summary> public override BlockSyntax Block => GetRed(ref this.block, 3)!; /// <summary> /// Inherited from AnonymousFunctionExpressionSyntax, but not used for /// AnonymousMethodExpressionSyntax. This will always be null. /// </summary> public override ExpressionSyntax? ExpressionBody => GetRed(ref this.expressionBody, 4); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 2 => GetRed(ref this.parameterList, 2), 3 => GetRed(ref this.block, 3)!, 4 => GetRed(ref this.expressionBody, 4), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 2 => this.parameterList, 3 => this.block, 4 => this.expressionBody, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitAnonymousMethodExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitAnonymousMethodExpression(this); public AnonymousMethodExpressionSyntax Update(SyntaxTokenList modifiers, SyntaxToken delegateKeyword, ParameterListSyntax? parameterList, BlockSyntax block, ExpressionSyntax? expressionBody) { if (modifiers != this.Modifiers || delegateKeyword != this.DelegateKeyword || parameterList != this.ParameterList || block != this.Block || expressionBody != this.ExpressionBody) { var newNode = SyntaxFactory.AnonymousMethodExpression(modifiers, delegateKeyword, parameterList, block, expressionBody); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override AnonymousFunctionExpressionSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new AnonymousMethodExpressionSyntax WithModifiers(SyntaxTokenList modifiers) => Update(modifiers, this.DelegateKeyword, this.ParameterList, this.Block, this.ExpressionBody); public AnonymousMethodExpressionSyntax WithDelegateKeyword(SyntaxToken delegateKeyword) => Update(this.Modifiers, delegateKeyword, this.ParameterList, this.Block, this.ExpressionBody); public AnonymousMethodExpressionSyntax WithParameterList(ParameterListSyntax? parameterList) => Update(this.Modifiers, this.DelegateKeyword, parameterList, this.Block, this.ExpressionBody); internal override AnonymousFunctionExpressionSyntax WithBlockCore(BlockSyntax? block) => WithBlock(block ?? throw new ArgumentNullException(nameof(block))); public new AnonymousMethodExpressionSyntax WithBlock(BlockSyntax block) => Update(this.Modifiers, this.DelegateKeyword, this.ParameterList, block, this.ExpressionBody); internal override AnonymousFunctionExpressionSyntax WithExpressionBodyCore(ExpressionSyntax? expressionBody) => WithExpressionBody(expressionBody); public new AnonymousMethodExpressionSyntax WithExpressionBody(ExpressionSyntax? expressionBody) => Update(this.Modifiers, this.DelegateKeyword, this.ParameterList, this.Block, expressionBody); internal override AnonymousFunctionExpressionSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new AnonymousMethodExpressionSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); public AnonymousMethodExpressionSyntax AddParameterListParameters(params ParameterSyntax[] items) { var parameterList = this.ParameterList ?? SyntaxFactory.ParameterList(); return WithParameterList(parameterList.WithParameters(parameterList.Parameters.AddRange(items))); } internal override AnonymousFunctionExpressionSyntax AddBlockAttributeListsCore(params AttributeListSyntax[] items) => AddBlockAttributeLists(items); public new AnonymousMethodExpressionSyntax AddBlockAttributeLists(params AttributeListSyntax[] items) => WithBlock(this.Block.WithAttributeLists(this.Block.AttributeLists.AddRange(items))); internal override AnonymousFunctionExpressionSyntax AddBlockStatementsCore(params StatementSyntax[] items) => AddBlockStatements(items); public new AnonymousMethodExpressionSyntax AddBlockStatements(params StatementSyntax[] items) => WithBlock(this.Block.WithStatements(this.Block.Statements.AddRange(items))); } /// <summary>Provides the base class from which the classes that represent lambda expressions are derived.</summary> public abstract partial class LambdaExpressionSyntax : AnonymousFunctionExpressionSyntax { internal LambdaExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public abstract SyntaxList<AttributeListSyntax> AttributeLists { get; } public LambdaExpressionSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeListsCore(attributeLists); internal abstract LambdaExpressionSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists); public LambdaExpressionSyntax AddAttributeLists(params AttributeListSyntax[] items) => AddAttributeListsCore(items); internal abstract LambdaExpressionSyntax AddAttributeListsCore(params AttributeListSyntax[] items); /// <summary>SyntaxToken representing equals greater than.</summary> public abstract SyntaxToken ArrowToken { get; } public LambdaExpressionSyntax WithArrowToken(SyntaxToken arrowToken) => WithArrowTokenCore(arrowToken); internal abstract LambdaExpressionSyntax WithArrowTokenCore(SyntaxToken arrowToken); public new LambdaExpressionSyntax WithModifiers(SyntaxTokenList modifiers) => (LambdaExpressionSyntax)WithModifiersCore(modifiers); public new LambdaExpressionSyntax WithBlock(BlockSyntax? block) => (LambdaExpressionSyntax)WithBlockCore(block); public new LambdaExpressionSyntax WithExpressionBody(ExpressionSyntax? expressionBody) => (LambdaExpressionSyntax)WithExpressionBodyCore(expressionBody); public new LambdaExpressionSyntax AddModifiers(params SyntaxToken[] items) => (LambdaExpressionSyntax)AddModifiersCore(items); public new AnonymousFunctionExpressionSyntax AddBlockAttributeLists(params AttributeListSyntax[] items) => AddBlockAttributeListsCore(items); public new AnonymousFunctionExpressionSyntax AddBlockStatements(params StatementSyntax[] items) => AddBlockStatementsCore(items); } /// <summary>Class which represents the syntax node for a simple lambda expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.SimpleLambdaExpression"/></description></item> /// </list> /// </remarks> public sealed partial class SimpleLambdaExpressionSyntax : LambdaExpressionSyntax { private SyntaxNode? attributeLists; private ParameterSyntax? parameter; private BlockSyntax? block; private ExpressionSyntax? expressionBody; internal SimpleLambdaExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } /// <summary>ParameterSyntax node representing the parameter of the lambda expression.</summary> public ParameterSyntax Parameter => GetRed(ref this.parameter, 2)!; /// <summary>SyntaxToken representing equals greater than.</summary> public override SyntaxToken ArrowToken => new SyntaxToken(this, ((Syntax.InternalSyntax.SimpleLambdaExpressionSyntax)this.Green).arrowToken, GetChildPosition(3), GetChildIndex(3)); /// <summary> /// BlockSyntax node representing the body of the lambda. /// Only one of Block or ExpressionBody will be non-null. /// </summary> public override BlockSyntax? Block => GetRed(ref this.block, 4); /// <summary> /// ExpressionSyntax node representing the body of the lambda. /// Only one of Block or ExpressionBody will be non-null. /// </summary> public override ExpressionSyntax? ExpressionBody => GetRed(ref this.expressionBody, 5); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.parameter, 2)!, 4 => GetRed(ref this.block, 4), 5 => GetRed(ref this.expressionBody, 5), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.parameter, 4 => this.block, 5 => this.expressionBody, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitSimpleLambdaExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitSimpleLambdaExpression(this); public SimpleLambdaExpressionSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, ParameterSyntax parameter, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || parameter != this.Parameter || arrowToken != this.ArrowToken || block != this.Block || expressionBody != this.ExpressionBody) { var newNode = SyntaxFactory.SimpleLambdaExpression(attributeLists, modifiers, parameter, arrowToken, block, expressionBody); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override LambdaExpressionSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new SimpleLambdaExpressionSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.Parameter, this.ArrowToken, this.Block, this.ExpressionBody); internal override AnonymousFunctionExpressionSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new SimpleLambdaExpressionSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.Parameter, this.ArrowToken, this.Block, this.ExpressionBody); public SimpleLambdaExpressionSyntax WithParameter(ParameterSyntax parameter) => Update(this.AttributeLists, this.Modifiers, parameter, this.ArrowToken, this.Block, this.ExpressionBody); internal override LambdaExpressionSyntax WithArrowTokenCore(SyntaxToken arrowToken) => WithArrowToken(arrowToken); public new SimpleLambdaExpressionSyntax WithArrowToken(SyntaxToken arrowToken) => Update(this.AttributeLists, this.Modifiers, this.Parameter, arrowToken, this.Block, this.ExpressionBody); internal override AnonymousFunctionExpressionSyntax WithBlockCore(BlockSyntax? block) => WithBlock(block); public new SimpleLambdaExpressionSyntax WithBlock(BlockSyntax? block) => Update(this.AttributeLists, this.Modifiers, this.Parameter, this.ArrowToken, block, this.ExpressionBody); internal override AnonymousFunctionExpressionSyntax WithExpressionBodyCore(ExpressionSyntax? expressionBody) => WithExpressionBody(expressionBody); public new SimpleLambdaExpressionSyntax WithExpressionBody(ExpressionSyntax? expressionBody) => Update(this.AttributeLists, this.Modifiers, this.Parameter, this.ArrowToken, this.Block, expressionBody); internal override LambdaExpressionSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new SimpleLambdaExpressionSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override AnonymousFunctionExpressionSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new SimpleLambdaExpressionSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); public SimpleLambdaExpressionSyntax AddParameterAttributeLists(params AttributeListSyntax[] items) => WithParameter(this.Parameter.WithAttributeLists(this.Parameter.AttributeLists.AddRange(items))); public SimpleLambdaExpressionSyntax AddParameterModifiers(params SyntaxToken[] items) => WithParameter(this.Parameter.WithModifiers(this.Parameter.Modifiers.AddRange(items))); internal override AnonymousFunctionExpressionSyntax AddBlockAttributeListsCore(params AttributeListSyntax[] items) => AddBlockAttributeLists(items); public new SimpleLambdaExpressionSyntax AddBlockAttributeLists(params AttributeListSyntax[] items) { var block = this.Block ?? SyntaxFactory.Block(); return WithBlock(block.WithAttributeLists(block.AttributeLists.AddRange(items))); } internal override AnonymousFunctionExpressionSyntax AddBlockStatementsCore(params StatementSyntax[] items) => AddBlockStatements(items); public new SimpleLambdaExpressionSyntax AddBlockStatements(params StatementSyntax[] items) { var block = this.Block ?? SyntaxFactory.Block(); return WithBlock(block.WithStatements(block.Statements.AddRange(items))); } } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.RefExpression"/></description></item> /// </list> /// </remarks> public sealed partial class RefExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? expression; internal RefExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken RefKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.RefExpressionSyntax)this.Green).refKeyword, Position, 0); public ExpressionSyntax Expression => GetRed(ref this.expression, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.expression, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.expression : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitRefExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitRefExpression(this); public RefExpressionSyntax Update(SyntaxToken refKeyword, ExpressionSyntax expression) { if (refKeyword != this.RefKeyword || expression != this.Expression) { var newNode = SyntaxFactory.RefExpression(refKeyword, expression); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public RefExpressionSyntax WithRefKeyword(SyntaxToken refKeyword) => Update(refKeyword, this.Expression); public RefExpressionSyntax WithExpression(ExpressionSyntax expression) => Update(this.RefKeyword, expression); } /// <summary>Class which represents the syntax node for parenthesized lambda expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ParenthesizedLambdaExpression"/></description></item> /// </list> /// </remarks> public sealed partial class ParenthesizedLambdaExpressionSyntax : LambdaExpressionSyntax { private SyntaxNode? attributeLists; private TypeSyntax? returnType; private ParameterListSyntax? parameterList; private BlockSyntax? block; private ExpressionSyntax? expressionBody; internal ParenthesizedLambdaExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public TypeSyntax? ReturnType => GetRed(ref this.returnType, 2); /// <summary>ParameterListSyntax node representing the list of parameters for the lambda expression.</summary> public ParameterListSyntax ParameterList => GetRed(ref this.parameterList, 3)!; /// <summary>SyntaxToken representing equals greater than.</summary> public override SyntaxToken ArrowToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ParenthesizedLambdaExpressionSyntax)this.Green).arrowToken, GetChildPosition(4), GetChildIndex(4)); /// <summary> /// BlockSyntax node representing the body of the lambda. /// Only one of Block or ExpressionBody will be non-null. /// </summary> public override BlockSyntax? Block => GetRed(ref this.block, 5); /// <summary> /// ExpressionSyntax node representing the body of the lambda. /// Only one of Block or ExpressionBody will be non-null. /// </summary> public override ExpressionSyntax? ExpressionBody => GetRed(ref this.expressionBody, 6); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.returnType, 2), 3 => GetRed(ref this.parameterList, 3)!, 5 => GetRed(ref this.block, 5), 6 => GetRed(ref this.expressionBody, 6), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.returnType, 3 => this.parameterList, 5 => this.block, 6 => this.expressionBody, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitParenthesizedLambdaExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitParenthesizedLambdaExpression(this); public ParenthesizedLambdaExpressionSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, TypeSyntax? returnType, ParameterListSyntax parameterList, SyntaxToken arrowToken, BlockSyntax? block, ExpressionSyntax? expressionBody) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || returnType != this.ReturnType || parameterList != this.ParameterList || arrowToken != this.ArrowToken || block != this.Block || expressionBody != this.ExpressionBody) { var newNode = SyntaxFactory.ParenthesizedLambdaExpression(attributeLists, modifiers, returnType, parameterList, arrowToken, block, expressionBody); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override LambdaExpressionSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new ParenthesizedLambdaExpressionSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.ReturnType, this.ParameterList, this.ArrowToken, this.Block, this.ExpressionBody); internal override AnonymousFunctionExpressionSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new ParenthesizedLambdaExpressionSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.ReturnType, this.ParameterList, this.ArrowToken, this.Block, this.ExpressionBody); public ParenthesizedLambdaExpressionSyntax WithReturnType(TypeSyntax? returnType) => Update(this.AttributeLists, this.Modifiers, returnType, this.ParameterList, this.ArrowToken, this.Block, this.ExpressionBody); public ParenthesizedLambdaExpressionSyntax WithParameterList(ParameterListSyntax parameterList) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, parameterList, this.ArrowToken, this.Block, this.ExpressionBody); internal override LambdaExpressionSyntax WithArrowTokenCore(SyntaxToken arrowToken) => WithArrowToken(arrowToken); public new ParenthesizedLambdaExpressionSyntax WithArrowToken(SyntaxToken arrowToken) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.ParameterList, arrowToken, this.Block, this.ExpressionBody); internal override AnonymousFunctionExpressionSyntax WithBlockCore(BlockSyntax? block) => WithBlock(block); public new ParenthesizedLambdaExpressionSyntax WithBlock(BlockSyntax? block) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.ParameterList, this.ArrowToken, block, this.ExpressionBody); internal override AnonymousFunctionExpressionSyntax WithExpressionBodyCore(ExpressionSyntax? expressionBody) => WithExpressionBody(expressionBody); public new ParenthesizedLambdaExpressionSyntax WithExpressionBody(ExpressionSyntax? expressionBody) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.ParameterList, this.ArrowToken, this.Block, expressionBody); internal override LambdaExpressionSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new ParenthesizedLambdaExpressionSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override AnonymousFunctionExpressionSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new ParenthesizedLambdaExpressionSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); public ParenthesizedLambdaExpressionSyntax AddParameterListParameters(params ParameterSyntax[] items) => WithParameterList(this.ParameterList.WithParameters(this.ParameterList.Parameters.AddRange(items))); internal override AnonymousFunctionExpressionSyntax AddBlockAttributeListsCore(params AttributeListSyntax[] items) => AddBlockAttributeLists(items); public new ParenthesizedLambdaExpressionSyntax AddBlockAttributeLists(params AttributeListSyntax[] items) { var block = this.Block ?? SyntaxFactory.Block(); return WithBlock(block.WithAttributeLists(block.AttributeLists.AddRange(items))); } internal override AnonymousFunctionExpressionSyntax AddBlockStatementsCore(params StatementSyntax[] items) => AddBlockStatements(items); public new ParenthesizedLambdaExpressionSyntax AddBlockStatements(params StatementSyntax[] items) { var block = this.Block ?? SyntaxFactory.Block(); return WithBlock(block.WithStatements(block.Statements.AddRange(items))); } } /// <summary>Class which represents the syntax node for initializer expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ObjectInitializerExpression"/></description></item> /// <item><description><see cref="SyntaxKind.CollectionInitializerExpression"/></description></item> /// <item><description><see cref="SyntaxKind.ArrayInitializerExpression"/></description></item> /// <item><description><see cref="SyntaxKind.ComplexElementInitializerExpression"/></description></item> /// <item><description><see cref="SyntaxKind.WithInitializerExpression"/></description></item> /// </list> /// </remarks> public sealed partial class InitializerExpressionSyntax : ExpressionSyntax { private SyntaxNode? expressions; internal InitializerExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the open brace.</summary> public SyntaxToken OpenBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.InitializerExpressionSyntax)this.Green).openBraceToken, Position, 0); /// <summary>SeparatedSyntaxList of ExpressionSyntax representing the list of expressions in the initializer expression.</summary> public SeparatedSyntaxList<ExpressionSyntax> Expressions { get { var red = GetRed(ref this.expressions, 1); return red != null ? new SeparatedSyntaxList<ExpressionSyntax>(red, GetChildIndex(1)) : default; } } /// <summary>SyntaxToken representing the close brace.</summary> public SyntaxToken CloseBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.InitializerExpressionSyntax)this.Green).closeBraceToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.expressions, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.expressions : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitInitializerExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitInitializerExpression(this); public InitializerExpressionSyntax Update(SyntaxToken openBraceToken, SeparatedSyntaxList<ExpressionSyntax> expressions, SyntaxToken closeBraceToken) { if (openBraceToken != this.OpenBraceToken || expressions != this.Expressions || closeBraceToken != this.CloseBraceToken) { var newNode = SyntaxFactory.InitializerExpression(this.Kind(), openBraceToken, expressions, closeBraceToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public InitializerExpressionSyntax WithOpenBraceToken(SyntaxToken openBraceToken) => Update(openBraceToken, this.Expressions, this.CloseBraceToken); public InitializerExpressionSyntax WithExpressions(SeparatedSyntaxList<ExpressionSyntax> expressions) => Update(this.OpenBraceToken, expressions, this.CloseBraceToken); public InitializerExpressionSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) => Update(this.OpenBraceToken, this.Expressions, closeBraceToken); public InitializerExpressionSyntax AddExpressions(params ExpressionSyntax[] items) => WithExpressions(this.Expressions.AddRange(items)); } public abstract partial class BaseObjectCreationExpressionSyntax : ExpressionSyntax { internal BaseObjectCreationExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the new keyword.</summary> public abstract SyntaxToken NewKeyword { get; } public BaseObjectCreationExpressionSyntax WithNewKeyword(SyntaxToken newKeyword) => WithNewKeywordCore(newKeyword); internal abstract BaseObjectCreationExpressionSyntax WithNewKeywordCore(SyntaxToken newKeyword); /// <summary>ArgumentListSyntax representing the list of arguments passed as part of the object creation expression.</summary> public abstract ArgumentListSyntax? ArgumentList { get; } public BaseObjectCreationExpressionSyntax WithArgumentList(ArgumentListSyntax? argumentList) => WithArgumentListCore(argumentList); internal abstract BaseObjectCreationExpressionSyntax WithArgumentListCore(ArgumentListSyntax? argumentList); public BaseObjectCreationExpressionSyntax AddArgumentListArguments(params ArgumentSyntax[] items) => AddArgumentListArgumentsCore(items); internal abstract BaseObjectCreationExpressionSyntax AddArgumentListArgumentsCore(params ArgumentSyntax[] items); /// <summary>InitializerExpressionSyntax representing the initializer expression for the object being created.</summary> public abstract InitializerExpressionSyntax? Initializer { get; } public BaseObjectCreationExpressionSyntax WithInitializer(InitializerExpressionSyntax? initializer) => WithInitializerCore(initializer); internal abstract BaseObjectCreationExpressionSyntax WithInitializerCore(InitializerExpressionSyntax? initializer); } /// <summary>Class which represents the syntax node for implicit object creation expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ImplicitObjectCreationExpression"/></description></item> /// </list> /// </remarks> public sealed partial class ImplicitObjectCreationExpressionSyntax : BaseObjectCreationExpressionSyntax { private ArgumentListSyntax? argumentList; private InitializerExpressionSyntax? initializer; internal ImplicitObjectCreationExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the new keyword.</summary> public override SyntaxToken NewKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ImplicitObjectCreationExpressionSyntax)this.Green).newKeyword, Position, 0); /// <summary>ArgumentListSyntax representing the list of arguments passed as part of the object creation expression.</summary> public override ArgumentListSyntax ArgumentList => GetRed(ref this.argumentList, 1)!; /// <summary>InitializerExpressionSyntax representing the initializer expression for the object being created.</summary> public override InitializerExpressionSyntax? Initializer => GetRed(ref this.initializer, 2); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 1 => GetRed(ref this.argumentList, 1)!, 2 => GetRed(ref this.initializer, 2), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 1 => this.argumentList, 2 => this.initializer, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitImplicitObjectCreationExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitImplicitObjectCreationExpression(this); public ImplicitObjectCreationExpressionSyntax Update(SyntaxToken newKeyword, ArgumentListSyntax argumentList, InitializerExpressionSyntax? initializer) { if (newKeyword != this.NewKeyword || argumentList != this.ArgumentList || initializer != this.Initializer) { var newNode = SyntaxFactory.ImplicitObjectCreationExpression(newKeyword, argumentList, initializer); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override BaseObjectCreationExpressionSyntax WithNewKeywordCore(SyntaxToken newKeyword) => WithNewKeyword(newKeyword); public new ImplicitObjectCreationExpressionSyntax WithNewKeyword(SyntaxToken newKeyword) => Update(newKeyword, this.ArgumentList, this.Initializer); internal override BaseObjectCreationExpressionSyntax WithArgumentListCore(ArgumentListSyntax? argumentList) => WithArgumentList(argumentList ?? throw new ArgumentNullException(nameof(argumentList))); public new ImplicitObjectCreationExpressionSyntax WithArgumentList(ArgumentListSyntax argumentList) => Update(this.NewKeyword, argumentList, this.Initializer); internal override BaseObjectCreationExpressionSyntax WithInitializerCore(InitializerExpressionSyntax? initializer) => WithInitializer(initializer); public new ImplicitObjectCreationExpressionSyntax WithInitializer(InitializerExpressionSyntax? initializer) => Update(this.NewKeyword, this.ArgumentList, initializer); internal override BaseObjectCreationExpressionSyntax AddArgumentListArgumentsCore(params ArgumentSyntax[] items) => AddArgumentListArguments(items); public new ImplicitObjectCreationExpressionSyntax AddArgumentListArguments(params ArgumentSyntax[] items) => WithArgumentList(this.ArgumentList.WithArguments(this.ArgumentList.Arguments.AddRange(items))); } /// <summary>Class which represents the syntax node for object creation expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ObjectCreationExpression"/></description></item> /// </list> /// </remarks> public sealed partial class ObjectCreationExpressionSyntax : BaseObjectCreationExpressionSyntax { private TypeSyntax? type; private ArgumentListSyntax? argumentList; private InitializerExpressionSyntax? initializer; internal ObjectCreationExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the new keyword.</summary> public override SyntaxToken NewKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ObjectCreationExpressionSyntax)this.Green).newKeyword, Position, 0); /// <summary>TypeSyntax representing the type of the object being created.</summary> public TypeSyntax Type => GetRed(ref this.type, 1)!; /// <summary>ArgumentListSyntax representing the list of arguments passed as part of the object creation expression.</summary> public override ArgumentListSyntax? ArgumentList => GetRed(ref this.argumentList, 2); /// <summary>InitializerExpressionSyntax representing the initializer expression for the object being created.</summary> public override InitializerExpressionSyntax? Initializer => GetRed(ref this.initializer, 3); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 1 => GetRed(ref this.type, 1)!, 2 => GetRed(ref this.argumentList, 2), 3 => GetRed(ref this.initializer, 3), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 1 => this.type, 2 => this.argumentList, 3 => this.initializer, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitObjectCreationExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitObjectCreationExpression(this); public ObjectCreationExpressionSyntax Update(SyntaxToken newKeyword, TypeSyntax type, ArgumentListSyntax? argumentList, InitializerExpressionSyntax? initializer) { if (newKeyword != this.NewKeyword || type != this.Type || argumentList != this.ArgumentList || initializer != this.Initializer) { var newNode = SyntaxFactory.ObjectCreationExpression(newKeyword, type, argumentList, initializer); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override BaseObjectCreationExpressionSyntax WithNewKeywordCore(SyntaxToken newKeyword) => WithNewKeyword(newKeyword); public new ObjectCreationExpressionSyntax WithNewKeyword(SyntaxToken newKeyword) => Update(newKeyword, this.Type, this.ArgumentList, this.Initializer); public ObjectCreationExpressionSyntax WithType(TypeSyntax type) => Update(this.NewKeyword, type, this.ArgumentList, this.Initializer); internal override BaseObjectCreationExpressionSyntax WithArgumentListCore(ArgumentListSyntax? argumentList) => WithArgumentList(argumentList); public new ObjectCreationExpressionSyntax WithArgumentList(ArgumentListSyntax? argumentList) => Update(this.NewKeyword, this.Type, argumentList, this.Initializer); internal override BaseObjectCreationExpressionSyntax WithInitializerCore(InitializerExpressionSyntax? initializer) => WithInitializer(initializer); public new ObjectCreationExpressionSyntax WithInitializer(InitializerExpressionSyntax? initializer) => Update(this.NewKeyword, this.Type, this.ArgumentList, initializer); internal override BaseObjectCreationExpressionSyntax AddArgumentListArgumentsCore(params ArgumentSyntax[] items) => AddArgumentListArguments(items); public new ObjectCreationExpressionSyntax AddArgumentListArguments(params ArgumentSyntax[] items) { var argumentList = this.ArgumentList ?? SyntaxFactory.ArgumentList(); return WithArgumentList(argumentList.WithArguments(argumentList.Arguments.AddRange(items))); } } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.WithExpression"/></description></item> /// </list> /// </remarks> public sealed partial class WithExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? expression; private InitializerExpressionSyntax? initializer; internal WithExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public ExpressionSyntax Expression => GetRedAtZero(ref this.expression)!; public SyntaxToken WithKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.WithExpressionSyntax)this.Green).withKeyword, GetChildPosition(1), GetChildIndex(1)); /// <summary>InitializerExpressionSyntax representing the initializer expression for the with expression.</summary> public InitializerExpressionSyntax Initializer => GetRed(ref this.initializer, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.expression)!, 2 => GetRed(ref this.initializer, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.expression, 2 => this.initializer, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitWithExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitWithExpression(this); public WithExpressionSyntax Update(ExpressionSyntax expression, SyntaxToken withKeyword, InitializerExpressionSyntax initializer) { if (expression != this.Expression || withKeyword != this.WithKeyword || initializer != this.Initializer) { var newNode = SyntaxFactory.WithExpression(expression, withKeyword, initializer); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public WithExpressionSyntax WithExpression(ExpressionSyntax expression) => Update(expression, this.WithKeyword, this.Initializer); public WithExpressionSyntax WithWithKeyword(SyntaxToken withKeyword) => Update(this.Expression, withKeyword, this.Initializer); public WithExpressionSyntax WithInitializer(InitializerExpressionSyntax initializer) => Update(this.Expression, this.WithKeyword, initializer); public WithExpressionSyntax AddInitializerExpressions(params ExpressionSyntax[] items) => WithInitializer(this.Initializer.WithExpressions(this.Initializer.Expressions.AddRange(items))); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.AnonymousObjectMemberDeclarator"/></description></item> /// </list> /// </remarks> public sealed partial class AnonymousObjectMemberDeclaratorSyntax : CSharpSyntaxNode { private NameEqualsSyntax? nameEquals; private ExpressionSyntax? expression; internal AnonymousObjectMemberDeclaratorSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>NameEqualsSyntax representing the optional name of the member being initialized.</summary> public NameEqualsSyntax? NameEquals => GetRedAtZero(ref this.nameEquals); /// <summary>ExpressionSyntax representing the value the member is initialized with.</summary> public ExpressionSyntax Expression => GetRed(ref this.expression, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.nameEquals), 1 => GetRed(ref this.expression, 1)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.nameEquals, 1 => this.expression, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitAnonymousObjectMemberDeclarator(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitAnonymousObjectMemberDeclarator(this); public AnonymousObjectMemberDeclaratorSyntax Update(NameEqualsSyntax? nameEquals, ExpressionSyntax expression) { if (nameEquals != this.NameEquals || expression != this.Expression) { var newNode = SyntaxFactory.AnonymousObjectMemberDeclarator(nameEquals, expression); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public AnonymousObjectMemberDeclaratorSyntax WithNameEquals(NameEqualsSyntax? nameEquals) => Update(nameEquals, this.Expression); public AnonymousObjectMemberDeclaratorSyntax WithExpression(ExpressionSyntax expression) => Update(this.NameEquals, expression); } /// <summary>Class which represents the syntax node for anonymous object creation expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.AnonymousObjectCreationExpression"/></description></item> /// </list> /// </remarks> public sealed partial class AnonymousObjectCreationExpressionSyntax : ExpressionSyntax { private SyntaxNode? initializers; internal AnonymousObjectCreationExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the new keyword.</summary> public SyntaxToken NewKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.AnonymousObjectCreationExpressionSyntax)this.Green).newKeyword, Position, 0); /// <summary>SyntaxToken representing the open brace.</summary> public SyntaxToken OpenBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.AnonymousObjectCreationExpressionSyntax)this.Green).openBraceToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>SeparatedSyntaxList of AnonymousObjectMemberDeclaratorSyntax representing the list of object member initializers.</summary> public SeparatedSyntaxList<AnonymousObjectMemberDeclaratorSyntax> Initializers { get { var red = GetRed(ref this.initializers, 2); return red != null ? new SeparatedSyntaxList<AnonymousObjectMemberDeclaratorSyntax>(red, GetChildIndex(2)) : default; } } /// <summary>SyntaxToken representing the close brace.</summary> public SyntaxToken CloseBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.AnonymousObjectCreationExpressionSyntax)this.Green).closeBraceToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => index == 2 ? GetRed(ref this.initializers, 2)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 2 ? this.initializers : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitAnonymousObjectCreationExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitAnonymousObjectCreationExpression(this); public AnonymousObjectCreationExpressionSyntax Update(SyntaxToken newKeyword, SyntaxToken openBraceToken, SeparatedSyntaxList<AnonymousObjectMemberDeclaratorSyntax> initializers, SyntaxToken closeBraceToken) { if (newKeyword != this.NewKeyword || openBraceToken != this.OpenBraceToken || initializers != this.Initializers || closeBraceToken != this.CloseBraceToken) { var newNode = SyntaxFactory.AnonymousObjectCreationExpression(newKeyword, openBraceToken, initializers, closeBraceToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public AnonymousObjectCreationExpressionSyntax WithNewKeyword(SyntaxToken newKeyword) => Update(newKeyword, this.OpenBraceToken, this.Initializers, this.CloseBraceToken); public AnonymousObjectCreationExpressionSyntax WithOpenBraceToken(SyntaxToken openBraceToken) => Update(this.NewKeyword, openBraceToken, this.Initializers, this.CloseBraceToken); public AnonymousObjectCreationExpressionSyntax WithInitializers(SeparatedSyntaxList<AnonymousObjectMemberDeclaratorSyntax> initializers) => Update(this.NewKeyword, this.OpenBraceToken, initializers, this.CloseBraceToken); public AnonymousObjectCreationExpressionSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) => Update(this.NewKeyword, this.OpenBraceToken, this.Initializers, closeBraceToken); public AnonymousObjectCreationExpressionSyntax AddInitializers(params AnonymousObjectMemberDeclaratorSyntax[] items) => WithInitializers(this.Initializers.AddRange(items)); } /// <summary>Class which represents the syntax node for array creation expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ArrayCreationExpression"/></description></item> /// </list> /// </remarks> public sealed partial class ArrayCreationExpressionSyntax : ExpressionSyntax { private ArrayTypeSyntax? type; private InitializerExpressionSyntax? initializer; internal ArrayCreationExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the new keyword.</summary> public SyntaxToken NewKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ArrayCreationExpressionSyntax)this.Green).newKeyword, Position, 0); /// <summary>ArrayTypeSyntax node representing the type of the array.</summary> public ArrayTypeSyntax Type => GetRed(ref this.type, 1)!; /// <summary>InitializerExpressionSyntax node representing the initializer of the array creation expression.</summary> public InitializerExpressionSyntax? Initializer => GetRed(ref this.initializer, 2); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 1 => GetRed(ref this.type, 1)!, 2 => GetRed(ref this.initializer, 2), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 1 => this.type, 2 => this.initializer, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitArrayCreationExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitArrayCreationExpression(this); public ArrayCreationExpressionSyntax Update(SyntaxToken newKeyword, ArrayTypeSyntax type, InitializerExpressionSyntax? initializer) { if (newKeyword != this.NewKeyword || type != this.Type || initializer != this.Initializer) { var newNode = SyntaxFactory.ArrayCreationExpression(newKeyword, type, initializer); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ArrayCreationExpressionSyntax WithNewKeyword(SyntaxToken newKeyword) => Update(newKeyword, this.Type, this.Initializer); public ArrayCreationExpressionSyntax WithType(ArrayTypeSyntax type) => Update(this.NewKeyword, type, this.Initializer); public ArrayCreationExpressionSyntax WithInitializer(InitializerExpressionSyntax? initializer) => Update(this.NewKeyword, this.Type, initializer); public ArrayCreationExpressionSyntax AddTypeRankSpecifiers(params ArrayRankSpecifierSyntax[] items) => WithType(this.Type.WithRankSpecifiers(this.Type.RankSpecifiers.AddRange(items))); } /// <summary>Class which represents the syntax node for implicit array creation expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ImplicitArrayCreationExpression"/></description></item> /// </list> /// </remarks> public sealed partial class ImplicitArrayCreationExpressionSyntax : ExpressionSyntax { private InitializerExpressionSyntax? initializer; internal ImplicitArrayCreationExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the new keyword.</summary> public SyntaxToken NewKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ImplicitArrayCreationExpressionSyntax)this.Green).newKeyword, Position, 0); /// <summary>SyntaxToken representing the open bracket.</summary> public SyntaxToken OpenBracketToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ImplicitArrayCreationExpressionSyntax)this.Green).openBracketToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>SyntaxList of SyntaxToken representing the commas in the implicit array creation expression.</summary> public SyntaxTokenList Commas { get { var slot = this.Green.GetSlot(2); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(2), GetChildIndex(2)) : default; } } /// <summary>SyntaxToken representing the close bracket.</summary> public SyntaxToken CloseBracketToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ImplicitArrayCreationExpressionSyntax)this.Green).closeBracketToken, GetChildPosition(3), GetChildIndex(3)); /// <summary>InitializerExpressionSyntax representing the initializer expression of the implicit array creation expression.</summary> public InitializerExpressionSyntax Initializer => GetRed(ref this.initializer, 4)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 4 ? GetRed(ref this.initializer, 4)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 4 ? this.initializer : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitImplicitArrayCreationExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitImplicitArrayCreationExpression(this); public ImplicitArrayCreationExpressionSyntax Update(SyntaxToken newKeyword, SyntaxToken openBracketToken, SyntaxTokenList commas, SyntaxToken closeBracketToken, InitializerExpressionSyntax initializer) { if (newKeyword != this.NewKeyword || openBracketToken != this.OpenBracketToken || commas != this.Commas || closeBracketToken != this.CloseBracketToken || initializer != this.Initializer) { var newNode = SyntaxFactory.ImplicitArrayCreationExpression(newKeyword, openBracketToken, commas, closeBracketToken, initializer); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ImplicitArrayCreationExpressionSyntax WithNewKeyword(SyntaxToken newKeyword) => Update(newKeyword, this.OpenBracketToken, this.Commas, this.CloseBracketToken, this.Initializer); public ImplicitArrayCreationExpressionSyntax WithOpenBracketToken(SyntaxToken openBracketToken) => Update(this.NewKeyword, openBracketToken, this.Commas, this.CloseBracketToken, this.Initializer); public ImplicitArrayCreationExpressionSyntax WithCommas(SyntaxTokenList commas) => Update(this.NewKeyword, this.OpenBracketToken, commas, this.CloseBracketToken, this.Initializer); public ImplicitArrayCreationExpressionSyntax WithCloseBracketToken(SyntaxToken closeBracketToken) => Update(this.NewKeyword, this.OpenBracketToken, this.Commas, closeBracketToken, this.Initializer); public ImplicitArrayCreationExpressionSyntax WithInitializer(InitializerExpressionSyntax initializer) => Update(this.NewKeyword, this.OpenBracketToken, this.Commas, this.CloseBracketToken, initializer); public ImplicitArrayCreationExpressionSyntax AddCommas(params SyntaxToken[] items) => WithCommas(this.Commas.AddRange(items)); public ImplicitArrayCreationExpressionSyntax AddInitializerExpressions(params ExpressionSyntax[] items) => WithInitializer(this.Initializer.WithExpressions(this.Initializer.Expressions.AddRange(items))); } /// <summary>Class which represents the syntax node for stackalloc array creation expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.StackAllocArrayCreationExpression"/></description></item> /// </list> /// </remarks> public sealed partial class StackAllocArrayCreationExpressionSyntax : ExpressionSyntax { private TypeSyntax? type; private InitializerExpressionSyntax? initializer; internal StackAllocArrayCreationExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the stackalloc keyword.</summary> public SyntaxToken StackAllocKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.StackAllocArrayCreationExpressionSyntax)this.Green).stackAllocKeyword, Position, 0); /// <summary>TypeSyntax node representing the type of the stackalloc array.</summary> public TypeSyntax Type => GetRed(ref this.type, 1)!; /// <summary>InitializerExpressionSyntax node representing the initializer of the stackalloc array creation expression.</summary> public InitializerExpressionSyntax? Initializer => GetRed(ref this.initializer, 2); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 1 => GetRed(ref this.type, 1)!, 2 => GetRed(ref this.initializer, 2), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 1 => this.type, 2 => this.initializer, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitStackAllocArrayCreationExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitStackAllocArrayCreationExpression(this); public StackAllocArrayCreationExpressionSyntax Update(SyntaxToken stackAllocKeyword, TypeSyntax type, InitializerExpressionSyntax? initializer) { if (stackAllocKeyword != this.StackAllocKeyword || type != this.Type || initializer != this.Initializer) { var newNode = SyntaxFactory.StackAllocArrayCreationExpression(stackAllocKeyword, type, initializer); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public StackAllocArrayCreationExpressionSyntax WithStackAllocKeyword(SyntaxToken stackAllocKeyword) => Update(stackAllocKeyword, this.Type, this.Initializer); public StackAllocArrayCreationExpressionSyntax WithType(TypeSyntax type) => Update(this.StackAllocKeyword, type, this.Initializer); public StackAllocArrayCreationExpressionSyntax WithInitializer(InitializerExpressionSyntax? initializer) => Update(this.StackAllocKeyword, this.Type, initializer); } /// <summary>Class which represents the syntax node for implicit stackalloc array creation expression.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ImplicitStackAllocArrayCreationExpression"/></description></item> /// </list> /// </remarks> public sealed partial class ImplicitStackAllocArrayCreationExpressionSyntax : ExpressionSyntax { private InitializerExpressionSyntax? initializer; internal ImplicitStackAllocArrayCreationExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the stackalloc keyword.</summary> public SyntaxToken StackAllocKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ImplicitStackAllocArrayCreationExpressionSyntax)this.Green).stackAllocKeyword, Position, 0); /// <summary>SyntaxToken representing the open bracket.</summary> public SyntaxToken OpenBracketToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ImplicitStackAllocArrayCreationExpressionSyntax)this.Green).openBracketToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>SyntaxToken representing the close bracket.</summary> public SyntaxToken CloseBracketToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ImplicitStackAllocArrayCreationExpressionSyntax)this.Green).closeBracketToken, GetChildPosition(2), GetChildIndex(2)); /// <summary>InitializerExpressionSyntax representing the initializer expression of the implicit stackalloc array creation expression.</summary> public InitializerExpressionSyntax Initializer => GetRed(ref this.initializer, 3)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 3 ? GetRed(ref this.initializer, 3)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 3 ? this.initializer : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitImplicitStackAllocArrayCreationExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitImplicitStackAllocArrayCreationExpression(this); public ImplicitStackAllocArrayCreationExpressionSyntax Update(SyntaxToken stackAllocKeyword, SyntaxToken openBracketToken, SyntaxToken closeBracketToken, InitializerExpressionSyntax initializer) { if (stackAllocKeyword != this.StackAllocKeyword || openBracketToken != this.OpenBracketToken || closeBracketToken != this.CloseBracketToken || initializer != this.Initializer) { var newNode = SyntaxFactory.ImplicitStackAllocArrayCreationExpression(stackAllocKeyword, openBracketToken, closeBracketToken, initializer); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ImplicitStackAllocArrayCreationExpressionSyntax WithStackAllocKeyword(SyntaxToken stackAllocKeyword) => Update(stackAllocKeyword, this.OpenBracketToken, this.CloseBracketToken, this.Initializer); public ImplicitStackAllocArrayCreationExpressionSyntax WithOpenBracketToken(SyntaxToken openBracketToken) => Update(this.StackAllocKeyword, openBracketToken, this.CloseBracketToken, this.Initializer); public ImplicitStackAllocArrayCreationExpressionSyntax WithCloseBracketToken(SyntaxToken closeBracketToken) => Update(this.StackAllocKeyword, this.OpenBracketToken, closeBracketToken, this.Initializer); public ImplicitStackAllocArrayCreationExpressionSyntax WithInitializer(InitializerExpressionSyntax initializer) => Update(this.StackAllocKeyword, this.OpenBracketToken, this.CloseBracketToken, initializer); public ImplicitStackAllocArrayCreationExpressionSyntax AddInitializerExpressions(params ExpressionSyntax[] items) => WithInitializer(this.Initializer.WithExpressions(this.Initializer.Expressions.AddRange(items))); } public abstract partial class QueryClauseSyntax : CSharpSyntaxNode { internal QueryClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } } public abstract partial class SelectOrGroupClauseSyntax : CSharpSyntaxNode { internal SelectOrGroupClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.QueryExpression"/></description></item> /// </list> /// </remarks> public sealed partial class QueryExpressionSyntax : ExpressionSyntax { private FromClauseSyntax? fromClause; private QueryBodySyntax? body; internal QueryExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public FromClauseSyntax FromClause => GetRedAtZero(ref this.fromClause)!; public QueryBodySyntax Body => GetRed(ref this.body, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.fromClause)!, 1 => GetRed(ref this.body, 1)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.fromClause, 1 => this.body, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitQueryExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitQueryExpression(this); public QueryExpressionSyntax Update(FromClauseSyntax fromClause, QueryBodySyntax body) { if (fromClause != this.FromClause || body != this.Body) { var newNode = SyntaxFactory.QueryExpression(fromClause, body); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public QueryExpressionSyntax WithFromClause(FromClauseSyntax fromClause) => Update(fromClause, this.Body); public QueryExpressionSyntax WithBody(QueryBodySyntax body) => Update(this.FromClause, body); public QueryExpressionSyntax AddBodyClauses(params QueryClauseSyntax[] items) => WithBody(this.Body.WithClauses(this.Body.Clauses.AddRange(items))); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.QueryBody"/></description></item> /// </list> /// </remarks> public sealed partial class QueryBodySyntax : CSharpSyntaxNode { private SyntaxNode? clauses; private SelectOrGroupClauseSyntax? selectOrGroup; private QueryContinuationSyntax? continuation; internal QueryBodySyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxList<QueryClauseSyntax> Clauses => new SyntaxList<QueryClauseSyntax>(GetRed(ref this.clauses, 0)); public SelectOrGroupClauseSyntax SelectOrGroup => GetRed(ref this.selectOrGroup, 1)!; public QueryContinuationSyntax? Continuation => GetRed(ref this.continuation, 2); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.clauses)!, 1 => GetRed(ref this.selectOrGroup, 1)!, 2 => GetRed(ref this.continuation, 2), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.clauses, 1 => this.selectOrGroup, 2 => this.continuation, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitQueryBody(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitQueryBody(this); public QueryBodySyntax Update(SyntaxList<QueryClauseSyntax> clauses, SelectOrGroupClauseSyntax selectOrGroup, QueryContinuationSyntax? continuation) { if (clauses != this.Clauses || selectOrGroup != this.SelectOrGroup || continuation != this.Continuation) { var newNode = SyntaxFactory.QueryBody(clauses, selectOrGroup, continuation); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public QueryBodySyntax WithClauses(SyntaxList<QueryClauseSyntax> clauses) => Update(clauses, this.SelectOrGroup, this.Continuation); public QueryBodySyntax WithSelectOrGroup(SelectOrGroupClauseSyntax selectOrGroup) => Update(this.Clauses, selectOrGroup, this.Continuation); public QueryBodySyntax WithContinuation(QueryContinuationSyntax? continuation) => Update(this.Clauses, this.SelectOrGroup, continuation); public QueryBodySyntax AddClauses(params QueryClauseSyntax[] items) => WithClauses(this.Clauses.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.FromClause"/></description></item> /// </list> /// </remarks> public sealed partial class FromClauseSyntax : QueryClauseSyntax { private TypeSyntax? type; private ExpressionSyntax? expression; internal FromClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken FromKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.FromClauseSyntax)this.Green).fromKeyword, Position, 0); public TypeSyntax? Type => GetRed(ref this.type, 1); /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.FromClauseSyntax)this.Green).identifier, GetChildPosition(2), GetChildIndex(2)); public SyntaxToken InKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.FromClauseSyntax)this.Green).inKeyword, GetChildPosition(3), GetChildIndex(3)); public ExpressionSyntax Expression => GetRed(ref this.expression, 4)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 1 => GetRed(ref this.type, 1), 4 => GetRed(ref this.expression, 4)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 1 => this.type, 4 => this.expression, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitFromClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitFromClause(this); public FromClauseSyntax Update(SyntaxToken fromKeyword, TypeSyntax? type, SyntaxToken identifier, SyntaxToken inKeyword, ExpressionSyntax expression) { if (fromKeyword != this.FromKeyword || type != this.Type || identifier != this.Identifier || inKeyword != this.InKeyword || expression != this.Expression) { var newNode = SyntaxFactory.FromClause(fromKeyword, type, identifier, inKeyword, expression); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public FromClauseSyntax WithFromKeyword(SyntaxToken fromKeyword) => Update(fromKeyword, this.Type, this.Identifier, this.InKeyword, this.Expression); public FromClauseSyntax WithType(TypeSyntax? type) => Update(this.FromKeyword, type, this.Identifier, this.InKeyword, this.Expression); public FromClauseSyntax WithIdentifier(SyntaxToken identifier) => Update(this.FromKeyword, this.Type, identifier, this.InKeyword, this.Expression); public FromClauseSyntax WithInKeyword(SyntaxToken inKeyword) => Update(this.FromKeyword, this.Type, this.Identifier, inKeyword, this.Expression); public FromClauseSyntax WithExpression(ExpressionSyntax expression) => Update(this.FromKeyword, this.Type, this.Identifier, this.InKeyword, expression); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.LetClause"/></description></item> /// </list> /// </remarks> public sealed partial class LetClauseSyntax : QueryClauseSyntax { private ExpressionSyntax? expression; internal LetClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken LetKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.LetClauseSyntax)this.Green).letKeyword, Position, 0); /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.LetClauseSyntax)this.Green).identifier, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken EqualsToken => new SyntaxToken(this, ((Syntax.InternalSyntax.LetClauseSyntax)this.Green).equalsToken, GetChildPosition(2), GetChildIndex(2)); public ExpressionSyntax Expression => GetRed(ref this.expression, 3)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 3 ? GetRed(ref this.expression, 3)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 3 ? this.expression : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitLetClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitLetClause(this); public LetClauseSyntax Update(SyntaxToken letKeyword, SyntaxToken identifier, SyntaxToken equalsToken, ExpressionSyntax expression) { if (letKeyword != this.LetKeyword || identifier != this.Identifier || equalsToken != this.EqualsToken || expression != this.Expression) { var newNode = SyntaxFactory.LetClause(letKeyword, identifier, equalsToken, expression); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public LetClauseSyntax WithLetKeyword(SyntaxToken letKeyword) => Update(letKeyword, this.Identifier, this.EqualsToken, this.Expression); public LetClauseSyntax WithIdentifier(SyntaxToken identifier) => Update(this.LetKeyword, identifier, this.EqualsToken, this.Expression); public LetClauseSyntax WithEqualsToken(SyntaxToken equalsToken) => Update(this.LetKeyword, this.Identifier, equalsToken, this.Expression); public LetClauseSyntax WithExpression(ExpressionSyntax expression) => Update(this.LetKeyword, this.Identifier, this.EqualsToken, expression); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.JoinClause"/></description></item> /// </list> /// </remarks> public sealed partial class JoinClauseSyntax : QueryClauseSyntax { private TypeSyntax? type; private ExpressionSyntax? inExpression; private ExpressionSyntax? leftExpression; private ExpressionSyntax? rightExpression; private JoinIntoClauseSyntax? into; internal JoinClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken JoinKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.JoinClauseSyntax)this.Green).joinKeyword, Position, 0); public TypeSyntax? Type => GetRed(ref this.type, 1); /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.JoinClauseSyntax)this.Green).identifier, GetChildPosition(2), GetChildIndex(2)); public SyntaxToken InKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.JoinClauseSyntax)this.Green).inKeyword, GetChildPosition(3), GetChildIndex(3)); public ExpressionSyntax InExpression => GetRed(ref this.inExpression, 4)!; public SyntaxToken OnKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.JoinClauseSyntax)this.Green).onKeyword, GetChildPosition(5), GetChildIndex(5)); public ExpressionSyntax LeftExpression => GetRed(ref this.leftExpression, 6)!; public SyntaxToken EqualsKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.JoinClauseSyntax)this.Green).equalsKeyword, GetChildPosition(7), GetChildIndex(7)); public ExpressionSyntax RightExpression => GetRed(ref this.rightExpression, 8)!; public JoinIntoClauseSyntax? Into => GetRed(ref this.into, 9); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 1 => GetRed(ref this.type, 1), 4 => GetRed(ref this.inExpression, 4)!, 6 => GetRed(ref this.leftExpression, 6)!, 8 => GetRed(ref this.rightExpression, 8)!, 9 => GetRed(ref this.into, 9), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 1 => this.type, 4 => this.inExpression, 6 => this.leftExpression, 8 => this.rightExpression, 9 => this.into, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitJoinClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitJoinClause(this); public JoinClauseSyntax Update(SyntaxToken joinKeyword, TypeSyntax? type, SyntaxToken identifier, SyntaxToken inKeyword, ExpressionSyntax inExpression, SyntaxToken onKeyword, ExpressionSyntax leftExpression, SyntaxToken equalsKeyword, ExpressionSyntax rightExpression, JoinIntoClauseSyntax? into) { if (joinKeyword != this.JoinKeyword || type != this.Type || identifier != this.Identifier || inKeyword != this.InKeyword || inExpression != this.InExpression || onKeyword != this.OnKeyword || leftExpression != this.LeftExpression || equalsKeyword != this.EqualsKeyword || rightExpression != this.RightExpression || into != this.Into) { var newNode = SyntaxFactory.JoinClause(joinKeyword, type, identifier, inKeyword, inExpression, onKeyword, leftExpression, equalsKeyword, rightExpression, into); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public JoinClauseSyntax WithJoinKeyword(SyntaxToken joinKeyword) => Update(joinKeyword, this.Type, this.Identifier, this.InKeyword, this.InExpression, this.OnKeyword, this.LeftExpression, this.EqualsKeyword, this.RightExpression, this.Into); public JoinClauseSyntax WithType(TypeSyntax? type) => Update(this.JoinKeyword, type, this.Identifier, this.InKeyword, this.InExpression, this.OnKeyword, this.LeftExpression, this.EqualsKeyword, this.RightExpression, this.Into); public JoinClauseSyntax WithIdentifier(SyntaxToken identifier) => Update(this.JoinKeyword, this.Type, identifier, this.InKeyword, this.InExpression, this.OnKeyword, this.LeftExpression, this.EqualsKeyword, this.RightExpression, this.Into); public JoinClauseSyntax WithInKeyword(SyntaxToken inKeyword) => Update(this.JoinKeyword, this.Type, this.Identifier, inKeyword, this.InExpression, this.OnKeyword, this.LeftExpression, this.EqualsKeyword, this.RightExpression, this.Into); public JoinClauseSyntax WithInExpression(ExpressionSyntax inExpression) => Update(this.JoinKeyword, this.Type, this.Identifier, this.InKeyword, inExpression, this.OnKeyword, this.LeftExpression, this.EqualsKeyword, this.RightExpression, this.Into); public JoinClauseSyntax WithOnKeyword(SyntaxToken onKeyword) => Update(this.JoinKeyword, this.Type, this.Identifier, this.InKeyword, this.InExpression, onKeyword, this.LeftExpression, this.EqualsKeyword, this.RightExpression, this.Into); public JoinClauseSyntax WithLeftExpression(ExpressionSyntax leftExpression) => Update(this.JoinKeyword, this.Type, this.Identifier, this.InKeyword, this.InExpression, this.OnKeyword, leftExpression, this.EqualsKeyword, this.RightExpression, this.Into); public JoinClauseSyntax WithEqualsKeyword(SyntaxToken equalsKeyword) => Update(this.JoinKeyword, this.Type, this.Identifier, this.InKeyword, this.InExpression, this.OnKeyword, this.LeftExpression, equalsKeyword, this.RightExpression, this.Into); public JoinClauseSyntax WithRightExpression(ExpressionSyntax rightExpression) => Update(this.JoinKeyword, this.Type, this.Identifier, this.InKeyword, this.InExpression, this.OnKeyword, this.LeftExpression, this.EqualsKeyword, rightExpression, this.Into); public JoinClauseSyntax WithInto(JoinIntoClauseSyntax? into) => Update(this.JoinKeyword, this.Type, this.Identifier, this.InKeyword, this.InExpression, this.OnKeyword, this.LeftExpression, this.EqualsKeyword, this.RightExpression, into); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.JoinIntoClause"/></description></item> /// </list> /// </remarks> public sealed partial class JoinIntoClauseSyntax : CSharpSyntaxNode { internal JoinIntoClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken IntoKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.JoinIntoClauseSyntax)this.Green).intoKeyword, Position, 0); /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.JoinIntoClauseSyntax)this.Green).identifier, GetChildPosition(1), GetChildIndex(1)); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitJoinIntoClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitJoinIntoClause(this); public JoinIntoClauseSyntax Update(SyntaxToken intoKeyword, SyntaxToken identifier) { if (intoKeyword != this.IntoKeyword || identifier != this.Identifier) { var newNode = SyntaxFactory.JoinIntoClause(intoKeyword, identifier); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public JoinIntoClauseSyntax WithIntoKeyword(SyntaxToken intoKeyword) => Update(intoKeyword, this.Identifier); public JoinIntoClauseSyntax WithIdentifier(SyntaxToken identifier) => Update(this.IntoKeyword, identifier); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.WhereClause"/></description></item> /// </list> /// </remarks> public sealed partial class WhereClauseSyntax : QueryClauseSyntax { private ExpressionSyntax? condition; internal WhereClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken WhereKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.WhereClauseSyntax)this.Green).whereKeyword, Position, 0); public ExpressionSyntax Condition => GetRed(ref this.condition, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.condition, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.condition : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitWhereClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitWhereClause(this); public WhereClauseSyntax Update(SyntaxToken whereKeyword, ExpressionSyntax condition) { if (whereKeyword != this.WhereKeyword || condition != this.Condition) { var newNode = SyntaxFactory.WhereClause(whereKeyword, condition); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public WhereClauseSyntax WithWhereKeyword(SyntaxToken whereKeyword) => Update(whereKeyword, this.Condition); public WhereClauseSyntax WithCondition(ExpressionSyntax condition) => Update(this.WhereKeyword, condition); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.OrderByClause"/></description></item> /// </list> /// </remarks> public sealed partial class OrderByClauseSyntax : QueryClauseSyntax { private SyntaxNode? orderings; internal OrderByClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken OrderByKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.OrderByClauseSyntax)this.Green).orderByKeyword, Position, 0); public SeparatedSyntaxList<OrderingSyntax> Orderings { get { var red = GetRed(ref this.orderings, 1); return red != null ? new SeparatedSyntaxList<OrderingSyntax>(red, GetChildIndex(1)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.orderings, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.orderings : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitOrderByClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitOrderByClause(this); public OrderByClauseSyntax Update(SyntaxToken orderByKeyword, SeparatedSyntaxList<OrderingSyntax> orderings) { if (orderByKeyword != this.OrderByKeyword || orderings != this.Orderings) { var newNode = SyntaxFactory.OrderByClause(orderByKeyword, orderings); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public OrderByClauseSyntax WithOrderByKeyword(SyntaxToken orderByKeyword) => Update(orderByKeyword, this.Orderings); public OrderByClauseSyntax WithOrderings(SeparatedSyntaxList<OrderingSyntax> orderings) => Update(this.OrderByKeyword, orderings); public OrderByClauseSyntax AddOrderings(params OrderingSyntax[] items) => WithOrderings(this.Orderings.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.AscendingOrdering"/></description></item> /// <item><description><see cref="SyntaxKind.DescendingOrdering"/></description></item> /// </list> /// </remarks> public sealed partial class OrderingSyntax : CSharpSyntaxNode { private ExpressionSyntax? expression; internal OrderingSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public ExpressionSyntax Expression => GetRedAtZero(ref this.expression)!; public SyntaxToken AscendingOrDescendingKeyword { get { var slot = ((Syntax.InternalSyntax.OrderingSyntax)this.Green).ascendingOrDescendingKeyword; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.expression)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.expression : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitOrdering(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitOrdering(this); public OrderingSyntax Update(ExpressionSyntax expression, SyntaxToken ascendingOrDescendingKeyword) { if (expression != this.Expression || ascendingOrDescendingKeyword != this.AscendingOrDescendingKeyword) { var newNode = SyntaxFactory.Ordering(this.Kind(), expression, ascendingOrDescendingKeyword); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public OrderingSyntax WithExpression(ExpressionSyntax expression) => Update(expression, this.AscendingOrDescendingKeyword); public OrderingSyntax WithAscendingOrDescendingKeyword(SyntaxToken ascendingOrDescendingKeyword) => Update(this.Expression, ascendingOrDescendingKeyword); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.SelectClause"/></description></item> /// </list> /// </remarks> public sealed partial class SelectClauseSyntax : SelectOrGroupClauseSyntax { private ExpressionSyntax? expression; internal SelectClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken SelectKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.SelectClauseSyntax)this.Green).selectKeyword, Position, 0); public ExpressionSyntax Expression => GetRed(ref this.expression, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.expression, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.expression : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitSelectClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitSelectClause(this); public SelectClauseSyntax Update(SyntaxToken selectKeyword, ExpressionSyntax expression) { if (selectKeyword != this.SelectKeyword || expression != this.Expression) { var newNode = SyntaxFactory.SelectClause(selectKeyword, expression); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public SelectClauseSyntax WithSelectKeyword(SyntaxToken selectKeyword) => Update(selectKeyword, this.Expression); public SelectClauseSyntax WithExpression(ExpressionSyntax expression) => Update(this.SelectKeyword, expression); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.GroupClause"/></description></item> /// </list> /// </remarks> public sealed partial class GroupClauseSyntax : SelectOrGroupClauseSyntax { private ExpressionSyntax? groupExpression; private ExpressionSyntax? byExpression; internal GroupClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken GroupKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.GroupClauseSyntax)this.Green).groupKeyword, Position, 0); public ExpressionSyntax GroupExpression => GetRed(ref this.groupExpression, 1)!; public SyntaxToken ByKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.GroupClauseSyntax)this.Green).byKeyword, GetChildPosition(2), GetChildIndex(2)); public ExpressionSyntax ByExpression => GetRed(ref this.byExpression, 3)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 1 => GetRed(ref this.groupExpression, 1)!, 3 => GetRed(ref this.byExpression, 3)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 1 => this.groupExpression, 3 => this.byExpression, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitGroupClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitGroupClause(this); public GroupClauseSyntax Update(SyntaxToken groupKeyword, ExpressionSyntax groupExpression, SyntaxToken byKeyword, ExpressionSyntax byExpression) { if (groupKeyword != this.GroupKeyword || groupExpression != this.GroupExpression || byKeyword != this.ByKeyword || byExpression != this.ByExpression) { var newNode = SyntaxFactory.GroupClause(groupKeyword, groupExpression, byKeyword, byExpression); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public GroupClauseSyntax WithGroupKeyword(SyntaxToken groupKeyword) => Update(groupKeyword, this.GroupExpression, this.ByKeyword, this.ByExpression); public GroupClauseSyntax WithGroupExpression(ExpressionSyntax groupExpression) => Update(this.GroupKeyword, groupExpression, this.ByKeyword, this.ByExpression); public GroupClauseSyntax WithByKeyword(SyntaxToken byKeyword) => Update(this.GroupKeyword, this.GroupExpression, byKeyword, this.ByExpression); public GroupClauseSyntax WithByExpression(ExpressionSyntax byExpression) => Update(this.GroupKeyword, this.GroupExpression, this.ByKeyword, byExpression); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.QueryContinuation"/></description></item> /// </list> /// </remarks> public sealed partial class QueryContinuationSyntax : CSharpSyntaxNode { private QueryBodySyntax? body; internal QueryContinuationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken IntoKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.QueryContinuationSyntax)this.Green).intoKeyword, Position, 0); /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.QueryContinuationSyntax)this.Green).identifier, GetChildPosition(1), GetChildIndex(1)); public QueryBodySyntax Body => GetRed(ref this.body, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 2 ? GetRed(ref this.body, 2)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 2 ? this.body : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitQueryContinuation(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitQueryContinuation(this); public QueryContinuationSyntax Update(SyntaxToken intoKeyword, SyntaxToken identifier, QueryBodySyntax body) { if (intoKeyword != this.IntoKeyword || identifier != this.Identifier || body != this.Body) { var newNode = SyntaxFactory.QueryContinuation(intoKeyword, identifier, body); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public QueryContinuationSyntax WithIntoKeyword(SyntaxToken intoKeyword) => Update(intoKeyword, this.Identifier, this.Body); public QueryContinuationSyntax WithIdentifier(SyntaxToken identifier) => Update(this.IntoKeyword, identifier, this.Body); public QueryContinuationSyntax WithBody(QueryBodySyntax body) => Update(this.IntoKeyword, this.Identifier, body); public QueryContinuationSyntax AddBodyClauses(params QueryClauseSyntax[] items) => WithBody(this.Body.WithClauses(this.Body.Clauses.AddRange(items))); } /// <summary>Class which represents a placeholder in an array size list.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.OmittedArraySizeExpression"/></description></item> /// </list> /// </remarks> public sealed partial class OmittedArraySizeExpressionSyntax : ExpressionSyntax { internal OmittedArraySizeExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the omitted array size expression.</summary> public SyntaxToken OmittedArraySizeExpressionToken => new SyntaxToken(this, ((Syntax.InternalSyntax.OmittedArraySizeExpressionSyntax)this.Green).omittedArraySizeExpressionToken, Position, 0); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitOmittedArraySizeExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitOmittedArraySizeExpression(this); public OmittedArraySizeExpressionSyntax Update(SyntaxToken omittedArraySizeExpressionToken) { if (omittedArraySizeExpressionToken != this.OmittedArraySizeExpressionToken) { var newNode = SyntaxFactory.OmittedArraySizeExpression(omittedArraySizeExpressionToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public OmittedArraySizeExpressionSyntax WithOmittedArraySizeExpressionToken(SyntaxToken omittedArraySizeExpressionToken) => Update(omittedArraySizeExpressionToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.InterpolatedStringExpression"/></description></item> /// </list> /// </remarks> public sealed partial class InterpolatedStringExpressionSyntax : ExpressionSyntax { private SyntaxNode? contents; internal InterpolatedStringExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>The first part of an interpolated string, $" or $@"</summary> public SyntaxToken StringStartToken => new SyntaxToken(this, ((Syntax.InternalSyntax.InterpolatedStringExpressionSyntax)this.Green).stringStartToken, Position, 0); /// <summary>List of parts of the interpolated string, each one is either a literal part or an interpolation.</summary> public SyntaxList<InterpolatedStringContentSyntax> Contents => new SyntaxList<InterpolatedStringContentSyntax>(GetRed(ref this.contents, 1)); /// <summary>The closing quote of the interpolated string.</summary> public SyntaxToken StringEndToken => new SyntaxToken(this, ((Syntax.InternalSyntax.InterpolatedStringExpressionSyntax)this.Green).stringEndToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.contents, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.contents : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitInterpolatedStringExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitInterpolatedStringExpression(this); public InterpolatedStringExpressionSyntax Update(SyntaxToken stringStartToken, SyntaxList<InterpolatedStringContentSyntax> contents, SyntaxToken stringEndToken) { if (stringStartToken != this.StringStartToken || contents != this.Contents || stringEndToken != this.StringEndToken) { var newNode = SyntaxFactory.InterpolatedStringExpression(stringStartToken, contents, stringEndToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public InterpolatedStringExpressionSyntax WithStringStartToken(SyntaxToken stringStartToken) => Update(stringStartToken, this.Contents, this.StringEndToken); public InterpolatedStringExpressionSyntax WithContents(SyntaxList<InterpolatedStringContentSyntax> contents) => Update(this.StringStartToken, contents, this.StringEndToken); public InterpolatedStringExpressionSyntax WithStringEndToken(SyntaxToken stringEndToken) => Update(this.StringStartToken, this.Contents, stringEndToken); public InterpolatedStringExpressionSyntax AddContents(params InterpolatedStringContentSyntax[] items) => WithContents(this.Contents.AddRange(items)); } /// <summary>Class which represents a simple pattern-matching expression using the "is" keyword.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.IsPatternExpression"/></description></item> /// </list> /// </remarks> public sealed partial class IsPatternExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? expression; private PatternSyntax? pattern; internal IsPatternExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>ExpressionSyntax node representing the expression on the left of the "is" operator.</summary> public ExpressionSyntax Expression => GetRedAtZero(ref this.expression)!; public SyntaxToken IsKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.IsPatternExpressionSyntax)this.Green).isKeyword, GetChildPosition(1), GetChildIndex(1)); /// <summary>PatternSyntax node representing the pattern on the right of the "is" operator.</summary> public PatternSyntax Pattern => GetRed(ref this.pattern, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.expression)!, 2 => GetRed(ref this.pattern, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.expression, 2 => this.pattern, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitIsPatternExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitIsPatternExpression(this); public IsPatternExpressionSyntax Update(ExpressionSyntax expression, SyntaxToken isKeyword, PatternSyntax pattern) { if (expression != this.Expression || isKeyword != this.IsKeyword || pattern != this.Pattern) { var newNode = SyntaxFactory.IsPatternExpression(expression, isKeyword, pattern); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public IsPatternExpressionSyntax WithExpression(ExpressionSyntax expression) => Update(expression, this.IsKeyword, this.Pattern); public IsPatternExpressionSyntax WithIsKeyword(SyntaxToken isKeyword) => Update(this.Expression, isKeyword, this.Pattern); public IsPatternExpressionSyntax WithPattern(PatternSyntax pattern) => Update(this.Expression, this.IsKeyword, pattern); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ThrowExpression"/></description></item> /// </list> /// </remarks> public sealed partial class ThrowExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? expression; internal ThrowExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken ThrowKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ThrowExpressionSyntax)this.Green).throwKeyword, Position, 0); public ExpressionSyntax Expression => GetRed(ref this.expression, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.expression, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.expression : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitThrowExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitThrowExpression(this); public ThrowExpressionSyntax Update(SyntaxToken throwKeyword, ExpressionSyntax expression) { if (throwKeyword != this.ThrowKeyword || expression != this.Expression) { var newNode = SyntaxFactory.ThrowExpression(throwKeyword, expression); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ThrowExpressionSyntax WithThrowKeyword(SyntaxToken throwKeyword) => Update(throwKeyword, this.Expression); public ThrowExpressionSyntax WithExpression(ExpressionSyntax expression) => Update(this.ThrowKeyword, expression); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.WhenClause"/></description></item> /// </list> /// </remarks> public sealed partial class WhenClauseSyntax : CSharpSyntaxNode { private ExpressionSyntax? condition; internal WhenClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken WhenKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.WhenClauseSyntax)this.Green).whenKeyword, Position, 0); public ExpressionSyntax Condition => GetRed(ref this.condition, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.condition, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.condition : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitWhenClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitWhenClause(this); public WhenClauseSyntax Update(SyntaxToken whenKeyword, ExpressionSyntax condition) { if (whenKeyword != this.WhenKeyword || condition != this.Condition) { var newNode = SyntaxFactory.WhenClause(whenKeyword, condition); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public WhenClauseSyntax WithWhenKeyword(SyntaxToken whenKeyword) => Update(whenKeyword, this.Condition); public WhenClauseSyntax WithCondition(ExpressionSyntax condition) => Update(this.WhenKeyword, condition); } public abstract partial class PatternSyntax : ExpressionOrPatternSyntax { internal PatternSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.DiscardPattern"/></description></item> /// </list> /// </remarks> public sealed partial class DiscardPatternSyntax : PatternSyntax { internal DiscardPatternSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken UnderscoreToken => new SyntaxToken(this, ((Syntax.InternalSyntax.DiscardPatternSyntax)this.Green).underscoreToken, Position, 0); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitDiscardPattern(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitDiscardPattern(this); public DiscardPatternSyntax Update(SyntaxToken underscoreToken) { if (underscoreToken != this.UnderscoreToken) { var newNode = SyntaxFactory.DiscardPattern(underscoreToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public DiscardPatternSyntax WithUnderscoreToken(SyntaxToken underscoreToken) => Update(underscoreToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.DeclarationPattern"/></description></item> /// </list> /// </remarks> public sealed partial class DeclarationPatternSyntax : PatternSyntax { private TypeSyntax? type; private VariableDesignationSyntax? designation; internal DeclarationPatternSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public TypeSyntax Type => GetRedAtZero(ref this.type)!; public VariableDesignationSyntax Designation => GetRed(ref this.designation, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.type)!, 1 => GetRed(ref this.designation, 1)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.type, 1 => this.designation, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitDeclarationPattern(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitDeclarationPattern(this); public DeclarationPatternSyntax Update(TypeSyntax type, VariableDesignationSyntax designation) { if (type != this.Type || designation != this.Designation) { var newNode = SyntaxFactory.DeclarationPattern(type, designation); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public DeclarationPatternSyntax WithType(TypeSyntax type) => Update(type, this.Designation); public DeclarationPatternSyntax WithDesignation(VariableDesignationSyntax designation) => Update(this.Type, designation); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.VarPattern"/></description></item> /// </list> /// </remarks> public sealed partial class VarPatternSyntax : PatternSyntax { private VariableDesignationSyntax? designation; internal VarPatternSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken VarKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.VarPatternSyntax)this.Green).varKeyword, Position, 0); public VariableDesignationSyntax Designation => GetRed(ref this.designation, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.designation, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.designation : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitVarPattern(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitVarPattern(this); public VarPatternSyntax Update(SyntaxToken varKeyword, VariableDesignationSyntax designation) { if (varKeyword != this.VarKeyword || designation != this.Designation) { var newNode = SyntaxFactory.VarPattern(varKeyword, designation); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public VarPatternSyntax WithVarKeyword(SyntaxToken varKeyword) => Update(varKeyword, this.Designation); public VarPatternSyntax WithDesignation(VariableDesignationSyntax designation) => Update(this.VarKeyword, designation); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.RecursivePattern"/></description></item> /// </list> /// </remarks> public sealed partial class RecursivePatternSyntax : PatternSyntax { private TypeSyntax? type; private PositionalPatternClauseSyntax? positionalPatternClause; private PropertyPatternClauseSyntax? propertyPatternClause; private VariableDesignationSyntax? designation; internal RecursivePatternSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public TypeSyntax? Type => GetRedAtZero(ref this.type); public PositionalPatternClauseSyntax? PositionalPatternClause => GetRed(ref this.positionalPatternClause, 1); public PropertyPatternClauseSyntax? PropertyPatternClause => GetRed(ref this.propertyPatternClause, 2); public VariableDesignationSyntax? Designation => GetRed(ref this.designation, 3); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.type), 1 => GetRed(ref this.positionalPatternClause, 1), 2 => GetRed(ref this.propertyPatternClause, 2), 3 => GetRed(ref this.designation, 3), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.type, 1 => this.positionalPatternClause, 2 => this.propertyPatternClause, 3 => this.designation, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitRecursivePattern(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitRecursivePattern(this); public RecursivePatternSyntax Update(TypeSyntax? type, PositionalPatternClauseSyntax? positionalPatternClause, PropertyPatternClauseSyntax? propertyPatternClause, VariableDesignationSyntax? designation) { if (type != this.Type || positionalPatternClause != this.PositionalPatternClause || propertyPatternClause != this.PropertyPatternClause || designation != this.Designation) { var newNode = SyntaxFactory.RecursivePattern(type, positionalPatternClause, propertyPatternClause, designation); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public RecursivePatternSyntax WithType(TypeSyntax? type) => Update(type, this.PositionalPatternClause, this.PropertyPatternClause, this.Designation); public RecursivePatternSyntax WithPositionalPatternClause(PositionalPatternClauseSyntax? positionalPatternClause) => Update(this.Type, positionalPatternClause, this.PropertyPatternClause, this.Designation); public RecursivePatternSyntax WithPropertyPatternClause(PropertyPatternClauseSyntax? propertyPatternClause) => Update(this.Type, this.PositionalPatternClause, propertyPatternClause, this.Designation); public RecursivePatternSyntax WithDesignation(VariableDesignationSyntax? designation) => Update(this.Type, this.PositionalPatternClause, this.PropertyPatternClause, designation); public RecursivePatternSyntax AddPositionalPatternClauseSubpatterns(params SubpatternSyntax[] items) { var positionalPatternClause = this.PositionalPatternClause ?? SyntaxFactory.PositionalPatternClause(); return WithPositionalPatternClause(positionalPatternClause.WithSubpatterns(positionalPatternClause.Subpatterns.AddRange(items))); } public RecursivePatternSyntax AddPropertyPatternClauseSubpatterns(params SubpatternSyntax[] items) { var propertyPatternClause = this.PropertyPatternClause ?? SyntaxFactory.PropertyPatternClause(); return WithPropertyPatternClause(propertyPatternClause.WithSubpatterns(propertyPatternClause.Subpatterns.AddRange(items))); } } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.PositionalPatternClause"/></description></item> /// </list> /// </remarks> public sealed partial class PositionalPatternClauseSyntax : CSharpSyntaxNode { private SyntaxNode? subpatterns; internal PositionalPatternClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.PositionalPatternClauseSyntax)this.Green).openParenToken, Position, 0); public SeparatedSyntaxList<SubpatternSyntax> Subpatterns { get { var red = GetRed(ref this.subpatterns, 1); return red != null ? new SeparatedSyntaxList<SubpatternSyntax>(red, GetChildIndex(1)) : default; } } public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.PositionalPatternClauseSyntax)this.Green).closeParenToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.subpatterns, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.subpatterns : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitPositionalPatternClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitPositionalPatternClause(this); public PositionalPatternClauseSyntax Update(SyntaxToken openParenToken, SeparatedSyntaxList<SubpatternSyntax> subpatterns, SyntaxToken closeParenToken) { if (openParenToken != this.OpenParenToken || subpatterns != this.Subpatterns || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.PositionalPatternClause(openParenToken, subpatterns, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public PositionalPatternClauseSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(openParenToken, this.Subpatterns, this.CloseParenToken); public PositionalPatternClauseSyntax WithSubpatterns(SeparatedSyntaxList<SubpatternSyntax> subpatterns) => Update(this.OpenParenToken, subpatterns, this.CloseParenToken); public PositionalPatternClauseSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.OpenParenToken, this.Subpatterns, closeParenToken); public PositionalPatternClauseSyntax AddSubpatterns(params SubpatternSyntax[] items) => WithSubpatterns(this.Subpatterns.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.PropertyPatternClause"/></description></item> /// </list> /// </remarks> public sealed partial class PropertyPatternClauseSyntax : CSharpSyntaxNode { private SyntaxNode? subpatterns; internal PropertyPatternClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken OpenBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.PropertyPatternClauseSyntax)this.Green).openBraceToken, Position, 0); public SeparatedSyntaxList<SubpatternSyntax> Subpatterns { get { var red = GetRed(ref this.subpatterns, 1); return red != null ? new SeparatedSyntaxList<SubpatternSyntax>(red, GetChildIndex(1)) : default; } } public SyntaxToken CloseBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.PropertyPatternClauseSyntax)this.Green).closeBraceToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.subpatterns, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.subpatterns : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitPropertyPatternClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitPropertyPatternClause(this); public PropertyPatternClauseSyntax Update(SyntaxToken openBraceToken, SeparatedSyntaxList<SubpatternSyntax> subpatterns, SyntaxToken closeBraceToken) { if (openBraceToken != this.OpenBraceToken || subpatterns != this.Subpatterns || closeBraceToken != this.CloseBraceToken) { var newNode = SyntaxFactory.PropertyPatternClause(openBraceToken, subpatterns, closeBraceToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public PropertyPatternClauseSyntax WithOpenBraceToken(SyntaxToken openBraceToken) => Update(openBraceToken, this.Subpatterns, this.CloseBraceToken); public PropertyPatternClauseSyntax WithSubpatterns(SeparatedSyntaxList<SubpatternSyntax> subpatterns) => Update(this.OpenBraceToken, subpatterns, this.CloseBraceToken); public PropertyPatternClauseSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) => Update(this.OpenBraceToken, this.Subpatterns, closeBraceToken); public PropertyPatternClauseSyntax AddSubpatterns(params SubpatternSyntax[] items) => WithSubpatterns(this.Subpatterns.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.Subpattern"/></description></item> /// </list> /// </remarks> public sealed partial class SubpatternSyntax : CSharpSyntaxNode { private BaseExpressionColonSyntax? expressionColon; private PatternSyntax? pattern; internal SubpatternSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public BaseExpressionColonSyntax? ExpressionColon => GetRedAtZero(ref this.expressionColon); public PatternSyntax Pattern => GetRed(ref this.pattern, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.expressionColon), 1 => GetRed(ref this.pattern, 1)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.expressionColon, 1 => this.pattern, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitSubpattern(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitSubpattern(this); public SubpatternSyntax Update(BaseExpressionColonSyntax? expressionColon, PatternSyntax pattern) { if (expressionColon != this.ExpressionColon || pattern != this.Pattern) { var newNode = SyntaxFactory.Subpattern(expressionColon, pattern); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public SubpatternSyntax WithExpressionColon(BaseExpressionColonSyntax? expressionColon) => Update(expressionColon, this.Pattern); public SubpatternSyntax WithPattern(PatternSyntax pattern) => Update(this.ExpressionColon, pattern); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ConstantPattern"/></description></item> /// </list> /// </remarks> public sealed partial class ConstantPatternSyntax : PatternSyntax { private ExpressionSyntax? expression; internal ConstantPatternSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>ExpressionSyntax node representing the constant expression.</summary> public ExpressionSyntax Expression => GetRedAtZero(ref this.expression)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.expression)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.expression : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitConstantPattern(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitConstantPattern(this); public ConstantPatternSyntax Update(ExpressionSyntax expression) { if (expression != this.Expression) { var newNode = SyntaxFactory.ConstantPattern(expression); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ConstantPatternSyntax WithExpression(ExpressionSyntax expression) => Update(expression); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ParenthesizedPattern"/></description></item> /// </list> /// </remarks> public sealed partial class ParenthesizedPatternSyntax : PatternSyntax { private PatternSyntax? pattern; internal ParenthesizedPatternSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ParenthesizedPatternSyntax)this.Green).openParenToken, Position, 0); public PatternSyntax Pattern => GetRed(ref this.pattern, 1)!; public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ParenthesizedPatternSyntax)this.Green).closeParenToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.pattern, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.pattern : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitParenthesizedPattern(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitParenthesizedPattern(this); public ParenthesizedPatternSyntax Update(SyntaxToken openParenToken, PatternSyntax pattern, SyntaxToken closeParenToken) { if (openParenToken != this.OpenParenToken || pattern != this.Pattern || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.ParenthesizedPattern(openParenToken, pattern, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ParenthesizedPatternSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(openParenToken, this.Pattern, this.CloseParenToken); public ParenthesizedPatternSyntax WithPattern(PatternSyntax pattern) => Update(this.OpenParenToken, pattern, this.CloseParenToken); public ParenthesizedPatternSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.OpenParenToken, this.Pattern, closeParenToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.RelationalPattern"/></description></item> /// </list> /// </remarks> public sealed partial class RelationalPatternSyntax : PatternSyntax { private ExpressionSyntax? expression; internal RelationalPatternSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the operator of the relational pattern.</summary> public SyntaxToken OperatorToken => new SyntaxToken(this, ((Syntax.InternalSyntax.RelationalPatternSyntax)this.Green).operatorToken, Position, 0); public ExpressionSyntax Expression => GetRed(ref this.expression, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.expression, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.expression : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitRelationalPattern(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitRelationalPattern(this); public RelationalPatternSyntax Update(SyntaxToken operatorToken, ExpressionSyntax expression) { if (operatorToken != this.OperatorToken || expression != this.Expression) { var newNode = SyntaxFactory.RelationalPattern(operatorToken, expression); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public RelationalPatternSyntax WithOperatorToken(SyntaxToken operatorToken) => Update(operatorToken, this.Expression); public RelationalPatternSyntax WithExpression(ExpressionSyntax expression) => Update(this.OperatorToken, expression); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.TypePattern"/></description></item> /// </list> /// </remarks> public sealed partial class TypePatternSyntax : PatternSyntax { private TypeSyntax? type; internal TypePatternSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>The type for the type pattern.</summary> public TypeSyntax Type => GetRedAtZero(ref this.type)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.type)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.type : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitTypePattern(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitTypePattern(this); public TypePatternSyntax Update(TypeSyntax type) { if (type != this.Type) { var newNode = SyntaxFactory.TypePattern(type); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public TypePatternSyntax WithType(TypeSyntax type) => Update(type); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.OrPattern"/></description></item> /// <item><description><see cref="SyntaxKind.AndPattern"/></description></item> /// </list> /// </remarks> public sealed partial class BinaryPatternSyntax : PatternSyntax { private PatternSyntax? left; private PatternSyntax? right; internal BinaryPatternSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public PatternSyntax Left => GetRedAtZero(ref this.left)!; public SyntaxToken OperatorToken => new SyntaxToken(this, ((Syntax.InternalSyntax.BinaryPatternSyntax)this.Green).operatorToken, GetChildPosition(1), GetChildIndex(1)); public PatternSyntax Right => GetRed(ref this.right, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.left)!, 2 => GetRed(ref this.right, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.left, 2 => this.right, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitBinaryPattern(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitBinaryPattern(this); public BinaryPatternSyntax Update(PatternSyntax left, SyntaxToken operatorToken, PatternSyntax right) { if (left != this.Left || operatorToken != this.OperatorToken || right != this.Right) { var newNode = SyntaxFactory.BinaryPattern(this.Kind(), left, operatorToken, right); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public BinaryPatternSyntax WithLeft(PatternSyntax left) => Update(left, this.OperatorToken, this.Right); public BinaryPatternSyntax WithOperatorToken(SyntaxToken operatorToken) => Update(this.Left, operatorToken, this.Right); public BinaryPatternSyntax WithRight(PatternSyntax right) => Update(this.Left, this.OperatorToken, right); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.NotPattern"/></description></item> /// </list> /// </remarks> public sealed partial class UnaryPatternSyntax : PatternSyntax { private PatternSyntax? pattern; internal UnaryPatternSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken OperatorToken => new SyntaxToken(this, ((Syntax.InternalSyntax.UnaryPatternSyntax)this.Green).operatorToken, Position, 0); public PatternSyntax Pattern => GetRed(ref this.pattern, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.pattern, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.pattern : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitUnaryPattern(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitUnaryPattern(this); public UnaryPatternSyntax Update(SyntaxToken operatorToken, PatternSyntax pattern) { if (operatorToken != this.OperatorToken || pattern != this.Pattern) { var newNode = SyntaxFactory.UnaryPattern(operatorToken, pattern); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public UnaryPatternSyntax WithOperatorToken(SyntaxToken operatorToken) => Update(operatorToken, this.Pattern); public UnaryPatternSyntax WithPattern(PatternSyntax pattern) => Update(this.OperatorToken, pattern); } public abstract partial class InterpolatedStringContentSyntax : CSharpSyntaxNode { internal InterpolatedStringContentSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.InterpolatedStringText"/></description></item> /// </list> /// </remarks> public sealed partial class InterpolatedStringTextSyntax : InterpolatedStringContentSyntax { internal InterpolatedStringTextSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>The text contents of a part of the interpolated string.</summary> public SyntaxToken TextToken => new SyntaxToken(this, ((Syntax.InternalSyntax.InterpolatedStringTextSyntax)this.Green).textToken, Position, 0); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitInterpolatedStringText(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitInterpolatedStringText(this); public InterpolatedStringTextSyntax Update(SyntaxToken textToken) { if (textToken != this.TextToken) { var newNode = SyntaxFactory.InterpolatedStringText(textToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public InterpolatedStringTextSyntax WithTextToken(SyntaxToken textToken) => Update(textToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.Interpolation"/></description></item> /// </list> /// </remarks> public sealed partial class InterpolationSyntax : InterpolatedStringContentSyntax { private ExpressionSyntax? expression; private InterpolationAlignmentClauseSyntax? alignmentClause; private InterpolationFormatClauseSyntax? formatClause; internal InterpolationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken OpenBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.InterpolationSyntax)this.Green).openBraceToken, Position, 0); public ExpressionSyntax Expression => GetRed(ref this.expression, 1)!; public InterpolationAlignmentClauseSyntax? AlignmentClause => GetRed(ref this.alignmentClause, 2); public InterpolationFormatClauseSyntax? FormatClause => GetRed(ref this.formatClause, 3); public SyntaxToken CloseBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.InterpolationSyntax)this.Green).closeBraceToken, GetChildPosition(4), GetChildIndex(4)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 1 => GetRed(ref this.expression, 1)!, 2 => GetRed(ref this.alignmentClause, 2), 3 => GetRed(ref this.formatClause, 3), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 1 => this.expression, 2 => this.alignmentClause, 3 => this.formatClause, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitInterpolation(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitInterpolation(this); public InterpolationSyntax Update(SyntaxToken openBraceToken, ExpressionSyntax expression, InterpolationAlignmentClauseSyntax? alignmentClause, InterpolationFormatClauseSyntax? formatClause, SyntaxToken closeBraceToken) { if (openBraceToken != this.OpenBraceToken || expression != this.Expression || alignmentClause != this.AlignmentClause || formatClause != this.FormatClause || closeBraceToken != this.CloseBraceToken) { var newNode = SyntaxFactory.Interpolation(openBraceToken, expression, alignmentClause, formatClause, closeBraceToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public InterpolationSyntax WithOpenBraceToken(SyntaxToken openBraceToken) => Update(openBraceToken, this.Expression, this.AlignmentClause, this.FormatClause, this.CloseBraceToken); public InterpolationSyntax WithExpression(ExpressionSyntax expression) => Update(this.OpenBraceToken, expression, this.AlignmentClause, this.FormatClause, this.CloseBraceToken); public InterpolationSyntax WithAlignmentClause(InterpolationAlignmentClauseSyntax? alignmentClause) => Update(this.OpenBraceToken, this.Expression, alignmentClause, this.FormatClause, this.CloseBraceToken); public InterpolationSyntax WithFormatClause(InterpolationFormatClauseSyntax? formatClause) => Update(this.OpenBraceToken, this.Expression, this.AlignmentClause, formatClause, this.CloseBraceToken); public InterpolationSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) => Update(this.OpenBraceToken, this.Expression, this.AlignmentClause, this.FormatClause, closeBraceToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.InterpolationAlignmentClause"/></description></item> /// </list> /// </remarks> public sealed partial class InterpolationAlignmentClauseSyntax : CSharpSyntaxNode { private ExpressionSyntax? value; internal InterpolationAlignmentClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken CommaToken => new SyntaxToken(this, ((Syntax.InternalSyntax.InterpolationAlignmentClauseSyntax)this.Green).commaToken, Position, 0); public ExpressionSyntax Value => GetRed(ref this.value, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.value, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.value : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitInterpolationAlignmentClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitInterpolationAlignmentClause(this); public InterpolationAlignmentClauseSyntax Update(SyntaxToken commaToken, ExpressionSyntax value) { if (commaToken != this.CommaToken || value != this.Value) { var newNode = SyntaxFactory.InterpolationAlignmentClause(commaToken, value); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public InterpolationAlignmentClauseSyntax WithCommaToken(SyntaxToken commaToken) => Update(commaToken, this.Value); public InterpolationAlignmentClauseSyntax WithValue(ExpressionSyntax value) => Update(this.CommaToken, value); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.InterpolationFormatClause"/></description></item> /// </list> /// </remarks> public sealed partial class InterpolationFormatClauseSyntax : CSharpSyntaxNode { internal InterpolationFormatClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken ColonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.InterpolationFormatClauseSyntax)this.Green).colonToken, Position, 0); /// <summary>The text contents of the format specifier for an interpolation.</summary> public SyntaxToken FormatStringToken => new SyntaxToken(this, ((Syntax.InternalSyntax.InterpolationFormatClauseSyntax)this.Green).formatStringToken, GetChildPosition(1), GetChildIndex(1)); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitInterpolationFormatClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitInterpolationFormatClause(this); public InterpolationFormatClauseSyntax Update(SyntaxToken colonToken, SyntaxToken formatStringToken) { if (colonToken != this.ColonToken || formatStringToken != this.FormatStringToken) { var newNode = SyntaxFactory.InterpolationFormatClause(colonToken, formatStringToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public InterpolationFormatClauseSyntax WithColonToken(SyntaxToken colonToken) => Update(colonToken, this.FormatStringToken); public InterpolationFormatClauseSyntax WithFormatStringToken(SyntaxToken formatStringToken) => Update(this.ColonToken, formatStringToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.GlobalStatement"/></description></item> /// </list> /// </remarks> public sealed partial class GlobalStatementSyntax : MemberDeclarationSyntax { private SyntaxNode? attributeLists; private StatementSyntax? statement; internal GlobalStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public StatementSyntax Statement => GetRed(ref this.statement, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.statement, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.statement, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitGlobalStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitGlobalStatement(this); public GlobalStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, StatementSyntax statement) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || statement != this.Statement) { var newNode = SyntaxFactory.GlobalStatement(attributeLists, modifiers, statement); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new GlobalStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.Statement); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new GlobalStatementSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.Statement); public GlobalStatementSyntax WithStatement(StatementSyntax statement) => Update(this.AttributeLists, this.Modifiers, statement); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new GlobalStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new GlobalStatementSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); } /// <summary>Represents the base class for all statements syntax classes.</summary> public abstract partial class StatementSyntax : CSharpSyntaxNode { internal StatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public abstract SyntaxList<AttributeListSyntax> AttributeLists { get; } public StatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeListsCore(attributeLists); internal abstract StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists); public StatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => AddAttributeListsCore(items); internal abstract StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.Block"/></description></item> /// </list> /// </remarks> public sealed partial class BlockSyntax : StatementSyntax { private SyntaxNode? attributeLists; private SyntaxNode? statements; internal BlockSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxToken OpenBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.BlockSyntax)this.Green).openBraceToken, GetChildPosition(1), GetChildIndex(1)); public SyntaxList<StatementSyntax> Statements => new SyntaxList<StatementSyntax>(GetRed(ref this.statements, 2)); public SyntaxToken CloseBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.BlockSyntax)this.Green).closeBraceToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.statements, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.statements, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitBlock(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitBlock(this); public BlockSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken openBraceToken, SyntaxList<StatementSyntax> statements, SyntaxToken closeBraceToken) { if (attributeLists != this.AttributeLists || openBraceToken != this.OpenBraceToken || statements != this.Statements || closeBraceToken != this.CloseBraceToken) { var newNode = SyntaxFactory.Block(attributeLists, openBraceToken, statements, closeBraceToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new BlockSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.OpenBraceToken, this.Statements, this.CloseBraceToken); public BlockSyntax WithOpenBraceToken(SyntaxToken openBraceToken) => Update(this.AttributeLists, openBraceToken, this.Statements, this.CloseBraceToken); public BlockSyntax WithStatements(SyntaxList<StatementSyntax> statements) => Update(this.AttributeLists, this.OpenBraceToken, statements, this.CloseBraceToken); public BlockSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) => Update(this.AttributeLists, this.OpenBraceToken, this.Statements, closeBraceToken); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new BlockSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); public BlockSyntax AddStatements(params StatementSyntax[] items) => WithStatements(this.Statements.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.LocalFunctionStatement"/></description></item> /// </list> /// </remarks> public sealed partial class LocalFunctionStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private TypeSyntax? returnType; private TypeParameterListSyntax? typeParameterList; private ParameterListSyntax? parameterList; private SyntaxNode? constraintClauses; private BlockSyntax? body; private ArrowExpressionClauseSyntax? expressionBody; internal LocalFunctionStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public TypeSyntax ReturnType => GetRed(ref this.returnType, 2)!; /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.LocalFunctionStatementSyntax)this.Green).identifier, GetChildPosition(3), GetChildIndex(3)); public TypeParameterListSyntax? TypeParameterList => GetRed(ref this.typeParameterList, 4); public ParameterListSyntax ParameterList => GetRed(ref this.parameterList, 5)!; public SyntaxList<TypeParameterConstraintClauseSyntax> ConstraintClauses => new SyntaxList<TypeParameterConstraintClauseSyntax>(GetRed(ref this.constraintClauses, 6)); public BlockSyntax? Body => GetRed(ref this.body, 7); public ArrowExpressionClauseSyntax? ExpressionBody => GetRed(ref this.expressionBody, 8); /// <summary>Gets the optional semicolon token.</summary> public SyntaxToken SemicolonToken { get { var slot = ((Syntax.InternalSyntax.LocalFunctionStatementSyntax)this.Green).semicolonToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(9), GetChildIndex(9)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.returnType, 2)!, 4 => GetRed(ref this.typeParameterList, 4), 5 => GetRed(ref this.parameterList, 5)!, 6 => GetRed(ref this.constraintClauses, 6)!, 7 => GetRed(ref this.body, 7), 8 => GetRed(ref this.expressionBody, 8), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.returnType, 4 => this.typeParameterList, 5 => this.parameterList, 6 => this.constraintClauses, 7 => this.body, 8 => this.expressionBody, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitLocalFunctionStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitLocalFunctionStatement(this); public LocalFunctionStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, TypeSyntax returnType, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax parameterList, SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || returnType != this.ReturnType || identifier != this.Identifier || typeParameterList != this.TypeParameterList || parameterList != this.ParameterList || constraintClauses != this.ConstraintClauses || body != this.Body || expressionBody != this.ExpressionBody || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.LocalFunctionStatement(attributeLists, modifiers, returnType, identifier, typeParameterList, parameterList, constraintClauses, body, expressionBody, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new LocalFunctionStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.ReturnType, this.Identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, this.Body, this.ExpressionBody, this.SemicolonToken); public LocalFunctionStatementSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.ReturnType, this.Identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, this.Body, this.ExpressionBody, this.SemicolonToken); public LocalFunctionStatementSyntax WithReturnType(TypeSyntax returnType) => Update(this.AttributeLists, this.Modifiers, returnType, this.Identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, this.Body, this.ExpressionBody, this.SemicolonToken); public LocalFunctionStatementSyntax WithIdentifier(SyntaxToken identifier) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, this.Body, this.ExpressionBody, this.SemicolonToken); public LocalFunctionStatementSyntax WithTypeParameterList(TypeParameterListSyntax? typeParameterList) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.Identifier, typeParameterList, this.ParameterList, this.ConstraintClauses, this.Body, this.ExpressionBody, this.SemicolonToken); public LocalFunctionStatementSyntax WithParameterList(ParameterListSyntax parameterList) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.Identifier, this.TypeParameterList, parameterList, this.ConstraintClauses, this.Body, this.ExpressionBody, this.SemicolonToken); public LocalFunctionStatementSyntax WithConstraintClauses(SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.Identifier, this.TypeParameterList, this.ParameterList, constraintClauses, this.Body, this.ExpressionBody, this.SemicolonToken); public LocalFunctionStatementSyntax WithBody(BlockSyntax? body) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.Identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, body, this.ExpressionBody, this.SemicolonToken); public LocalFunctionStatementSyntax WithExpressionBody(ArrowExpressionClauseSyntax? expressionBody) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.Identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, this.Body, expressionBody, this.SemicolonToken); public LocalFunctionStatementSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.Identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, this.Body, this.ExpressionBody, semicolonToken); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new LocalFunctionStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); public LocalFunctionStatementSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); public LocalFunctionStatementSyntax AddTypeParameterListParameters(params TypeParameterSyntax[] items) { var typeParameterList = this.TypeParameterList ?? SyntaxFactory.TypeParameterList(); return WithTypeParameterList(typeParameterList.WithParameters(typeParameterList.Parameters.AddRange(items))); } public LocalFunctionStatementSyntax AddParameterListParameters(params ParameterSyntax[] items) => WithParameterList(this.ParameterList.WithParameters(this.ParameterList.Parameters.AddRange(items))); public LocalFunctionStatementSyntax AddConstraintClauses(params TypeParameterConstraintClauseSyntax[] items) => WithConstraintClauses(this.ConstraintClauses.AddRange(items)); public LocalFunctionStatementSyntax AddBodyAttributeLists(params AttributeListSyntax[] items) { var body = this.Body ?? SyntaxFactory.Block(); return WithBody(body.WithAttributeLists(body.AttributeLists.AddRange(items))); } public LocalFunctionStatementSyntax AddBodyStatements(params StatementSyntax[] items) { var body = this.Body ?? SyntaxFactory.Block(); return WithBody(body.WithStatements(body.Statements.AddRange(items))); } } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.LocalDeclarationStatement"/></description></item> /// </list> /// </remarks> public sealed partial class LocalDeclarationStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private VariableDeclarationSyntax? declaration; internal LocalDeclarationStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxToken AwaitKeyword { get { var slot = ((Syntax.InternalSyntax.LocalDeclarationStatementSyntax)this.Green).awaitKeyword; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public SyntaxToken UsingKeyword { get { var slot = ((Syntax.InternalSyntax.LocalDeclarationStatementSyntax)this.Green).usingKeyword; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(2), GetChildIndex(2)) : default; } } /// <summary>Gets the modifier list.</summary> public SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(3); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(3), GetChildIndex(3)) : default; } } public VariableDeclarationSyntax Declaration => GetRed(ref this.declaration, 4)!; public SyntaxToken SemicolonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.LocalDeclarationStatementSyntax)this.Green).semicolonToken, GetChildPosition(5), GetChildIndex(5)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 4 => GetRed(ref this.declaration, 4)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 4 => this.declaration, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitLocalDeclarationStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitLocalDeclarationStatement(this); public LocalDeclarationStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken awaitKeyword, SyntaxToken usingKeyword, SyntaxTokenList modifiers, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || awaitKeyword != this.AwaitKeyword || usingKeyword != this.UsingKeyword || modifiers != this.Modifiers || declaration != this.Declaration || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.LocalDeclarationStatement(attributeLists, awaitKeyword, usingKeyword, modifiers, declaration, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new LocalDeclarationStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.AwaitKeyword, this.UsingKeyword, this.Modifiers, this.Declaration, this.SemicolonToken); public LocalDeclarationStatementSyntax WithAwaitKeyword(SyntaxToken awaitKeyword) => Update(this.AttributeLists, awaitKeyword, this.UsingKeyword, this.Modifiers, this.Declaration, this.SemicolonToken); public LocalDeclarationStatementSyntax WithUsingKeyword(SyntaxToken usingKeyword) => Update(this.AttributeLists, this.AwaitKeyword, usingKeyword, this.Modifiers, this.Declaration, this.SemicolonToken); public LocalDeclarationStatementSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, this.AwaitKeyword, this.UsingKeyword, modifiers, this.Declaration, this.SemicolonToken); public LocalDeclarationStatementSyntax WithDeclaration(VariableDeclarationSyntax declaration) => Update(this.AttributeLists, this.AwaitKeyword, this.UsingKeyword, this.Modifiers, declaration, this.SemicolonToken); public LocalDeclarationStatementSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.AwaitKeyword, this.UsingKeyword, this.Modifiers, this.Declaration, semicolonToken); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new LocalDeclarationStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); public LocalDeclarationStatementSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); public LocalDeclarationStatementSyntax AddDeclarationVariables(params VariableDeclaratorSyntax[] items) => WithDeclaration(this.Declaration.WithVariables(this.Declaration.Variables.AddRange(items))); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.VariableDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class VariableDeclarationSyntax : CSharpSyntaxNode { private TypeSyntax? type; private SyntaxNode? variables; internal VariableDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public TypeSyntax Type => GetRedAtZero(ref this.type)!; public SeparatedSyntaxList<VariableDeclaratorSyntax> Variables { get { var red = GetRed(ref this.variables, 1); return red != null ? new SeparatedSyntaxList<VariableDeclaratorSyntax>(red, GetChildIndex(1)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.type)!, 1 => GetRed(ref this.variables, 1)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.type, 1 => this.variables, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitVariableDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitVariableDeclaration(this); public VariableDeclarationSyntax Update(TypeSyntax type, SeparatedSyntaxList<VariableDeclaratorSyntax> variables) { if (type != this.Type || variables != this.Variables) { var newNode = SyntaxFactory.VariableDeclaration(type, variables); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public VariableDeclarationSyntax WithType(TypeSyntax type) => Update(type, this.Variables); public VariableDeclarationSyntax WithVariables(SeparatedSyntaxList<VariableDeclaratorSyntax> variables) => Update(this.Type, variables); public VariableDeclarationSyntax AddVariables(params VariableDeclaratorSyntax[] items) => WithVariables(this.Variables.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.VariableDeclarator"/></description></item> /// </list> /// </remarks> public sealed partial class VariableDeclaratorSyntax : CSharpSyntaxNode { private BracketedArgumentListSyntax? argumentList; private EqualsValueClauseSyntax? initializer; internal VariableDeclaratorSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.VariableDeclaratorSyntax)this.Green).identifier, Position, 0); public BracketedArgumentListSyntax? ArgumentList => GetRed(ref this.argumentList, 1); public EqualsValueClauseSyntax? Initializer => GetRed(ref this.initializer, 2); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 1 => GetRed(ref this.argumentList, 1), 2 => GetRed(ref this.initializer, 2), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 1 => this.argumentList, 2 => this.initializer, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitVariableDeclarator(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitVariableDeclarator(this); public VariableDeclaratorSyntax Update(SyntaxToken identifier, BracketedArgumentListSyntax? argumentList, EqualsValueClauseSyntax? initializer) { if (identifier != this.Identifier || argumentList != this.ArgumentList || initializer != this.Initializer) { var newNode = SyntaxFactory.VariableDeclarator(identifier, argumentList, initializer); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public VariableDeclaratorSyntax WithIdentifier(SyntaxToken identifier) => Update(identifier, this.ArgumentList, this.Initializer); public VariableDeclaratorSyntax WithArgumentList(BracketedArgumentListSyntax? argumentList) => Update(this.Identifier, argumentList, this.Initializer); public VariableDeclaratorSyntax WithInitializer(EqualsValueClauseSyntax? initializer) => Update(this.Identifier, this.ArgumentList, initializer); public VariableDeclaratorSyntax AddArgumentListArguments(params ArgumentSyntax[] items) { var argumentList = this.ArgumentList ?? SyntaxFactory.BracketedArgumentList(); return WithArgumentList(argumentList.WithArguments(argumentList.Arguments.AddRange(items))); } } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.EqualsValueClause"/></description></item> /// </list> /// </remarks> public sealed partial class EqualsValueClauseSyntax : CSharpSyntaxNode { private ExpressionSyntax? value; internal EqualsValueClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken EqualsToken => new SyntaxToken(this, ((Syntax.InternalSyntax.EqualsValueClauseSyntax)this.Green).equalsToken, Position, 0); public ExpressionSyntax Value => GetRed(ref this.value, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.value, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.value : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitEqualsValueClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitEqualsValueClause(this); public EqualsValueClauseSyntax Update(SyntaxToken equalsToken, ExpressionSyntax value) { if (equalsToken != this.EqualsToken || value != this.Value) { var newNode = SyntaxFactory.EqualsValueClause(equalsToken, value); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public EqualsValueClauseSyntax WithEqualsToken(SyntaxToken equalsToken) => Update(equalsToken, this.Value); public EqualsValueClauseSyntax WithValue(ExpressionSyntax value) => Update(this.EqualsToken, value); } public abstract partial class VariableDesignationSyntax : CSharpSyntaxNode { internal VariableDesignationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.SingleVariableDesignation"/></description></item> /// </list> /// </remarks> public sealed partial class SingleVariableDesignationSyntax : VariableDesignationSyntax { internal SingleVariableDesignationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.SingleVariableDesignationSyntax)this.Green).identifier, Position, 0); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitSingleVariableDesignation(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitSingleVariableDesignation(this); public SingleVariableDesignationSyntax Update(SyntaxToken identifier) { if (identifier != this.Identifier) { var newNode = SyntaxFactory.SingleVariableDesignation(identifier); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public SingleVariableDesignationSyntax WithIdentifier(SyntaxToken identifier) => Update(identifier); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.DiscardDesignation"/></description></item> /// </list> /// </remarks> public sealed partial class DiscardDesignationSyntax : VariableDesignationSyntax { internal DiscardDesignationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken UnderscoreToken => new SyntaxToken(this, ((Syntax.InternalSyntax.DiscardDesignationSyntax)this.Green).underscoreToken, Position, 0); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitDiscardDesignation(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitDiscardDesignation(this); public DiscardDesignationSyntax Update(SyntaxToken underscoreToken) { if (underscoreToken != this.UnderscoreToken) { var newNode = SyntaxFactory.DiscardDesignation(underscoreToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public DiscardDesignationSyntax WithUnderscoreToken(SyntaxToken underscoreToken) => Update(underscoreToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ParenthesizedVariableDesignation"/></description></item> /// </list> /// </remarks> public sealed partial class ParenthesizedVariableDesignationSyntax : VariableDesignationSyntax { private SyntaxNode? variables; internal ParenthesizedVariableDesignationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ParenthesizedVariableDesignationSyntax)this.Green).openParenToken, Position, 0); public SeparatedSyntaxList<VariableDesignationSyntax> Variables { get { var red = GetRed(ref this.variables, 1); return red != null ? new SeparatedSyntaxList<VariableDesignationSyntax>(red, GetChildIndex(1)) : default; } } public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ParenthesizedVariableDesignationSyntax)this.Green).closeParenToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.variables, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.variables : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitParenthesizedVariableDesignation(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitParenthesizedVariableDesignation(this); public ParenthesizedVariableDesignationSyntax Update(SyntaxToken openParenToken, SeparatedSyntaxList<VariableDesignationSyntax> variables, SyntaxToken closeParenToken) { if (openParenToken != this.OpenParenToken || variables != this.Variables || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.ParenthesizedVariableDesignation(openParenToken, variables, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ParenthesizedVariableDesignationSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(openParenToken, this.Variables, this.CloseParenToken); public ParenthesizedVariableDesignationSyntax WithVariables(SeparatedSyntaxList<VariableDesignationSyntax> variables) => Update(this.OpenParenToken, variables, this.CloseParenToken); public ParenthesizedVariableDesignationSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.OpenParenToken, this.Variables, closeParenToken); public ParenthesizedVariableDesignationSyntax AddVariables(params VariableDesignationSyntax[] items) => WithVariables(this.Variables.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ExpressionStatement"/></description></item> /// </list> /// </remarks> public sealed partial class ExpressionStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private ExpressionSyntax? expression; internal ExpressionStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public ExpressionSyntax Expression => GetRed(ref this.expression, 1)!; public SyntaxToken SemicolonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ExpressionStatementSyntax)this.Green).semicolonToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 1 => GetRed(ref this.expression, 1)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 1 => this.expression, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitExpressionStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitExpressionStatement(this); public ExpressionStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, ExpressionSyntax expression, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || expression != this.Expression || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.ExpressionStatement(attributeLists, expression, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new ExpressionStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Expression, this.SemicolonToken); public ExpressionStatementSyntax WithExpression(ExpressionSyntax expression) => Update(this.AttributeLists, expression, this.SemicolonToken); public ExpressionStatementSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Expression, semicolonToken); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new ExpressionStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.EmptyStatement"/></description></item> /// </list> /// </remarks> public sealed partial class EmptyStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; internal EmptyStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxToken SemicolonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.EmptyStatementSyntax)this.Green).semicolonToken, GetChildPosition(1), GetChildIndex(1)); internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.attributeLists)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.attributeLists : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitEmptyStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitEmptyStatement(this); public EmptyStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.EmptyStatement(attributeLists, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new EmptyStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.SemicolonToken); public EmptyStatementSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, semicolonToken); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new EmptyStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); } /// <summary>Represents a labeled statement syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.LabeledStatement"/></description></item> /// </list> /// </remarks> public sealed partial class LabeledStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private StatementSyntax? statement; internal LabeledStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.LabeledStatementSyntax)this.Green).identifier, GetChildPosition(1), GetChildIndex(1)); /// <summary>Gets a SyntaxToken that represents the colon following the statement's label.</summary> public SyntaxToken ColonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.LabeledStatementSyntax)this.Green).colonToken, GetChildPosition(2), GetChildIndex(2)); public StatementSyntax Statement => GetRed(ref this.statement, 3)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 3 => GetRed(ref this.statement, 3)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 3 => this.statement, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitLabeledStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitLabeledStatement(this); public LabeledStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken identifier, SyntaxToken colonToken, StatementSyntax statement) { if (attributeLists != this.AttributeLists || identifier != this.Identifier || colonToken != this.ColonToken || statement != this.Statement) { var newNode = SyntaxFactory.LabeledStatement(attributeLists, identifier, colonToken, statement); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new LabeledStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Identifier, this.ColonToken, this.Statement); public LabeledStatementSyntax WithIdentifier(SyntaxToken identifier) => Update(this.AttributeLists, identifier, this.ColonToken, this.Statement); public LabeledStatementSyntax WithColonToken(SyntaxToken colonToken) => Update(this.AttributeLists, this.Identifier, colonToken, this.Statement); public LabeledStatementSyntax WithStatement(StatementSyntax statement) => Update(this.AttributeLists, this.Identifier, this.ColonToken, statement); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new LabeledStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); } /// <summary> /// Represents a goto statement syntax /// </summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.GotoStatement"/></description></item> /// <item><description><see cref="SyntaxKind.GotoCaseStatement"/></description></item> /// <item><description><see cref="SyntaxKind.GotoDefaultStatement"/></description></item> /// </list> /// </remarks> public sealed partial class GotoStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private ExpressionSyntax? expression; internal GotoStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); /// <summary> /// Gets a SyntaxToken that represents the goto keyword. /// </summary> public SyntaxToken GotoKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.GotoStatementSyntax)this.Green).gotoKeyword, GetChildPosition(1), GetChildIndex(1)); /// <summary> /// Gets a SyntaxToken that represents the case or default keywords if any exists. /// </summary> public SyntaxToken CaseOrDefaultKeyword { get { var slot = ((Syntax.InternalSyntax.GotoStatementSyntax)this.Green).caseOrDefaultKeyword; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(2), GetChildIndex(2)) : default; } } /// <summary> /// Gets a constant expression for a goto case statement. /// </summary> public ExpressionSyntax? Expression => GetRed(ref this.expression, 3); /// <summary> /// Gets a SyntaxToken that represents the semi-colon at the end of the statement. /// </summary> public SyntaxToken SemicolonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.GotoStatementSyntax)this.Green).semicolonToken, GetChildPosition(4), GetChildIndex(4)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 3 => GetRed(ref this.expression, 3), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 3 => this.expression, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitGotoStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitGotoStatement(this); public GotoStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken gotoKeyword, SyntaxToken caseOrDefaultKeyword, ExpressionSyntax? expression, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || gotoKeyword != this.GotoKeyword || caseOrDefaultKeyword != this.CaseOrDefaultKeyword || expression != this.Expression || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.GotoStatement(this.Kind(), attributeLists, gotoKeyword, caseOrDefaultKeyword, expression, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new GotoStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.GotoKeyword, this.CaseOrDefaultKeyword, this.Expression, this.SemicolonToken); public GotoStatementSyntax WithGotoKeyword(SyntaxToken gotoKeyword) => Update(this.AttributeLists, gotoKeyword, this.CaseOrDefaultKeyword, this.Expression, this.SemicolonToken); public GotoStatementSyntax WithCaseOrDefaultKeyword(SyntaxToken caseOrDefaultKeyword) => Update(this.AttributeLists, this.GotoKeyword, caseOrDefaultKeyword, this.Expression, this.SemicolonToken); public GotoStatementSyntax WithExpression(ExpressionSyntax? expression) => Update(this.AttributeLists, this.GotoKeyword, this.CaseOrDefaultKeyword, expression, this.SemicolonToken); public GotoStatementSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.GotoKeyword, this.CaseOrDefaultKeyword, this.Expression, semicolonToken); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new GotoStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.BreakStatement"/></description></item> /// </list> /// </remarks> public sealed partial class BreakStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; internal BreakStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxToken BreakKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.BreakStatementSyntax)this.Green).breakKeyword, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken SemicolonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.BreakStatementSyntax)this.Green).semicolonToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.attributeLists)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.attributeLists : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitBreakStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitBreakStatement(this); public BreakStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken breakKeyword, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || breakKeyword != this.BreakKeyword || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.BreakStatement(attributeLists, breakKeyword, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new BreakStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.BreakKeyword, this.SemicolonToken); public BreakStatementSyntax WithBreakKeyword(SyntaxToken breakKeyword) => Update(this.AttributeLists, breakKeyword, this.SemicolonToken); public BreakStatementSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.BreakKeyword, semicolonToken); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new BreakStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ContinueStatement"/></description></item> /// </list> /// </remarks> public sealed partial class ContinueStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; internal ContinueStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxToken ContinueKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ContinueStatementSyntax)this.Green).continueKeyword, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken SemicolonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ContinueStatementSyntax)this.Green).semicolonToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.attributeLists)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.attributeLists : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitContinueStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitContinueStatement(this); public ContinueStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken continueKeyword, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || continueKeyword != this.ContinueKeyword || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.ContinueStatement(attributeLists, continueKeyword, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new ContinueStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.ContinueKeyword, this.SemicolonToken); public ContinueStatementSyntax WithContinueKeyword(SyntaxToken continueKeyword) => Update(this.AttributeLists, continueKeyword, this.SemicolonToken); public ContinueStatementSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.ContinueKeyword, semicolonToken); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new ContinueStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ReturnStatement"/></description></item> /// </list> /// </remarks> public sealed partial class ReturnStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private ExpressionSyntax? expression; internal ReturnStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxToken ReturnKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ReturnStatementSyntax)this.Green).returnKeyword, GetChildPosition(1), GetChildIndex(1)); public ExpressionSyntax? Expression => GetRed(ref this.expression, 2); public SyntaxToken SemicolonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ReturnStatementSyntax)this.Green).semicolonToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.expression, 2), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.expression, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitReturnStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitReturnStatement(this); public ReturnStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken returnKeyword, ExpressionSyntax? expression, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || returnKeyword != this.ReturnKeyword || expression != this.Expression || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.ReturnStatement(attributeLists, returnKeyword, expression, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new ReturnStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.ReturnKeyword, this.Expression, this.SemicolonToken); public ReturnStatementSyntax WithReturnKeyword(SyntaxToken returnKeyword) => Update(this.AttributeLists, returnKeyword, this.Expression, this.SemicolonToken); public ReturnStatementSyntax WithExpression(ExpressionSyntax? expression) => Update(this.AttributeLists, this.ReturnKeyword, expression, this.SemicolonToken); public ReturnStatementSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.ReturnKeyword, this.Expression, semicolonToken); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new ReturnStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ThrowStatement"/></description></item> /// </list> /// </remarks> public sealed partial class ThrowStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private ExpressionSyntax? expression; internal ThrowStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxToken ThrowKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ThrowStatementSyntax)this.Green).throwKeyword, GetChildPosition(1), GetChildIndex(1)); public ExpressionSyntax? Expression => GetRed(ref this.expression, 2); public SyntaxToken SemicolonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ThrowStatementSyntax)this.Green).semicolonToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.expression, 2), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.expression, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitThrowStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitThrowStatement(this); public ThrowStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken throwKeyword, ExpressionSyntax? expression, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || throwKeyword != this.ThrowKeyword || expression != this.Expression || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.ThrowStatement(attributeLists, throwKeyword, expression, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new ThrowStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.ThrowKeyword, this.Expression, this.SemicolonToken); public ThrowStatementSyntax WithThrowKeyword(SyntaxToken throwKeyword) => Update(this.AttributeLists, throwKeyword, this.Expression, this.SemicolonToken); public ThrowStatementSyntax WithExpression(ExpressionSyntax? expression) => Update(this.AttributeLists, this.ThrowKeyword, expression, this.SemicolonToken); public ThrowStatementSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.ThrowKeyword, this.Expression, semicolonToken); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new ThrowStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.YieldReturnStatement"/></description></item> /// <item><description><see cref="SyntaxKind.YieldBreakStatement"/></description></item> /// </list> /// </remarks> public sealed partial class YieldStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private ExpressionSyntax? expression; internal YieldStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxToken YieldKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.YieldStatementSyntax)this.Green).yieldKeyword, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken ReturnOrBreakKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.YieldStatementSyntax)this.Green).returnOrBreakKeyword, GetChildPosition(2), GetChildIndex(2)); public ExpressionSyntax? Expression => GetRed(ref this.expression, 3); public SyntaxToken SemicolonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.YieldStatementSyntax)this.Green).semicolonToken, GetChildPosition(4), GetChildIndex(4)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 3 => GetRed(ref this.expression, 3), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 3 => this.expression, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitYieldStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitYieldStatement(this); public YieldStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken yieldKeyword, SyntaxToken returnOrBreakKeyword, ExpressionSyntax? expression, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || yieldKeyword != this.YieldKeyword || returnOrBreakKeyword != this.ReturnOrBreakKeyword || expression != this.Expression || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.YieldStatement(this.Kind(), attributeLists, yieldKeyword, returnOrBreakKeyword, expression, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new YieldStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.YieldKeyword, this.ReturnOrBreakKeyword, this.Expression, this.SemicolonToken); public YieldStatementSyntax WithYieldKeyword(SyntaxToken yieldKeyword) => Update(this.AttributeLists, yieldKeyword, this.ReturnOrBreakKeyword, this.Expression, this.SemicolonToken); public YieldStatementSyntax WithReturnOrBreakKeyword(SyntaxToken returnOrBreakKeyword) => Update(this.AttributeLists, this.YieldKeyword, returnOrBreakKeyword, this.Expression, this.SemicolonToken); public YieldStatementSyntax WithExpression(ExpressionSyntax? expression) => Update(this.AttributeLists, this.YieldKeyword, this.ReturnOrBreakKeyword, expression, this.SemicolonToken); public YieldStatementSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.YieldKeyword, this.ReturnOrBreakKeyword, this.Expression, semicolonToken); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new YieldStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.WhileStatement"/></description></item> /// </list> /// </remarks> public sealed partial class WhileStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private ExpressionSyntax? condition; private StatementSyntax? statement; internal WhileStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxToken WhileKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.WhileStatementSyntax)this.Green).whileKeyword, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.WhileStatementSyntax)this.Green).openParenToken, GetChildPosition(2), GetChildIndex(2)); public ExpressionSyntax Condition => GetRed(ref this.condition, 3)!; public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.WhileStatementSyntax)this.Green).closeParenToken, GetChildPosition(4), GetChildIndex(4)); public StatementSyntax Statement => GetRed(ref this.statement, 5)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 3 => GetRed(ref this.condition, 3)!, 5 => GetRed(ref this.statement, 5)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 3 => this.condition, 5 => this.statement, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitWhileStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitWhileStatement(this); public WhileStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, StatementSyntax statement) { if (attributeLists != this.AttributeLists || whileKeyword != this.WhileKeyword || openParenToken != this.OpenParenToken || condition != this.Condition || closeParenToken != this.CloseParenToken || statement != this.Statement) { var newNode = SyntaxFactory.WhileStatement(attributeLists, whileKeyword, openParenToken, condition, closeParenToken, statement); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new WhileStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.WhileKeyword, this.OpenParenToken, this.Condition, this.CloseParenToken, this.Statement); public WhileStatementSyntax WithWhileKeyword(SyntaxToken whileKeyword) => Update(this.AttributeLists, whileKeyword, this.OpenParenToken, this.Condition, this.CloseParenToken, this.Statement); public WhileStatementSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.AttributeLists, this.WhileKeyword, openParenToken, this.Condition, this.CloseParenToken, this.Statement); public WhileStatementSyntax WithCondition(ExpressionSyntax condition) => Update(this.AttributeLists, this.WhileKeyword, this.OpenParenToken, condition, this.CloseParenToken, this.Statement); public WhileStatementSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.AttributeLists, this.WhileKeyword, this.OpenParenToken, this.Condition, closeParenToken, this.Statement); public WhileStatementSyntax WithStatement(StatementSyntax statement) => Update(this.AttributeLists, this.WhileKeyword, this.OpenParenToken, this.Condition, this.CloseParenToken, statement); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new WhileStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.DoStatement"/></description></item> /// </list> /// </remarks> public sealed partial class DoStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private StatementSyntax? statement; private ExpressionSyntax? condition; internal DoStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxToken DoKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.DoStatementSyntax)this.Green).doKeyword, GetChildPosition(1), GetChildIndex(1)); public StatementSyntax Statement => GetRed(ref this.statement, 2)!; public SyntaxToken WhileKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.DoStatementSyntax)this.Green).whileKeyword, GetChildPosition(3), GetChildIndex(3)); public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.DoStatementSyntax)this.Green).openParenToken, GetChildPosition(4), GetChildIndex(4)); public ExpressionSyntax Condition => GetRed(ref this.condition, 5)!; public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.DoStatementSyntax)this.Green).closeParenToken, GetChildPosition(6), GetChildIndex(6)); public SyntaxToken SemicolonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.DoStatementSyntax)this.Green).semicolonToken, GetChildPosition(7), GetChildIndex(7)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.statement, 2)!, 5 => GetRed(ref this.condition, 5)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.statement, 5 => this.condition, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitDoStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitDoStatement(this); public DoStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken doKeyword, StatementSyntax statement, SyntaxToken whileKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || doKeyword != this.DoKeyword || statement != this.Statement || whileKeyword != this.WhileKeyword || openParenToken != this.OpenParenToken || condition != this.Condition || closeParenToken != this.CloseParenToken || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.DoStatement(attributeLists, doKeyword, statement, whileKeyword, openParenToken, condition, closeParenToken, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new DoStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.DoKeyword, this.Statement, this.WhileKeyword, this.OpenParenToken, this.Condition, this.CloseParenToken, this.SemicolonToken); public DoStatementSyntax WithDoKeyword(SyntaxToken doKeyword) => Update(this.AttributeLists, doKeyword, this.Statement, this.WhileKeyword, this.OpenParenToken, this.Condition, this.CloseParenToken, this.SemicolonToken); public DoStatementSyntax WithStatement(StatementSyntax statement) => Update(this.AttributeLists, this.DoKeyword, statement, this.WhileKeyword, this.OpenParenToken, this.Condition, this.CloseParenToken, this.SemicolonToken); public DoStatementSyntax WithWhileKeyword(SyntaxToken whileKeyword) => Update(this.AttributeLists, this.DoKeyword, this.Statement, whileKeyword, this.OpenParenToken, this.Condition, this.CloseParenToken, this.SemicolonToken); public DoStatementSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.AttributeLists, this.DoKeyword, this.Statement, this.WhileKeyword, openParenToken, this.Condition, this.CloseParenToken, this.SemicolonToken); public DoStatementSyntax WithCondition(ExpressionSyntax condition) => Update(this.AttributeLists, this.DoKeyword, this.Statement, this.WhileKeyword, this.OpenParenToken, condition, this.CloseParenToken, this.SemicolonToken); public DoStatementSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.AttributeLists, this.DoKeyword, this.Statement, this.WhileKeyword, this.OpenParenToken, this.Condition, closeParenToken, this.SemicolonToken); public DoStatementSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.DoKeyword, this.Statement, this.WhileKeyword, this.OpenParenToken, this.Condition, this.CloseParenToken, semicolonToken); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new DoStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ForStatement"/></description></item> /// </list> /// </remarks> public sealed partial class ForStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private VariableDeclarationSyntax? declaration; private SyntaxNode? initializers; private ExpressionSyntax? condition; private SyntaxNode? incrementors; private StatementSyntax? statement; internal ForStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxToken ForKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ForStatementSyntax)this.Green).forKeyword, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ForStatementSyntax)this.Green).openParenToken, GetChildPosition(2), GetChildIndex(2)); public VariableDeclarationSyntax? Declaration => GetRed(ref this.declaration, 3); public SeparatedSyntaxList<ExpressionSyntax> Initializers { get { var red = GetRed(ref this.initializers, 4); return red != null ? new SeparatedSyntaxList<ExpressionSyntax>(red, GetChildIndex(4)) : default; } } public SyntaxToken FirstSemicolonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ForStatementSyntax)this.Green).firstSemicolonToken, GetChildPosition(5), GetChildIndex(5)); public ExpressionSyntax? Condition => GetRed(ref this.condition, 6); public SyntaxToken SecondSemicolonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ForStatementSyntax)this.Green).secondSemicolonToken, GetChildPosition(7), GetChildIndex(7)); public SeparatedSyntaxList<ExpressionSyntax> Incrementors { get { var red = GetRed(ref this.incrementors, 8); return red != null ? new SeparatedSyntaxList<ExpressionSyntax>(red, GetChildIndex(8)) : default; } } public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ForStatementSyntax)this.Green).closeParenToken, GetChildPosition(9), GetChildIndex(9)); public StatementSyntax Statement => GetRed(ref this.statement, 10)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 3 => GetRed(ref this.declaration, 3), 4 => GetRed(ref this.initializers, 4)!, 6 => GetRed(ref this.condition, 6), 8 => GetRed(ref this.incrementors, 8)!, 10 => GetRed(ref this.statement, 10)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 3 => this.declaration, 4 => this.initializers, 6 => this.condition, 8 => this.incrementors, 10 => this.statement, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitForStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitForStatement(this); public ForStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken forKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, SeparatedSyntaxList<ExpressionSyntax> initializers, SyntaxToken firstSemicolonToken, ExpressionSyntax? condition, SyntaxToken secondSemicolonToken, SeparatedSyntaxList<ExpressionSyntax> incrementors, SyntaxToken closeParenToken, StatementSyntax statement) { if (attributeLists != this.AttributeLists || forKeyword != this.ForKeyword || openParenToken != this.OpenParenToken || declaration != this.Declaration || initializers != this.Initializers || firstSemicolonToken != this.FirstSemicolonToken || condition != this.Condition || secondSemicolonToken != this.SecondSemicolonToken || incrementors != this.Incrementors || closeParenToken != this.CloseParenToken || statement != this.Statement) { var newNode = SyntaxFactory.ForStatement(attributeLists, forKeyword, openParenToken, declaration, initializers, firstSemicolonToken, condition, secondSemicolonToken, incrementors, closeParenToken, statement); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new ForStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.ForKeyword, this.OpenParenToken, this.Declaration, this.Initializers, this.FirstSemicolonToken, this.Condition, this.SecondSemicolonToken, this.Incrementors, this.CloseParenToken, this.Statement); public ForStatementSyntax WithForKeyword(SyntaxToken forKeyword) => Update(this.AttributeLists, forKeyword, this.OpenParenToken, this.Declaration, this.Initializers, this.FirstSemicolonToken, this.Condition, this.SecondSemicolonToken, this.Incrementors, this.CloseParenToken, this.Statement); public ForStatementSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.AttributeLists, this.ForKeyword, openParenToken, this.Declaration, this.Initializers, this.FirstSemicolonToken, this.Condition, this.SecondSemicolonToken, this.Incrementors, this.CloseParenToken, this.Statement); public ForStatementSyntax WithDeclaration(VariableDeclarationSyntax? declaration) => Update(this.AttributeLists, this.ForKeyword, this.OpenParenToken, declaration, this.Initializers, this.FirstSemicolonToken, this.Condition, this.SecondSemicolonToken, this.Incrementors, this.CloseParenToken, this.Statement); public ForStatementSyntax WithInitializers(SeparatedSyntaxList<ExpressionSyntax> initializers) => Update(this.AttributeLists, this.ForKeyword, this.OpenParenToken, this.Declaration, initializers, this.FirstSemicolonToken, this.Condition, this.SecondSemicolonToken, this.Incrementors, this.CloseParenToken, this.Statement); public ForStatementSyntax WithFirstSemicolonToken(SyntaxToken firstSemicolonToken) => Update(this.AttributeLists, this.ForKeyword, this.OpenParenToken, this.Declaration, this.Initializers, firstSemicolonToken, this.Condition, this.SecondSemicolonToken, this.Incrementors, this.CloseParenToken, this.Statement); public ForStatementSyntax WithCondition(ExpressionSyntax? condition) => Update(this.AttributeLists, this.ForKeyword, this.OpenParenToken, this.Declaration, this.Initializers, this.FirstSemicolonToken, condition, this.SecondSemicolonToken, this.Incrementors, this.CloseParenToken, this.Statement); public ForStatementSyntax WithSecondSemicolonToken(SyntaxToken secondSemicolonToken) => Update(this.AttributeLists, this.ForKeyword, this.OpenParenToken, this.Declaration, this.Initializers, this.FirstSemicolonToken, this.Condition, secondSemicolonToken, this.Incrementors, this.CloseParenToken, this.Statement); public ForStatementSyntax WithIncrementors(SeparatedSyntaxList<ExpressionSyntax> incrementors) => Update(this.AttributeLists, this.ForKeyword, this.OpenParenToken, this.Declaration, this.Initializers, this.FirstSemicolonToken, this.Condition, this.SecondSemicolonToken, incrementors, this.CloseParenToken, this.Statement); public ForStatementSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.AttributeLists, this.ForKeyword, this.OpenParenToken, this.Declaration, this.Initializers, this.FirstSemicolonToken, this.Condition, this.SecondSemicolonToken, this.Incrementors, closeParenToken, this.Statement); public ForStatementSyntax WithStatement(StatementSyntax statement) => Update(this.AttributeLists, this.ForKeyword, this.OpenParenToken, this.Declaration, this.Initializers, this.FirstSemicolonToken, this.Condition, this.SecondSemicolonToken, this.Incrementors, this.CloseParenToken, statement); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new ForStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); public ForStatementSyntax AddInitializers(params ExpressionSyntax[] items) => WithInitializers(this.Initializers.AddRange(items)); public ForStatementSyntax AddIncrementors(params ExpressionSyntax[] items) => WithIncrementors(this.Incrementors.AddRange(items)); } public abstract partial class CommonForEachStatementSyntax : StatementSyntax { internal CommonForEachStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public abstract SyntaxToken AwaitKeyword { get; } public CommonForEachStatementSyntax WithAwaitKeyword(SyntaxToken awaitKeyword) => WithAwaitKeywordCore(awaitKeyword); internal abstract CommonForEachStatementSyntax WithAwaitKeywordCore(SyntaxToken awaitKeyword); public abstract SyntaxToken ForEachKeyword { get; } public CommonForEachStatementSyntax WithForEachKeyword(SyntaxToken forEachKeyword) => WithForEachKeywordCore(forEachKeyword); internal abstract CommonForEachStatementSyntax WithForEachKeywordCore(SyntaxToken forEachKeyword); public abstract SyntaxToken OpenParenToken { get; } public CommonForEachStatementSyntax WithOpenParenToken(SyntaxToken openParenToken) => WithOpenParenTokenCore(openParenToken); internal abstract CommonForEachStatementSyntax WithOpenParenTokenCore(SyntaxToken openParenToken); public abstract SyntaxToken InKeyword { get; } public CommonForEachStatementSyntax WithInKeyword(SyntaxToken inKeyword) => WithInKeywordCore(inKeyword); internal abstract CommonForEachStatementSyntax WithInKeywordCore(SyntaxToken inKeyword); public abstract ExpressionSyntax Expression { get; } public CommonForEachStatementSyntax WithExpression(ExpressionSyntax expression) => WithExpressionCore(expression); internal abstract CommonForEachStatementSyntax WithExpressionCore(ExpressionSyntax expression); public abstract SyntaxToken CloseParenToken { get; } public CommonForEachStatementSyntax WithCloseParenToken(SyntaxToken closeParenToken) => WithCloseParenTokenCore(closeParenToken); internal abstract CommonForEachStatementSyntax WithCloseParenTokenCore(SyntaxToken closeParenToken); public abstract StatementSyntax Statement { get; } public CommonForEachStatementSyntax WithStatement(StatementSyntax statement) => WithStatementCore(statement); internal abstract CommonForEachStatementSyntax WithStatementCore(StatementSyntax statement); public new CommonForEachStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => (CommonForEachStatementSyntax)WithAttributeListsCore(attributeLists); public new CommonForEachStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => (CommonForEachStatementSyntax)AddAttributeListsCore(items); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ForEachStatement"/></description></item> /// </list> /// </remarks> public sealed partial class ForEachStatementSyntax : CommonForEachStatementSyntax { private SyntaxNode? attributeLists; private TypeSyntax? type; private ExpressionSyntax? expression; private StatementSyntax? statement; internal ForEachStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxToken AwaitKeyword { get { var slot = ((Syntax.InternalSyntax.ForEachStatementSyntax)this.Green).awaitKeyword; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public override SyntaxToken ForEachKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ForEachStatementSyntax)this.Green).forEachKeyword, GetChildPosition(2), GetChildIndex(2)); public override SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ForEachStatementSyntax)this.Green).openParenToken, GetChildPosition(3), GetChildIndex(3)); public TypeSyntax Type => GetRed(ref this.type, 4)!; /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.ForEachStatementSyntax)this.Green).identifier, GetChildPosition(5), GetChildIndex(5)); public override SyntaxToken InKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ForEachStatementSyntax)this.Green).inKeyword, GetChildPosition(6), GetChildIndex(6)); public override ExpressionSyntax Expression => GetRed(ref this.expression, 7)!; public override SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ForEachStatementSyntax)this.Green).closeParenToken, GetChildPosition(8), GetChildIndex(8)); public override StatementSyntax Statement => GetRed(ref this.statement, 9)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 4 => GetRed(ref this.type, 4)!, 7 => GetRed(ref this.expression, 7)!, 9 => GetRed(ref this.statement, 9)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 4 => this.type, 7 => this.expression, 9 => this.statement, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitForEachStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitForEachStatement(this); public ForEachStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken awaitKeyword, SyntaxToken forEachKeyword, SyntaxToken openParenToken, TypeSyntax type, SyntaxToken identifier, SyntaxToken inKeyword, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement) { if (attributeLists != this.AttributeLists || awaitKeyword != this.AwaitKeyword || forEachKeyword != this.ForEachKeyword || openParenToken != this.OpenParenToken || type != this.Type || identifier != this.Identifier || inKeyword != this.InKeyword || expression != this.Expression || closeParenToken != this.CloseParenToken || statement != this.Statement) { var newNode = SyntaxFactory.ForEachStatement(attributeLists, awaitKeyword, forEachKeyword, openParenToken, type, identifier, inKeyword, expression, closeParenToken, statement); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new ForEachStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.AwaitKeyword, this.ForEachKeyword, this.OpenParenToken, this.Type, this.Identifier, this.InKeyword, this.Expression, this.CloseParenToken, this.Statement); internal override CommonForEachStatementSyntax WithAwaitKeywordCore(SyntaxToken awaitKeyword) => WithAwaitKeyword(awaitKeyword); public new ForEachStatementSyntax WithAwaitKeyword(SyntaxToken awaitKeyword) => Update(this.AttributeLists, awaitKeyword, this.ForEachKeyword, this.OpenParenToken, this.Type, this.Identifier, this.InKeyword, this.Expression, this.CloseParenToken, this.Statement); internal override CommonForEachStatementSyntax WithForEachKeywordCore(SyntaxToken forEachKeyword) => WithForEachKeyword(forEachKeyword); public new ForEachStatementSyntax WithForEachKeyword(SyntaxToken forEachKeyword) => Update(this.AttributeLists, this.AwaitKeyword, forEachKeyword, this.OpenParenToken, this.Type, this.Identifier, this.InKeyword, this.Expression, this.CloseParenToken, this.Statement); internal override CommonForEachStatementSyntax WithOpenParenTokenCore(SyntaxToken openParenToken) => WithOpenParenToken(openParenToken); public new ForEachStatementSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.AttributeLists, this.AwaitKeyword, this.ForEachKeyword, openParenToken, this.Type, this.Identifier, this.InKeyword, this.Expression, this.CloseParenToken, this.Statement); public ForEachStatementSyntax WithType(TypeSyntax type) => Update(this.AttributeLists, this.AwaitKeyword, this.ForEachKeyword, this.OpenParenToken, type, this.Identifier, this.InKeyword, this.Expression, this.CloseParenToken, this.Statement); public ForEachStatementSyntax WithIdentifier(SyntaxToken identifier) => Update(this.AttributeLists, this.AwaitKeyword, this.ForEachKeyword, this.OpenParenToken, this.Type, identifier, this.InKeyword, this.Expression, this.CloseParenToken, this.Statement); internal override CommonForEachStatementSyntax WithInKeywordCore(SyntaxToken inKeyword) => WithInKeyword(inKeyword); public new ForEachStatementSyntax WithInKeyword(SyntaxToken inKeyword) => Update(this.AttributeLists, this.AwaitKeyword, this.ForEachKeyword, this.OpenParenToken, this.Type, this.Identifier, inKeyword, this.Expression, this.CloseParenToken, this.Statement); internal override CommonForEachStatementSyntax WithExpressionCore(ExpressionSyntax expression) => WithExpression(expression); public new ForEachStatementSyntax WithExpression(ExpressionSyntax expression) => Update(this.AttributeLists, this.AwaitKeyword, this.ForEachKeyword, this.OpenParenToken, this.Type, this.Identifier, this.InKeyword, expression, this.CloseParenToken, this.Statement); internal override CommonForEachStatementSyntax WithCloseParenTokenCore(SyntaxToken closeParenToken) => WithCloseParenToken(closeParenToken); public new ForEachStatementSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.AttributeLists, this.AwaitKeyword, this.ForEachKeyword, this.OpenParenToken, this.Type, this.Identifier, this.InKeyword, this.Expression, closeParenToken, this.Statement); internal override CommonForEachStatementSyntax WithStatementCore(StatementSyntax statement) => WithStatement(statement); public new ForEachStatementSyntax WithStatement(StatementSyntax statement) => Update(this.AttributeLists, this.AwaitKeyword, this.ForEachKeyword, this.OpenParenToken, this.Type, this.Identifier, this.InKeyword, this.Expression, this.CloseParenToken, statement); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new ForEachStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ForEachVariableStatement"/></description></item> /// </list> /// </remarks> public sealed partial class ForEachVariableStatementSyntax : CommonForEachStatementSyntax { private SyntaxNode? attributeLists; private ExpressionSyntax? variable; private ExpressionSyntax? expression; private StatementSyntax? statement; internal ForEachVariableStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxToken AwaitKeyword { get { var slot = ((Syntax.InternalSyntax.ForEachVariableStatementSyntax)this.Green).awaitKeyword; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public override SyntaxToken ForEachKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ForEachVariableStatementSyntax)this.Green).forEachKeyword, GetChildPosition(2), GetChildIndex(2)); public override SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ForEachVariableStatementSyntax)this.Green).openParenToken, GetChildPosition(3), GetChildIndex(3)); /// <summary> /// The variable(s) of the loop. In correct code this is a tuple /// literal, declaration expression with a tuple designator, or /// a discard syntax in the form of a simple identifier. In broken /// code it could be something else. /// </summary> public ExpressionSyntax Variable => GetRed(ref this.variable, 4)!; public override SyntaxToken InKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ForEachVariableStatementSyntax)this.Green).inKeyword, GetChildPosition(5), GetChildIndex(5)); public override ExpressionSyntax Expression => GetRed(ref this.expression, 6)!; public override SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ForEachVariableStatementSyntax)this.Green).closeParenToken, GetChildPosition(7), GetChildIndex(7)); public override StatementSyntax Statement => GetRed(ref this.statement, 8)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 4 => GetRed(ref this.variable, 4)!, 6 => GetRed(ref this.expression, 6)!, 8 => GetRed(ref this.statement, 8)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 4 => this.variable, 6 => this.expression, 8 => this.statement, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitForEachVariableStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitForEachVariableStatement(this); public ForEachVariableStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken awaitKeyword, SyntaxToken forEachKeyword, SyntaxToken openParenToken, ExpressionSyntax variable, SyntaxToken inKeyword, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement) { if (attributeLists != this.AttributeLists || awaitKeyword != this.AwaitKeyword || forEachKeyword != this.ForEachKeyword || openParenToken != this.OpenParenToken || variable != this.Variable || inKeyword != this.InKeyword || expression != this.Expression || closeParenToken != this.CloseParenToken || statement != this.Statement) { var newNode = SyntaxFactory.ForEachVariableStatement(attributeLists, awaitKeyword, forEachKeyword, openParenToken, variable, inKeyword, expression, closeParenToken, statement); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new ForEachVariableStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.AwaitKeyword, this.ForEachKeyword, this.OpenParenToken, this.Variable, this.InKeyword, this.Expression, this.CloseParenToken, this.Statement); internal override CommonForEachStatementSyntax WithAwaitKeywordCore(SyntaxToken awaitKeyword) => WithAwaitKeyword(awaitKeyword); public new ForEachVariableStatementSyntax WithAwaitKeyword(SyntaxToken awaitKeyword) => Update(this.AttributeLists, awaitKeyword, this.ForEachKeyword, this.OpenParenToken, this.Variable, this.InKeyword, this.Expression, this.CloseParenToken, this.Statement); internal override CommonForEachStatementSyntax WithForEachKeywordCore(SyntaxToken forEachKeyword) => WithForEachKeyword(forEachKeyword); public new ForEachVariableStatementSyntax WithForEachKeyword(SyntaxToken forEachKeyword) => Update(this.AttributeLists, this.AwaitKeyword, forEachKeyword, this.OpenParenToken, this.Variable, this.InKeyword, this.Expression, this.CloseParenToken, this.Statement); internal override CommonForEachStatementSyntax WithOpenParenTokenCore(SyntaxToken openParenToken) => WithOpenParenToken(openParenToken); public new ForEachVariableStatementSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.AttributeLists, this.AwaitKeyword, this.ForEachKeyword, openParenToken, this.Variable, this.InKeyword, this.Expression, this.CloseParenToken, this.Statement); public ForEachVariableStatementSyntax WithVariable(ExpressionSyntax variable) => Update(this.AttributeLists, this.AwaitKeyword, this.ForEachKeyword, this.OpenParenToken, variable, this.InKeyword, this.Expression, this.CloseParenToken, this.Statement); internal override CommonForEachStatementSyntax WithInKeywordCore(SyntaxToken inKeyword) => WithInKeyword(inKeyword); public new ForEachVariableStatementSyntax WithInKeyword(SyntaxToken inKeyword) => Update(this.AttributeLists, this.AwaitKeyword, this.ForEachKeyword, this.OpenParenToken, this.Variable, inKeyword, this.Expression, this.CloseParenToken, this.Statement); internal override CommonForEachStatementSyntax WithExpressionCore(ExpressionSyntax expression) => WithExpression(expression); public new ForEachVariableStatementSyntax WithExpression(ExpressionSyntax expression) => Update(this.AttributeLists, this.AwaitKeyword, this.ForEachKeyword, this.OpenParenToken, this.Variable, this.InKeyword, expression, this.CloseParenToken, this.Statement); internal override CommonForEachStatementSyntax WithCloseParenTokenCore(SyntaxToken closeParenToken) => WithCloseParenToken(closeParenToken); public new ForEachVariableStatementSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.AttributeLists, this.AwaitKeyword, this.ForEachKeyword, this.OpenParenToken, this.Variable, this.InKeyword, this.Expression, closeParenToken, this.Statement); internal override CommonForEachStatementSyntax WithStatementCore(StatementSyntax statement) => WithStatement(statement); public new ForEachVariableStatementSyntax WithStatement(StatementSyntax statement) => Update(this.AttributeLists, this.AwaitKeyword, this.ForEachKeyword, this.OpenParenToken, this.Variable, this.InKeyword, this.Expression, this.CloseParenToken, statement); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new ForEachVariableStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.UsingStatement"/></description></item> /// </list> /// </remarks> public sealed partial class UsingStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private VariableDeclarationSyntax? declaration; private ExpressionSyntax? expression; private StatementSyntax? statement; internal UsingStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxToken AwaitKeyword { get { var slot = ((Syntax.InternalSyntax.UsingStatementSyntax)this.Green).awaitKeyword; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public SyntaxToken UsingKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.UsingStatementSyntax)this.Green).usingKeyword, GetChildPosition(2), GetChildIndex(2)); public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.UsingStatementSyntax)this.Green).openParenToken, GetChildPosition(3), GetChildIndex(3)); public VariableDeclarationSyntax? Declaration => GetRed(ref this.declaration, 4); public ExpressionSyntax? Expression => GetRed(ref this.expression, 5); public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.UsingStatementSyntax)this.Green).closeParenToken, GetChildPosition(6), GetChildIndex(6)); public StatementSyntax Statement => GetRed(ref this.statement, 7)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 4 => GetRed(ref this.declaration, 4), 5 => GetRed(ref this.expression, 5), 7 => GetRed(ref this.statement, 7)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 4 => this.declaration, 5 => this.expression, 7 => this.statement, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitUsingStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitUsingStatement(this); public UsingStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken awaitKeyword, SyntaxToken usingKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, ExpressionSyntax? expression, SyntaxToken closeParenToken, StatementSyntax statement) { if (attributeLists != this.AttributeLists || awaitKeyword != this.AwaitKeyword || usingKeyword != this.UsingKeyword || openParenToken != this.OpenParenToken || declaration != this.Declaration || expression != this.Expression || closeParenToken != this.CloseParenToken || statement != this.Statement) { var newNode = SyntaxFactory.UsingStatement(attributeLists, awaitKeyword, usingKeyword, openParenToken, declaration, expression, closeParenToken, statement); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new UsingStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.AwaitKeyword, this.UsingKeyword, this.OpenParenToken, this.Declaration, this.Expression, this.CloseParenToken, this.Statement); public UsingStatementSyntax WithAwaitKeyword(SyntaxToken awaitKeyword) => Update(this.AttributeLists, awaitKeyword, this.UsingKeyword, this.OpenParenToken, this.Declaration, this.Expression, this.CloseParenToken, this.Statement); public UsingStatementSyntax WithUsingKeyword(SyntaxToken usingKeyword) => Update(this.AttributeLists, this.AwaitKeyword, usingKeyword, this.OpenParenToken, this.Declaration, this.Expression, this.CloseParenToken, this.Statement); public UsingStatementSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.AttributeLists, this.AwaitKeyword, this.UsingKeyword, openParenToken, this.Declaration, this.Expression, this.CloseParenToken, this.Statement); public UsingStatementSyntax WithDeclaration(VariableDeclarationSyntax? declaration) => Update(this.AttributeLists, this.AwaitKeyword, this.UsingKeyword, this.OpenParenToken, declaration, this.Expression, this.CloseParenToken, this.Statement); public UsingStatementSyntax WithExpression(ExpressionSyntax? expression) => Update(this.AttributeLists, this.AwaitKeyword, this.UsingKeyword, this.OpenParenToken, this.Declaration, expression, this.CloseParenToken, this.Statement); public UsingStatementSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.AttributeLists, this.AwaitKeyword, this.UsingKeyword, this.OpenParenToken, this.Declaration, this.Expression, closeParenToken, this.Statement); public UsingStatementSyntax WithStatement(StatementSyntax statement) => Update(this.AttributeLists, this.AwaitKeyword, this.UsingKeyword, this.OpenParenToken, this.Declaration, this.Expression, this.CloseParenToken, statement); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new UsingStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.FixedStatement"/></description></item> /// </list> /// </remarks> public sealed partial class FixedStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private VariableDeclarationSyntax? declaration; private StatementSyntax? statement; internal FixedStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxToken FixedKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.FixedStatementSyntax)this.Green).fixedKeyword, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.FixedStatementSyntax)this.Green).openParenToken, GetChildPosition(2), GetChildIndex(2)); public VariableDeclarationSyntax Declaration => GetRed(ref this.declaration, 3)!; public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.FixedStatementSyntax)this.Green).closeParenToken, GetChildPosition(4), GetChildIndex(4)); public StatementSyntax Statement => GetRed(ref this.statement, 5)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 3 => GetRed(ref this.declaration, 3)!, 5 => GetRed(ref this.statement, 5)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 3 => this.declaration, 5 => this.statement, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitFixedStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitFixedStatement(this); public FixedStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken fixedKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax declaration, SyntaxToken closeParenToken, StatementSyntax statement) { if (attributeLists != this.AttributeLists || fixedKeyword != this.FixedKeyword || openParenToken != this.OpenParenToken || declaration != this.Declaration || closeParenToken != this.CloseParenToken || statement != this.Statement) { var newNode = SyntaxFactory.FixedStatement(attributeLists, fixedKeyword, openParenToken, declaration, closeParenToken, statement); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new FixedStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.FixedKeyword, this.OpenParenToken, this.Declaration, this.CloseParenToken, this.Statement); public FixedStatementSyntax WithFixedKeyword(SyntaxToken fixedKeyword) => Update(this.AttributeLists, fixedKeyword, this.OpenParenToken, this.Declaration, this.CloseParenToken, this.Statement); public FixedStatementSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.AttributeLists, this.FixedKeyword, openParenToken, this.Declaration, this.CloseParenToken, this.Statement); public FixedStatementSyntax WithDeclaration(VariableDeclarationSyntax declaration) => Update(this.AttributeLists, this.FixedKeyword, this.OpenParenToken, declaration, this.CloseParenToken, this.Statement); public FixedStatementSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.AttributeLists, this.FixedKeyword, this.OpenParenToken, this.Declaration, closeParenToken, this.Statement); public FixedStatementSyntax WithStatement(StatementSyntax statement) => Update(this.AttributeLists, this.FixedKeyword, this.OpenParenToken, this.Declaration, this.CloseParenToken, statement); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new FixedStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); public FixedStatementSyntax AddDeclarationVariables(params VariableDeclaratorSyntax[] items) => WithDeclaration(this.Declaration.WithVariables(this.Declaration.Variables.AddRange(items))); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.CheckedStatement"/></description></item> /// <item><description><see cref="SyntaxKind.UncheckedStatement"/></description></item> /// </list> /// </remarks> public sealed partial class CheckedStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private BlockSyntax? block; internal CheckedStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxToken Keyword => new SyntaxToken(this, ((Syntax.InternalSyntax.CheckedStatementSyntax)this.Green).keyword, GetChildPosition(1), GetChildIndex(1)); public BlockSyntax Block => GetRed(ref this.block, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.block, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.block, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitCheckedStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitCheckedStatement(this); public CheckedStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken keyword, BlockSyntax block) { if (attributeLists != this.AttributeLists || keyword != this.Keyword || block != this.Block) { var newNode = SyntaxFactory.CheckedStatement(this.Kind(), attributeLists, keyword, block); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new CheckedStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Keyword, this.Block); public CheckedStatementSyntax WithKeyword(SyntaxToken keyword) => Update(this.AttributeLists, keyword, this.Block); public CheckedStatementSyntax WithBlock(BlockSyntax block) => Update(this.AttributeLists, this.Keyword, block); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new CheckedStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); public CheckedStatementSyntax AddBlockAttributeLists(params AttributeListSyntax[] items) => WithBlock(this.Block.WithAttributeLists(this.Block.AttributeLists.AddRange(items))); public CheckedStatementSyntax AddBlockStatements(params StatementSyntax[] items) => WithBlock(this.Block.WithStatements(this.Block.Statements.AddRange(items))); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.UnsafeStatement"/></description></item> /// </list> /// </remarks> public sealed partial class UnsafeStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private BlockSyntax? block; internal UnsafeStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxToken UnsafeKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.UnsafeStatementSyntax)this.Green).unsafeKeyword, GetChildPosition(1), GetChildIndex(1)); public BlockSyntax Block => GetRed(ref this.block, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.block, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.block, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitUnsafeStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitUnsafeStatement(this); public UnsafeStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken unsafeKeyword, BlockSyntax block) { if (attributeLists != this.AttributeLists || unsafeKeyword != this.UnsafeKeyword || block != this.Block) { var newNode = SyntaxFactory.UnsafeStatement(attributeLists, unsafeKeyword, block); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new UnsafeStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.UnsafeKeyword, this.Block); public UnsafeStatementSyntax WithUnsafeKeyword(SyntaxToken unsafeKeyword) => Update(this.AttributeLists, unsafeKeyword, this.Block); public UnsafeStatementSyntax WithBlock(BlockSyntax block) => Update(this.AttributeLists, this.UnsafeKeyword, block); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new UnsafeStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); public UnsafeStatementSyntax AddBlockAttributeLists(params AttributeListSyntax[] items) => WithBlock(this.Block.WithAttributeLists(this.Block.AttributeLists.AddRange(items))); public UnsafeStatementSyntax AddBlockStatements(params StatementSyntax[] items) => WithBlock(this.Block.WithStatements(this.Block.Statements.AddRange(items))); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.LockStatement"/></description></item> /// </list> /// </remarks> public sealed partial class LockStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private ExpressionSyntax? expression; private StatementSyntax? statement; internal LockStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxToken LockKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.LockStatementSyntax)this.Green).lockKeyword, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.LockStatementSyntax)this.Green).openParenToken, GetChildPosition(2), GetChildIndex(2)); public ExpressionSyntax Expression => GetRed(ref this.expression, 3)!; public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.LockStatementSyntax)this.Green).closeParenToken, GetChildPosition(4), GetChildIndex(4)); public StatementSyntax Statement => GetRed(ref this.statement, 5)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 3 => GetRed(ref this.expression, 3)!, 5 => GetRed(ref this.statement, 5)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 3 => this.expression, 5 => this.statement, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitLockStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitLockStatement(this); public LockStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken lockKeyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement) { if (attributeLists != this.AttributeLists || lockKeyword != this.LockKeyword || openParenToken != this.OpenParenToken || expression != this.Expression || closeParenToken != this.CloseParenToken || statement != this.Statement) { var newNode = SyntaxFactory.LockStatement(attributeLists, lockKeyword, openParenToken, expression, closeParenToken, statement); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new LockStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.LockKeyword, this.OpenParenToken, this.Expression, this.CloseParenToken, this.Statement); public LockStatementSyntax WithLockKeyword(SyntaxToken lockKeyword) => Update(this.AttributeLists, lockKeyword, this.OpenParenToken, this.Expression, this.CloseParenToken, this.Statement); public LockStatementSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.AttributeLists, this.LockKeyword, openParenToken, this.Expression, this.CloseParenToken, this.Statement); public LockStatementSyntax WithExpression(ExpressionSyntax expression) => Update(this.AttributeLists, this.LockKeyword, this.OpenParenToken, expression, this.CloseParenToken, this.Statement); public LockStatementSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.AttributeLists, this.LockKeyword, this.OpenParenToken, this.Expression, closeParenToken, this.Statement); public LockStatementSyntax WithStatement(StatementSyntax statement) => Update(this.AttributeLists, this.LockKeyword, this.OpenParenToken, this.Expression, this.CloseParenToken, statement); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new LockStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); } /// <summary> /// Represents an if statement syntax. /// </summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.IfStatement"/></description></item> /// </list> /// </remarks> public sealed partial class IfStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private ExpressionSyntax? condition; private StatementSyntax? statement; private ElseClauseSyntax? @else; internal IfStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); /// <summary> /// Gets a SyntaxToken that represents the if keyword. /// </summary> public SyntaxToken IfKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.IfStatementSyntax)this.Green).ifKeyword, GetChildPosition(1), GetChildIndex(1)); /// <summary> /// Gets a SyntaxToken that represents the open parenthesis before the if statement's condition expression. /// </summary> public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.IfStatementSyntax)this.Green).openParenToken, GetChildPosition(2), GetChildIndex(2)); /// <summary> /// Gets an ExpressionSyntax that represents the condition of the if statement. /// </summary> public ExpressionSyntax Condition => GetRed(ref this.condition, 3)!; /// <summary> /// Gets a SyntaxToken that represents the close parenthesis after the if statement's condition expression. /// </summary> public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.IfStatementSyntax)this.Green).closeParenToken, GetChildPosition(4), GetChildIndex(4)); /// <summary> /// Gets a StatementSyntax the represents the statement to be executed when the condition is true. /// </summary> public StatementSyntax Statement => GetRed(ref this.statement, 5)!; /// <summary> /// Gets an ElseClauseSyntax that represents the statement to be executed when the condition is false if such statement exists. /// </summary> public ElseClauseSyntax? Else => GetRed(ref this.@else, 6); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 3 => GetRed(ref this.condition, 3)!, 5 => GetRed(ref this.statement, 5)!, 6 => GetRed(ref this.@else, 6), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 3 => this.condition, 5 => this.statement, 6 => this.@else, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitIfStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitIfStatement(this); public IfStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken ifKeyword, SyntaxToken openParenToken, ExpressionSyntax condition, SyntaxToken closeParenToken, StatementSyntax statement, ElseClauseSyntax? @else) { if (attributeLists != this.AttributeLists || ifKeyword != this.IfKeyword || openParenToken != this.OpenParenToken || condition != this.Condition || closeParenToken != this.CloseParenToken || statement != this.Statement || @else != this.Else) { var newNode = SyntaxFactory.IfStatement(attributeLists, ifKeyword, openParenToken, condition, closeParenToken, statement, @else); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new IfStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.IfKeyword, this.OpenParenToken, this.Condition, this.CloseParenToken, this.Statement, this.Else); public IfStatementSyntax WithIfKeyword(SyntaxToken ifKeyword) => Update(this.AttributeLists, ifKeyword, this.OpenParenToken, this.Condition, this.CloseParenToken, this.Statement, this.Else); public IfStatementSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.AttributeLists, this.IfKeyword, openParenToken, this.Condition, this.CloseParenToken, this.Statement, this.Else); public IfStatementSyntax WithCondition(ExpressionSyntax condition) => Update(this.AttributeLists, this.IfKeyword, this.OpenParenToken, condition, this.CloseParenToken, this.Statement, this.Else); public IfStatementSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.AttributeLists, this.IfKeyword, this.OpenParenToken, this.Condition, closeParenToken, this.Statement, this.Else); public IfStatementSyntax WithStatement(StatementSyntax statement) => Update(this.AttributeLists, this.IfKeyword, this.OpenParenToken, this.Condition, this.CloseParenToken, statement, this.Else); public IfStatementSyntax WithElse(ElseClauseSyntax? @else) => Update(this.AttributeLists, this.IfKeyword, this.OpenParenToken, this.Condition, this.CloseParenToken, this.Statement, @else); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new IfStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); } /// <summary>Represents an else statement syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ElseClause"/></description></item> /// </list> /// </remarks> public sealed partial class ElseClauseSyntax : CSharpSyntaxNode { private StatementSyntax? statement; internal ElseClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary> /// Gets a syntax token /// </summary> public SyntaxToken ElseKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ElseClauseSyntax)this.Green).elseKeyword, Position, 0); public StatementSyntax Statement => GetRed(ref this.statement, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.statement, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.statement : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitElseClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitElseClause(this); public ElseClauseSyntax Update(SyntaxToken elseKeyword, StatementSyntax statement) { if (elseKeyword != this.ElseKeyword || statement != this.Statement) { var newNode = SyntaxFactory.ElseClause(elseKeyword, statement); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ElseClauseSyntax WithElseKeyword(SyntaxToken elseKeyword) => Update(elseKeyword, this.Statement); public ElseClauseSyntax WithStatement(StatementSyntax statement) => Update(this.ElseKeyword, statement); } /// <summary>Represents a switch statement syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.SwitchStatement"/></description></item> /// </list> /// </remarks> public sealed partial class SwitchStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private ExpressionSyntax? expression; private SyntaxNode? sections; internal SwitchStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); /// <summary> /// Gets a SyntaxToken that represents the switch keyword. /// </summary> public SyntaxToken SwitchKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.SwitchStatementSyntax)this.Green).switchKeyword, GetChildPosition(1), GetChildIndex(1)); /// <summary> /// Gets a SyntaxToken that represents the open parenthesis preceding the switch governing expression. /// </summary> public SyntaxToken OpenParenToken { get { var slot = ((Syntax.InternalSyntax.SwitchStatementSyntax)this.Green).openParenToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(2), GetChildIndex(2)) : default; } } /// <summary> /// Gets an ExpressionSyntax representing the expression of the switch statement. /// </summary> public ExpressionSyntax Expression => GetRed(ref this.expression, 3)!; /// <summary> /// Gets a SyntaxToken that represents the close parenthesis following the switch governing expression. /// </summary> public SyntaxToken CloseParenToken { get { var slot = ((Syntax.InternalSyntax.SwitchStatementSyntax)this.Green).closeParenToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(4), GetChildIndex(4)) : default; } } /// <summary> /// Gets a SyntaxToken that represents the open braces preceding the switch sections. /// </summary> public SyntaxToken OpenBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.SwitchStatementSyntax)this.Green).openBraceToken, GetChildPosition(5), GetChildIndex(5)); /// <summary> /// Gets a SyntaxList of SwitchSectionSyntax's that represents the switch sections of the switch statement. /// </summary> public SyntaxList<SwitchSectionSyntax> Sections => new SyntaxList<SwitchSectionSyntax>(GetRed(ref this.sections, 6)); /// <summary> /// Gets a SyntaxToken that represents the open braces following the switch sections. /// </summary> public SyntaxToken CloseBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.SwitchStatementSyntax)this.Green).closeBraceToken, GetChildPosition(7), GetChildIndex(7)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 3 => GetRed(ref this.expression, 3)!, 6 => GetRed(ref this.sections, 6)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 3 => this.expression, 6 => this.sections, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitSwitchStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitSwitchStatement(this); public SwitchStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken switchKeyword, SyntaxToken openParenToken, ExpressionSyntax expression, SyntaxToken closeParenToken, SyntaxToken openBraceToken, SyntaxList<SwitchSectionSyntax> sections, SyntaxToken closeBraceToken) { if (attributeLists != this.AttributeLists || switchKeyword != this.SwitchKeyword || openParenToken != this.OpenParenToken || expression != this.Expression || closeParenToken != this.CloseParenToken || openBraceToken != this.OpenBraceToken || sections != this.Sections || closeBraceToken != this.CloseBraceToken) { var newNode = SyntaxFactory.SwitchStatement(attributeLists, switchKeyword, openParenToken, expression, closeParenToken, openBraceToken, sections, closeBraceToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new SwitchStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.SwitchKeyword, this.OpenParenToken, this.Expression, this.CloseParenToken, this.OpenBraceToken, this.Sections, this.CloseBraceToken); public SwitchStatementSyntax WithSwitchKeyword(SyntaxToken switchKeyword) => Update(this.AttributeLists, switchKeyword, this.OpenParenToken, this.Expression, this.CloseParenToken, this.OpenBraceToken, this.Sections, this.CloseBraceToken); public SwitchStatementSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.AttributeLists, this.SwitchKeyword, openParenToken, this.Expression, this.CloseParenToken, this.OpenBraceToken, this.Sections, this.CloseBraceToken); public SwitchStatementSyntax WithExpression(ExpressionSyntax expression) => Update(this.AttributeLists, this.SwitchKeyword, this.OpenParenToken, expression, this.CloseParenToken, this.OpenBraceToken, this.Sections, this.CloseBraceToken); public SwitchStatementSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.AttributeLists, this.SwitchKeyword, this.OpenParenToken, this.Expression, closeParenToken, this.OpenBraceToken, this.Sections, this.CloseBraceToken); public SwitchStatementSyntax WithOpenBraceToken(SyntaxToken openBraceToken) => Update(this.AttributeLists, this.SwitchKeyword, this.OpenParenToken, this.Expression, this.CloseParenToken, openBraceToken, this.Sections, this.CloseBraceToken); public SwitchStatementSyntax WithSections(SyntaxList<SwitchSectionSyntax> sections) => Update(this.AttributeLists, this.SwitchKeyword, this.OpenParenToken, this.Expression, this.CloseParenToken, this.OpenBraceToken, sections, this.CloseBraceToken); public SwitchStatementSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) => Update(this.AttributeLists, this.SwitchKeyword, this.OpenParenToken, this.Expression, this.CloseParenToken, this.OpenBraceToken, this.Sections, closeBraceToken); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new SwitchStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); public SwitchStatementSyntax AddSections(params SwitchSectionSyntax[] items) => WithSections(this.Sections.AddRange(items)); } /// <summary>Represents a switch section syntax of a switch statement.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.SwitchSection"/></description></item> /// </list> /// </remarks> public sealed partial class SwitchSectionSyntax : CSharpSyntaxNode { private SyntaxNode? labels; private SyntaxNode? statements; internal SwitchSectionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary> /// Gets a SyntaxList of SwitchLabelSyntax's the represents the possible labels that control can transfer to within the section. /// </summary> public SyntaxList<SwitchLabelSyntax> Labels => new SyntaxList<SwitchLabelSyntax>(GetRed(ref this.labels, 0)); /// <summary> /// Gets a SyntaxList of StatementSyntax's the represents the statements to be executed when control transfer to a label the belongs to the section. /// </summary> public SyntaxList<StatementSyntax> Statements => new SyntaxList<StatementSyntax>(GetRed(ref this.statements, 1)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.labels)!, 1 => GetRed(ref this.statements, 1)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.labels, 1 => this.statements, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitSwitchSection(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitSwitchSection(this); public SwitchSectionSyntax Update(SyntaxList<SwitchLabelSyntax> labels, SyntaxList<StatementSyntax> statements) { if (labels != this.Labels || statements != this.Statements) { var newNode = SyntaxFactory.SwitchSection(labels, statements); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public SwitchSectionSyntax WithLabels(SyntaxList<SwitchLabelSyntax> labels) => Update(labels, this.Statements); public SwitchSectionSyntax WithStatements(SyntaxList<StatementSyntax> statements) => Update(this.Labels, statements); public SwitchSectionSyntax AddLabels(params SwitchLabelSyntax[] items) => WithLabels(this.Labels.AddRange(items)); public SwitchSectionSyntax AddStatements(params StatementSyntax[] items) => WithStatements(this.Statements.AddRange(items)); } /// <summary>Represents a switch label within a switch statement.</summary> public abstract partial class SwitchLabelSyntax : CSharpSyntaxNode { internal SwitchLabelSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary> /// Gets a SyntaxToken that represents a case or default keyword that belongs to a switch label. /// </summary> public abstract SyntaxToken Keyword { get; } public SwitchLabelSyntax WithKeyword(SyntaxToken keyword) => WithKeywordCore(keyword); internal abstract SwitchLabelSyntax WithKeywordCore(SyntaxToken keyword); /// <summary> /// Gets a SyntaxToken that represents the colon that terminates the switch label. /// </summary> public abstract SyntaxToken ColonToken { get; } public SwitchLabelSyntax WithColonToken(SyntaxToken colonToken) => WithColonTokenCore(colonToken); internal abstract SwitchLabelSyntax WithColonTokenCore(SyntaxToken colonToken); } /// <summary>Represents a case label within a switch statement.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.CasePatternSwitchLabel"/></description></item> /// </list> /// </remarks> public sealed partial class CasePatternSwitchLabelSyntax : SwitchLabelSyntax { private PatternSyntax? pattern; private WhenClauseSyntax? whenClause; internal CasePatternSwitchLabelSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the case keyword token.</summary> public override SyntaxToken Keyword => new SyntaxToken(this, ((Syntax.InternalSyntax.CasePatternSwitchLabelSyntax)this.Green).keyword, Position, 0); /// <summary> /// Gets a PatternSyntax that represents the pattern that gets matched for the case label. /// </summary> public PatternSyntax Pattern => GetRed(ref this.pattern, 1)!; public WhenClauseSyntax? WhenClause => GetRed(ref this.whenClause, 2); public override SyntaxToken ColonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.CasePatternSwitchLabelSyntax)this.Green).colonToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 1 => GetRed(ref this.pattern, 1)!, 2 => GetRed(ref this.whenClause, 2), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 1 => this.pattern, 2 => this.whenClause, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitCasePatternSwitchLabel(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitCasePatternSwitchLabel(this); public CasePatternSwitchLabelSyntax Update(SyntaxToken keyword, PatternSyntax pattern, WhenClauseSyntax? whenClause, SyntaxToken colonToken) { if (keyword != this.Keyword || pattern != this.Pattern || whenClause != this.WhenClause || colonToken != this.ColonToken) { var newNode = SyntaxFactory.CasePatternSwitchLabel(keyword, pattern, whenClause, colonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override SwitchLabelSyntax WithKeywordCore(SyntaxToken keyword) => WithKeyword(keyword); public new CasePatternSwitchLabelSyntax WithKeyword(SyntaxToken keyword) => Update(keyword, this.Pattern, this.WhenClause, this.ColonToken); public CasePatternSwitchLabelSyntax WithPattern(PatternSyntax pattern) => Update(this.Keyword, pattern, this.WhenClause, this.ColonToken); public CasePatternSwitchLabelSyntax WithWhenClause(WhenClauseSyntax? whenClause) => Update(this.Keyword, this.Pattern, whenClause, this.ColonToken); internal override SwitchLabelSyntax WithColonTokenCore(SyntaxToken colonToken) => WithColonToken(colonToken); public new CasePatternSwitchLabelSyntax WithColonToken(SyntaxToken colonToken) => Update(this.Keyword, this.Pattern, this.WhenClause, colonToken); } /// <summary>Represents a case label within a switch statement.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.CaseSwitchLabel"/></description></item> /// </list> /// </remarks> public sealed partial class CaseSwitchLabelSyntax : SwitchLabelSyntax { private ExpressionSyntax? value; internal CaseSwitchLabelSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the case keyword token.</summary> public override SyntaxToken Keyword => new SyntaxToken(this, ((Syntax.InternalSyntax.CaseSwitchLabelSyntax)this.Green).keyword, Position, 0); /// <summary> /// Gets an ExpressionSyntax that represents the constant expression that gets matched for the case label. /// </summary> public ExpressionSyntax Value => GetRed(ref this.value, 1)!; public override SyntaxToken ColonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.CaseSwitchLabelSyntax)this.Green).colonToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.value, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.value : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitCaseSwitchLabel(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitCaseSwitchLabel(this); public CaseSwitchLabelSyntax Update(SyntaxToken keyword, ExpressionSyntax value, SyntaxToken colonToken) { if (keyword != this.Keyword || value != this.Value || colonToken != this.ColonToken) { var newNode = SyntaxFactory.CaseSwitchLabel(keyword, value, colonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override SwitchLabelSyntax WithKeywordCore(SyntaxToken keyword) => WithKeyword(keyword); public new CaseSwitchLabelSyntax WithKeyword(SyntaxToken keyword) => Update(keyword, this.Value, this.ColonToken); public CaseSwitchLabelSyntax WithValue(ExpressionSyntax value) => Update(this.Keyword, value, this.ColonToken); internal override SwitchLabelSyntax WithColonTokenCore(SyntaxToken colonToken) => WithColonToken(colonToken); public new CaseSwitchLabelSyntax WithColonToken(SyntaxToken colonToken) => Update(this.Keyword, this.Value, colonToken); } /// <summary>Represents a default label within a switch statement.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.DefaultSwitchLabel"/></description></item> /// </list> /// </remarks> public sealed partial class DefaultSwitchLabelSyntax : SwitchLabelSyntax { internal DefaultSwitchLabelSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the default keyword token.</summary> public override SyntaxToken Keyword => new SyntaxToken(this, ((Syntax.InternalSyntax.DefaultSwitchLabelSyntax)this.Green).keyword, Position, 0); public override SyntaxToken ColonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.DefaultSwitchLabelSyntax)this.Green).colonToken, GetChildPosition(1), GetChildIndex(1)); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitDefaultSwitchLabel(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitDefaultSwitchLabel(this); public DefaultSwitchLabelSyntax Update(SyntaxToken keyword, SyntaxToken colonToken) { if (keyword != this.Keyword || colonToken != this.ColonToken) { var newNode = SyntaxFactory.DefaultSwitchLabel(keyword, colonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override SwitchLabelSyntax WithKeywordCore(SyntaxToken keyword) => WithKeyword(keyword); public new DefaultSwitchLabelSyntax WithKeyword(SyntaxToken keyword) => Update(keyword, this.ColonToken); internal override SwitchLabelSyntax WithColonTokenCore(SyntaxToken colonToken) => WithColonToken(colonToken); public new DefaultSwitchLabelSyntax WithColonToken(SyntaxToken colonToken) => Update(this.Keyword, colonToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.SwitchExpression"/></description></item> /// </list> /// </remarks> public sealed partial class SwitchExpressionSyntax : ExpressionSyntax { private ExpressionSyntax? governingExpression; private SyntaxNode? arms; internal SwitchExpressionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public ExpressionSyntax GoverningExpression => GetRedAtZero(ref this.governingExpression)!; public SyntaxToken SwitchKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.SwitchExpressionSyntax)this.Green).switchKeyword, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken OpenBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.SwitchExpressionSyntax)this.Green).openBraceToken, GetChildPosition(2), GetChildIndex(2)); public SeparatedSyntaxList<SwitchExpressionArmSyntax> Arms { get { var red = GetRed(ref this.arms, 3); return red != null ? new SeparatedSyntaxList<SwitchExpressionArmSyntax>(red, GetChildIndex(3)) : default; } } public SyntaxToken CloseBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.SwitchExpressionSyntax)this.Green).closeBraceToken, GetChildPosition(4), GetChildIndex(4)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.governingExpression)!, 3 => GetRed(ref this.arms, 3)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.governingExpression, 3 => this.arms, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitSwitchExpression(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitSwitchExpression(this); public SwitchExpressionSyntax Update(ExpressionSyntax governingExpression, SyntaxToken switchKeyword, SyntaxToken openBraceToken, SeparatedSyntaxList<SwitchExpressionArmSyntax> arms, SyntaxToken closeBraceToken) { if (governingExpression != this.GoverningExpression || switchKeyword != this.SwitchKeyword || openBraceToken != this.OpenBraceToken || arms != this.Arms || closeBraceToken != this.CloseBraceToken) { var newNode = SyntaxFactory.SwitchExpression(governingExpression, switchKeyword, openBraceToken, arms, closeBraceToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public SwitchExpressionSyntax WithGoverningExpression(ExpressionSyntax governingExpression) => Update(governingExpression, this.SwitchKeyword, this.OpenBraceToken, this.Arms, this.CloseBraceToken); public SwitchExpressionSyntax WithSwitchKeyword(SyntaxToken switchKeyword) => Update(this.GoverningExpression, switchKeyword, this.OpenBraceToken, this.Arms, this.CloseBraceToken); public SwitchExpressionSyntax WithOpenBraceToken(SyntaxToken openBraceToken) => Update(this.GoverningExpression, this.SwitchKeyword, openBraceToken, this.Arms, this.CloseBraceToken); public SwitchExpressionSyntax WithArms(SeparatedSyntaxList<SwitchExpressionArmSyntax> arms) => Update(this.GoverningExpression, this.SwitchKeyword, this.OpenBraceToken, arms, this.CloseBraceToken); public SwitchExpressionSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) => Update(this.GoverningExpression, this.SwitchKeyword, this.OpenBraceToken, this.Arms, closeBraceToken); public SwitchExpressionSyntax AddArms(params SwitchExpressionArmSyntax[] items) => WithArms(this.Arms.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.SwitchExpressionArm"/></description></item> /// </list> /// </remarks> public sealed partial class SwitchExpressionArmSyntax : CSharpSyntaxNode { private PatternSyntax? pattern; private WhenClauseSyntax? whenClause; private ExpressionSyntax? expression; internal SwitchExpressionArmSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public PatternSyntax Pattern => GetRedAtZero(ref this.pattern)!; public WhenClauseSyntax? WhenClause => GetRed(ref this.whenClause, 1); public SyntaxToken EqualsGreaterThanToken => new SyntaxToken(this, ((Syntax.InternalSyntax.SwitchExpressionArmSyntax)this.Green).equalsGreaterThanToken, GetChildPosition(2), GetChildIndex(2)); public ExpressionSyntax Expression => GetRed(ref this.expression, 3)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.pattern)!, 1 => GetRed(ref this.whenClause, 1), 3 => GetRed(ref this.expression, 3)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.pattern, 1 => this.whenClause, 3 => this.expression, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitSwitchExpressionArm(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitSwitchExpressionArm(this); public SwitchExpressionArmSyntax Update(PatternSyntax pattern, WhenClauseSyntax? whenClause, SyntaxToken equalsGreaterThanToken, ExpressionSyntax expression) { if (pattern != this.Pattern || whenClause != this.WhenClause || equalsGreaterThanToken != this.EqualsGreaterThanToken || expression != this.Expression) { var newNode = SyntaxFactory.SwitchExpressionArm(pattern, whenClause, equalsGreaterThanToken, expression); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public SwitchExpressionArmSyntax WithPattern(PatternSyntax pattern) => Update(pattern, this.WhenClause, this.EqualsGreaterThanToken, this.Expression); public SwitchExpressionArmSyntax WithWhenClause(WhenClauseSyntax? whenClause) => Update(this.Pattern, whenClause, this.EqualsGreaterThanToken, this.Expression); public SwitchExpressionArmSyntax WithEqualsGreaterThanToken(SyntaxToken equalsGreaterThanToken) => Update(this.Pattern, this.WhenClause, equalsGreaterThanToken, this.Expression); public SwitchExpressionArmSyntax WithExpression(ExpressionSyntax expression) => Update(this.Pattern, this.WhenClause, this.EqualsGreaterThanToken, expression); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.TryStatement"/></description></item> /// </list> /// </remarks> public sealed partial class TryStatementSyntax : StatementSyntax { private SyntaxNode? attributeLists; private BlockSyntax? block; private SyntaxNode? catches; private FinallyClauseSyntax? @finally; internal TryStatementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxToken TryKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.TryStatementSyntax)this.Green).tryKeyword, GetChildPosition(1), GetChildIndex(1)); public BlockSyntax Block => GetRed(ref this.block, 2)!; public SyntaxList<CatchClauseSyntax> Catches => new SyntaxList<CatchClauseSyntax>(GetRed(ref this.catches, 3)); public FinallyClauseSyntax? Finally => GetRed(ref this.@finally, 4); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.block, 2)!, 3 => GetRed(ref this.catches, 3)!, 4 => GetRed(ref this.@finally, 4), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.block, 3 => this.catches, 4 => this.@finally, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitTryStatement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitTryStatement(this); public TryStatementSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken tryKeyword, BlockSyntax block, SyntaxList<CatchClauseSyntax> catches, FinallyClauseSyntax? @finally) { if (attributeLists != this.AttributeLists || tryKeyword != this.TryKeyword || block != this.Block || catches != this.Catches || @finally != this.Finally) { var newNode = SyntaxFactory.TryStatement(attributeLists, tryKeyword, block, catches, @finally); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override StatementSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new TryStatementSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.TryKeyword, this.Block, this.Catches, this.Finally); public TryStatementSyntax WithTryKeyword(SyntaxToken tryKeyword) => Update(this.AttributeLists, tryKeyword, this.Block, this.Catches, this.Finally); public TryStatementSyntax WithBlock(BlockSyntax block) => Update(this.AttributeLists, this.TryKeyword, block, this.Catches, this.Finally); public TryStatementSyntax WithCatches(SyntaxList<CatchClauseSyntax> catches) => Update(this.AttributeLists, this.TryKeyword, this.Block, catches, this.Finally); public TryStatementSyntax WithFinally(FinallyClauseSyntax? @finally) => Update(this.AttributeLists, this.TryKeyword, this.Block, this.Catches, @finally); internal override StatementSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new TryStatementSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); public TryStatementSyntax AddBlockAttributeLists(params AttributeListSyntax[] items) => WithBlock(this.Block.WithAttributeLists(this.Block.AttributeLists.AddRange(items))); public TryStatementSyntax AddBlockStatements(params StatementSyntax[] items) => WithBlock(this.Block.WithStatements(this.Block.Statements.AddRange(items))); public TryStatementSyntax AddCatches(params CatchClauseSyntax[] items) => WithCatches(this.Catches.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.CatchClause"/></description></item> /// </list> /// </remarks> public sealed partial class CatchClauseSyntax : CSharpSyntaxNode { private CatchDeclarationSyntax? declaration; private CatchFilterClauseSyntax? filter; private BlockSyntax? block; internal CatchClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken CatchKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.CatchClauseSyntax)this.Green).catchKeyword, Position, 0); public CatchDeclarationSyntax? Declaration => GetRed(ref this.declaration, 1); public CatchFilterClauseSyntax? Filter => GetRed(ref this.filter, 2); public BlockSyntax Block => GetRed(ref this.block, 3)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 1 => GetRed(ref this.declaration, 1), 2 => GetRed(ref this.filter, 2), 3 => GetRed(ref this.block, 3)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 1 => this.declaration, 2 => this.filter, 3 => this.block, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitCatchClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitCatchClause(this); public CatchClauseSyntax Update(SyntaxToken catchKeyword, CatchDeclarationSyntax? declaration, CatchFilterClauseSyntax? filter, BlockSyntax block) { if (catchKeyword != this.CatchKeyword || declaration != this.Declaration || filter != this.Filter || block != this.Block) { var newNode = SyntaxFactory.CatchClause(catchKeyword, declaration, filter, block); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public CatchClauseSyntax WithCatchKeyword(SyntaxToken catchKeyword) => Update(catchKeyword, this.Declaration, this.Filter, this.Block); public CatchClauseSyntax WithDeclaration(CatchDeclarationSyntax? declaration) => Update(this.CatchKeyword, declaration, this.Filter, this.Block); public CatchClauseSyntax WithFilter(CatchFilterClauseSyntax? filter) => Update(this.CatchKeyword, this.Declaration, filter, this.Block); public CatchClauseSyntax WithBlock(BlockSyntax block) => Update(this.CatchKeyword, this.Declaration, this.Filter, block); public CatchClauseSyntax AddBlockAttributeLists(params AttributeListSyntax[] items) => WithBlock(this.Block.WithAttributeLists(this.Block.AttributeLists.AddRange(items))); public CatchClauseSyntax AddBlockStatements(params StatementSyntax[] items) => WithBlock(this.Block.WithStatements(this.Block.Statements.AddRange(items))); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.CatchDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class CatchDeclarationSyntax : CSharpSyntaxNode { private TypeSyntax? type; internal CatchDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.CatchDeclarationSyntax)this.Green).openParenToken, Position, 0); public TypeSyntax Type => GetRed(ref this.type, 1)!; public SyntaxToken Identifier { get { var slot = ((Syntax.InternalSyntax.CatchDeclarationSyntax)this.Green).identifier; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(2), GetChildIndex(2)) : default; } } public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.CatchDeclarationSyntax)this.Green).closeParenToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.type, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.type : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitCatchDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitCatchDeclaration(this); public CatchDeclarationSyntax Update(SyntaxToken openParenToken, TypeSyntax type, SyntaxToken identifier, SyntaxToken closeParenToken) { if (openParenToken != this.OpenParenToken || type != this.Type || identifier != this.Identifier || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.CatchDeclaration(openParenToken, type, identifier, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public CatchDeclarationSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(openParenToken, this.Type, this.Identifier, this.CloseParenToken); public CatchDeclarationSyntax WithType(TypeSyntax type) => Update(this.OpenParenToken, type, this.Identifier, this.CloseParenToken); public CatchDeclarationSyntax WithIdentifier(SyntaxToken identifier) => Update(this.OpenParenToken, this.Type, identifier, this.CloseParenToken); public CatchDeclarationSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.OpenParenToken, this.Type, this.Identifier, closeParenToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.CatchFilterClause"/></description></item> /// </list> /// </remarks> public sealed partial class CatchFilterClauseSyntax : CSharpSyntaxNode { private ExpressionSyntax? filterExpression; internal CatchFilterClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken WhenKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.CatchFilterClauseSyntax)this.Green).whenKeyword, Position, 0); public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.CatchFilterClauseSyntax)this.Green).openParenToken, GetChildPosition(1), GetChildIndex(1)); public ExpressionSyntax FilterExpression => GetRed(ref this.filterExpression, 2)!; public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.CatchFilterClauseSyntax)this.Green).closeParenToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => index == 2 ? GetRed(ref this.filterExpression, 2)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 2 ? this.filterExpression : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitCatchFilterClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitCatchFilterClause(this); public CatchFilterClauseSyntax Update(SyntaxToken whenKeyword, SyntaxToken openParenToken, ExpressionSyntax filterExpression, SyntaxToken closeParenToken) { if (whenKeyword != this.WhenKeyword || openParenToken != this.OpenParenToken || filterExpression != this.FilterExpression || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.CatchFilterClause(whenKeyword, openParenToken, filterExpression, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public CatchFilterClauseSyntax WithWhenKeyword(SyntaxToken whenKeyword) => Update(whenKeyword, this.OpenParenToken, this.FilterExpression, this.CloseParenToken); public CatchFilterClauseSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.WhenKeyword, openParenToken, this.FilterExpression, this.CloseParenToken); public CatchFilterClauseSyntax WithFilterExpression(ExpressionSyntax filterExpression) => Update(this.WhenKeyword, this.OpenParenToken, filterExpression, this.CloseParenToken); public CatchFilterClauseSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.WhenKeyword, this.OpenParenToken, this.FilterExpression, closeParenToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.FinallyClause"/></description></item> /// </list> /// </remarks> public sealed partial class FinallyClauseSyntax : CSharpSyntaxNode { private BlockSyntax? block; internal FinallyClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken FinallyKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.FinallyClauseSyntax)this.Green).finallyKeyword, Position, 0); public BlockSyntax Block => GetRed(ref this.block, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.block, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.block : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitFinallyClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitFinallyClause(this); public FinallyClauseSyntax Update(SyntaxToken finallyKeyword, BlockSyntax block) { if (finallyKeyword != this.FinallyKeyword || block != this.Block) { var newNode = SyntaxFactory.FinallyClause(finallyKeyword, block); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public FinallyClauseSyntax WithFinallyKeyword(SyntaxToken finallyKeyword) => Update(finallyKeyword, this.Block); public FinallyClauseSyntax WithBlock(BlockSyntax block) => Update(this.FinallyKeyword, block); public FinallyClauseSyntax AddBlockAttributeLists(params AttributeListSyntax[] items) => WithBlock(this.Block.WithAttributeLists(this.Block.AttributeLists.AddRange(items))); public FinallyClauseSyntax AddBlockStatements(params StatementSyntax[] items) => WithBlock(this.Block.WithStatements(this.Block.Statements.AddRange(items))); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.CompilationUnit"/></description></item> /// </list> /// </remarks> public sealed partial class CompilationUnitSyntax : CSharpSyntaxNode { private SyntaxNode? externs; private SyntaxNode? usings; private SyntaxNode? attributeLists; private SyntaxNode? members; internal CompilationUnitSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxList<ExternAliasDirectiveSyntax> Externs => new SyntaxList<ExternAliasDirectiveSyntax>(GetRed(ref this.externs, 0)); public SyntaxList<UsingDirectiveSyntax> Usings => new SyntaxList<UsingDirectiveSyntax>(GetRed(ref this.usings, 1)); /// <summary>Gets the attribute declaration list.</summary> public SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 2)); public SyntaxList<MemberDeclarationSyntax> Members => new SyntaxList<MemberDeclarationSyntax>(GetRed(ref this.members, 3)); public SyntaxToken EndOfFileToken => new SyntaxToken(this, ((Syntax.InternalSyntax.CompilationUnitSyntax)this.Green).endOfFileToken, GetChildPosition(4), GetChildIndex(4)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.externs)!, 1 => GetRed(ref this.usings, 1)!, 2 => GetRed(ref this.attributeLists, 2)!, 3 => GetRed(ref this.members, 3)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.externs, 1 => this.usings, 2 => this.attributeLists, 3 => this.members, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitCompilationUnit(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitCompilationUnit(this); public CompilationUnitSyntax Update(SyntaxList<ExternAliasDirectiveSyntax> externs, SyntaxList<UsingDirectiveSyntax> usings, SyntaxList<AttributeListSyntax> attributeLists, SyntaxList<MemberDeclarationSyntax> members, SyntaxToken endOfFileToken) { if (externs != this.Externs || usings != this.Usings || attributeLists != this.AttributeLists || members != this.Members || endOfFileToken != this.EndOfFileToken) { var newNode = SyntaxFactory.CompilationUnit(externs, usings, attributeLists, members, endOfFileToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public CompilationUnitSyntax WithExterns(SyntaxList<ExternAliasDirectiveSyntax> externs) => Update(externs, this.Usings, this.AttributeLists, this.Members, this.EndOfFileToken); public CompilationUnitSyntax WithUsings(SyntaxList<UsingDirectiveSyntax> usings) => Update(this.Externs, usings, this.AttributeLists, this.Members, this.EndOfFileToken); public CompilationUnitSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(this.Externs, this.Usings, attributeLists, this.Members, this.EndOfFileToken); public CompilationUnitSyntax WithMembers(SyntaxList<MemberDeclarationSyntax> members) => Update(this.Externs, this.Usings, this.AttributeLists, members, this.EndOfFileToken); public CompilationUnitSyntax WithEndOfFileToken(SyntaxToken endOfFileToken) => Update(this.Externs, this.Usings, this.AttributeLists, this.Members, endOfFileToken); public CompilationUnitSyntax AddExterns(params ExternAliasDirectiveSyntax[] items) => WithExterns(this.Externs.AddRange(items)); public CompilationUnitSyntax AddUsings(params UsingDirectiveSyntax[] items) => WithUsings(this.Usings.AddRange(items)); public CompilationUnitSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); public CompilationUnitSyntax AddMembers(params MemberDeclarationSyntax[] items) => WithMembers(this.Members.AddRange(items)); } /// <summary> /// Represents an ExternAlias directive syntax, e.g. "extern alias MyAlias;" with specifying "/r:MyAlias=SomeAssembly.dll " on the compiler command line. /// </summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ExternAliasDirective"/></description></item> /// </list> /// </remarks> public sealed partial class ExternAliasDirectiveSyntax : CSharpSyntaxNode { internal ExternAliasDirectiveSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>SyntaxToken representing the extern keyword.</summary> public SyntaxToken ExternKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ExternAliasDirectiveSyntax)this.Green).externKeyword, Position, 0); /// <summary>SyntaxToken representing the alias keyword.</summary> public SyntaxToken AliasKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ExternAliasDirectiveSyntax)this.Green).aliasKeyword, GetChildPosition(1), GetChildIndex(1)); /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.ExternAliasDirectiveSyntax)this.Green).identifier, GetChildPosition(2), GetChildIndex(2)); /// <summary>SyntaxToken representing the semicolon token.</summary> public SyntaxToken SemicolonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ExternAliasDirectiveSyntax)this.Green).semicolonToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitExternAliasDirective(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitExternAliasDirective(this); public ExternAliasDirectiveSyntax Update(SyntaxToken externKeyword, SyntaxToken aliasKeyword, SyntaxToken identifier, SyntaxToken semicolonToken) { if (externKeyword != this.ExternKeyword || aliasKeyword != this.AliasKeyword || identifier != this.Identifier || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.ExternAliasDirective(externKeyword, aliasKeyword, identifier, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ExternAliasDirectiveSyntax WithExternKeyword(SyntaxToken externKeyword) => Update(externKeyword, this.AliasKeyword, this.Identifier, this.SemicolonToken); public ExternAliasDirectiveSyntax WithAliasKeyword(SyntaxToken aliasKeyword) => Update(this.ExternKeyword, aliasKeyword, this.Identifier, this.SemicolonToken); public ExternAliasDirectiveSyntax WithIdentifier(SyntaxToken identifier) => Update(this.ExternKeyword, this.AliasKeyword, identifier, this.SemicolonToken); public ExternAliasDirectiveSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.ExternKeyword, this.AliasKeyword, this.Identifier, semicolonToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.UsingDirective"/></description></item> /// </list> /// </remarks> public sealed partial class UsingDirectiveSyntax : CSharpSyntaxNode { private NameEqualsSyntax? alias; private NameSyntax? name; internal UsingDirectiveSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken GlobalKeyword { get { var slot = ((Syntax.InternalSyntax.UsingDirectiveSyntax)this.Green).globalKeyword; return slot != null ? new SyntaxToken(this, slot, Position, 0) : default; } } public SyntaxToken UsingKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.UsingDirectiveSyntax)this.Green).usingKeyword, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken StaticKeyword { get { var slot = ((Syntax.InternalSyntax.UsingDirectiveSyntax)this.Green).staticKeyword; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(2), GetChildIndex(2)) : default; } } public NameEqualsSyntax? Alias => GetRed(ref this.alias, 3); public NameSyntax Name => GetRed(ref this.name, 4)!; public SyntaxToken SemicolonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.UsingDirectiveSyntax)this.Green).semicolonToken, GetChildPosition(5), GetChildIndex(5)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 3 => GetRed(ref this.alias, 3), 4 => GetRed(ref this.name, 4)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 3 => this.alias, 4 => this.name, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitUsingDirective(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitUsingDirective(this); public UsingDirectiveSyntax Update(SyntaxToken globalKeyword, SyntaxToken usingKeyword, SyntaxToken staticKeyword, NameEqualsSyntax? alias, NameSyntax name, SyntaxToken semicolonToken) { if (globalKeyword != this.GlobalKeyword || usingKeyword != this.UsingKeyword || staticKeyword != this.StaticKeyword || alias != this.Alias || name != this.Name || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.UsingDirective(globalKeyword, usingKeyword, staticKeyword, alias, name, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public UsingDirectiveSyntax WithGlobalKeyword(SyntaxToken globalKeyword) => Update(globalKeyword, this.UsingKeyword, this.StaticKeyword, this.Alias, this.Name, this.SemicolonToken); public UsingDirectiveSyntax WithUsingKeyword(SyntaxToken usingKeyword) => Update(this.GlobalKeyword, usingKeyword, this.StaticKeyword, this.Alias, this.Name, this.SemicolonToken); public UsingDirectiveSyntax WithStaticKeyword(SyntaxToken staticKeyword) => Update(this.GlobalKeyword, this.UsingKeyword, staticKeyword, this.Alias, this.Name, this.SemicolonToken); public UsingDirectiveSyntax WithAlias(NameEqualsSyntax? alias) => Update(this.GlobalKeyword, this.UsingKeyword, this.StaticKeyword, alias, this.Name, this.SemicolonToken); public UsingDirectiveSyntax WithName(NameSyntax name) => Update(this.GlobalKeyword, this.UsingKeyword, this.StaticKeyword, this.Alias, name, this.SemicolonToken); public UsingDirectiveSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.GlobalKeyword, this.UsingKeyword, this.StaticKeyword, this.Alias, this.Name, semicolonToken); } /// <summary>Member declaration syntax.</summary> public abstract partial class MemberDeclarationSyntax : CSharpSyntaxNode { internal MemberDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the attribute declaration list.</summary> public abstract SyntaxList<AttributeListSyntax> AttributeLists { get; } public MemberDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeListsCore(attributeLists); internal abstract MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists); public MemberDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => AddAttributeListsCore(items); internal abstract MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items); /// <summary>Gets the modifier list.</summary> public abstract SyntaxTokenList Modifiers { get; } public MemberDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => WithModifiersCore(modifiers); internal abstract MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers); public MemberDeclarationSyntax AddModifiers(params SyntaxToken[] items) => AddModifiersCore(items); internal abstract MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items); } public abstract partial class BaseNamespaceDeclarationSyntax : MemberDeclarationSyntax { internal BaseNamespaceDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public abstract SyntaxToken NamespaceKeyword { get; } public BaseNamespaceDeclarationSyntax WithNamespaceKeyword(SyntaxToken namespaceKeyword) => WithNamespaceKeywordCore(namespaceKeyword); internal abstract BaseNamespaceDeclarationSyntax WithNamespaceKeywordCore(SyntaxToken namespaceKeyword); public abstract NameSyntax Name { get; } public BaseNamespaceDeclarationSyntax WithName(NameSyntax name) => WithNameCore(name); internal abstract BaseNamespaceDeclarationSyntax WithNameCore(NameSyntax name); public abstract SyntaxList<ExternAliasDirectiveSyntax> Externs { get; } public BaseNamespaceDeclarationSyntax WithExterns(SyntaxList<ExternAliasDirectiveSyntax> externs) => WithExternsCore(externs); internal abstract BaseNamespaceDeclarationSyntax WithExternsCore(SyntaxList<ExternAliasDirectiveSyntax> externs); public BaseNamespaceDeclarationSyntax AddExterns(params ExternAliasDirectiveSyntax[] items) => AddExternsCore(items); internal abstract BaseNamespaceDeclarationSyntax AddExternsCore(params ExternAliasDirectiveSyntax[] items); public abstract SyntaxList<UsingDirectiveSyntax> Usings { get; } public BaseNamespaceDeclarationSyntax WithUsings(SyntaxList<UsingDirectiveSyntax> usings) => WithUsingsCore(usings); internal abstract BaseNamespaceDeclarationSyntax WithUsingsCore(SyntaxList<UsingDirectiveSyntax> usings); public BaseNamespaceDeclarationSyntax AddUsings(params UsingDirectiveSyntax[] items) => AddUsingsCore(items); internal abstract BaseNamespaceDeclarationSyntax AddUsingsCore(params UsingDirectiveSyntax[] items); public abstract SyntaxList<MemberDeclarationSyntax> Members { get; } public BaseNamespaceDeclarationSyntax WithMembers(SyntaxList<MemberDeclarationSyntax> members) => WithMembersCore(members); internal abstract BaseNamespaceDeclarationSyntax WithMembersCore(SyntaxList<MemberDeclarationSyntax> members); public BaseNamespaceDeclarationSyntax AddMembers(params MemberDeclarationSyntax[] items) => AddMembersCore(items); internal abstract BaseNamespaceDeclarationSyntax AddMembersCore(params MemberDeclarationSyntax[] items); public new BaseNamespaceDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => (BaseNamespaceDeclarationSyntax)WithAttributeListsCore(attributeLists); public new BaseNamespaceDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => (BaseNamespaceDeclarationSyntax)WithModifiersCore(modifiers); public new BaseNamespaceDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => (BaseNamespaceDeclarationSyntax)AddAttributeListsCore(items); public new BaseNamespaceDeclarationSyntax AddModifiers(params SyntaxToken[] items) => (BaseNamespaceDeclarationSyntax)AddModifiersCore(items); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.NamespaceDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class NamespaceDeclarationSyntax : BaseNamespaceDeclarationSyntax { private SyntaxNode? attributeLists; private NameSyntax? name; private SyntaxNode? externs; private SyntaxNode? usings; private SyntaxNode? members; internal NamespaceDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public override SyntaxToken NamespaceKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.NamespaceDeclarationSyntax)this.Green).namespaceKeyword, GetChildPosition(2), GetChildIndex(2)); public override NameSyntax Name => GetRed(ref this.name, 3)!; public SyntaxToken OpenBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.NamespaceDeclarationSyntax)this.Green).openBraceToken, GetChildPosition(4), GetChildIndex(4)); public override SyntaxList<ExternAliasDirectiveSyntax> Externs => new SyntaxList<ExternAliasDirectiveSyntax>(GetRed(ref this.externs, 5)); public override SyntaxList<UsingDirectiveSyntax> Usings => new SyntaxList<UsingDirectiveSyntax>(GetRed(ref this.usings, 6)); public override SyntaxList<MemberDeclarationSyntax> Members => new SyntaxList<MemberDeclarationSyntax>(GetRed(ref this.members, 7)); public SyntaxToken CloseBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.NamespaceDeclarationSyntax)this.Green).closeBraceToken, GetChildPosition(8), GetChildIndex(8)); /// <summary>Gets the optional semicolon token.</summary> public SyntaxToken SemicolonToken { get { var slot = ((Syntax.InternalSyntax.NamespaceDeclarationSyntax)this.Green).semicolonToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(9), GetChildIndex(9)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 3 => GetRed(ref this.name, 3)!, 5 => GetRed(ref this.externs, 5)!, 6 => GetRed(ref this.usings, 6)!, 7 => GetRed(ref this.members, 7)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 3 => this.name, 5 => this.externs, 6 => this.usings, 7 => this.members, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitNamespaceDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitNamespaceDeclaration(this); public NamespaceDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken namespaceKeyword, NameSyntax name, SyntaxToken openBraceToken, SyntaxList<ExternAliasDirectiveSyntax> externs, SyntaxList<UsingDirectiveSyntax> usings, SyntaxList<MemberDeclarationSyntax> members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || namespaceKeyword != this.NamespaceKeyword || name != this.Name || openBraceToken != this.OpenBraceToken || externs != this.Externs || usings != this.Usings || members != this.Members || closeBraceToken != this.CloseBraceToken || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.NamespaceDeclaration(attributeLists, modifiers, namespaceKeyword, name, openBraceToken, externs, usings, members, closeBraceToken, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new NamespaceDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.NamespaceKeyword, this.Name, this.OpenBraceToken, this.Externs, this.Usings, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new NamespaceDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.NamespaceKeyword, this.Name, this.OpenBraceToken, this.Externs, this.Usings, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseNamespaceDeclarationSyntax WithNamespaceKeywordCore(SyntaxToken namespaceKeyword) => WithNamespaceKeyword(namespaceKeyword); public new NamespaceDeclarationSyntax WithNamespaceKeyword(SyntaxToken namespaceKeyword) => Update(this.AttributeLists, this.Modifiers, namespaceKeyword, this.Name, this.OpenBraceToken, this.Externs, this.Usings, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseNamespaceDeclarationSyntax WithNameCore(NameSyntax name) => WithName(name); public new NamespaceDeclarationSyntax WithName(NameSyntax name) => Update(this.AttributeLists, this.Modifiers, this.NamespaceKeyword, name, this.OpenBraceToken, this.Externs, this.Usings, this.Members, this.CloseBraceToken, this.SemicolonToken); public NamespaceDeclarationSyntax WithOpenBraceToken(SyntaxToken openBraceToken) => Update(this.AttributeLists, this.Modifiers, this.NamespaceKeyword, this.Name, openBraceToken, this.Externs, this.Usings, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseNamespaceDeclarationSyntax WithExternsCore(SyntaxList<ExternAliasDirectiveSyntax> externs) => WithExterns(externs); public new NamespaceDeclarationSyntax WithExterns(SyntaxList<ExternAliasDirectiveSyntax> externs) => Update(this.AttributeLists, this.Modifiers, this.NamespaceKeyword, this.Name, this.OpenBraceToken, externs, this.Usings, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseNamespaceDeclarationSyntax WithUsingsCore(SyntaxList<UsingDirectiveSyntax> usings) => WithUsings(usings); public new NamespaceDeclarationSyntax WithUsings(SyntaxList<UsingDirectiveSyntax> usings) => Update(this.AttributeLists, this.Modifiers, this.NamespaceKeyword, this.Name, this.OpenBraceToken, this.Externs, usings, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseNamespaceDeclarationSyntax WithMembersCore(SyntaxList<MemberDeclarationSyntax> members) => WithMembers(members); public new NamespaceDeclarationSyntax WithMembers(SyntaxList<MemberDeclarationSyntax> members) => Update(this.AttributeLists, this.Modifiers, this.NamespaceKeyword, this.Name, this.OpenBraceToken, this.Externs, this.Usings, members, this.CloseBraceToken, this.SemicolonToken); public NamespaceDeclarationSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) => Update(this.AttributeLists, this.Modifiers, this.NamespaceKeyword, this.Name, this.OpenBraceToken, this.Externs, this.Usings, this.Members, closeBraceToken, this.SemicolonToken); public NamespaceDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.NamespaceKeyword, this.Name, this.OpenBraceToken, this.Externs, this.Usings, this.Members, this.CloseBraceToken, semicolonToken); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new NamespaceDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new NamespaceDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); internal override BaseNamespaceDeclarationSyntax AddExternsCore(params ExternAliasDirectiveSyntax[] items) => AddExterns(items); public new NamespaceDeclarationSyntax AddExterns(params ExternAliasDirectiveSyntax[] items) => WithExterns(this.Externs.AddRange(items)); internal override BaseNamespaceDeclarationSyntax AddUsingsCore(params UsingDirectiveSyntax[] items) => AddUsings(items); public new NamespaceDeclarationSyntax AddUsings(params UsingDirectiveSyntax[] items) => WithUsings(this.Usings.AddRange(items)); internal override BaseNamespaceDeclarationSyntax AddMembersCore(params MemberDeclarationSyntax[] items) => AddMembers(items); public new NamespaceDeclarationSyntax AddMembers(params MemberDeclarationSyntax[] items) => WithMembers(this.Members.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.FileScopedNamespaceDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class FileScopedNamespaceDeclarationSyntax : BaseNamespaceDeclarationSyntax { private SyntaxNode? attributeLists; private NameSyntax? name; private SyntaxNode? externs; private SyntaxNode? usings; private SyntaxNode? members; internal FileScopedNamespaceDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public override SyntaxToken NamespaceKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.FileScopedNamespaceDeclarationSyntax)this.Green).namespaceKeyword, GetChildPosition(2), GetChildIndex(2)); public override NameSyntax Name => GetRed(ref this.name, 3)!; public SyntaxToken SemicolonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.FileScopedNamespaceDeclarationSyntax)this.Green).semicolonToken, GetChildPosition(4), GetChildIndex(4)); public override SyntaxList<ExternAliasDirectiveSyntax> Externs => new SyntaxList<ExternAliasDirectiveSyntax>(GetRed(ref this.externs, 5)); public override SyntaxList<UsingDirectiveSyntax> Usings => new SyntaxList<UsingDirectiveSyntax>(GetRed(ref this.usings, 6)); public override SyntaxList<MemberDeclarationSyntax> Members => new SyntaxList<MemberDeclarationSyntax>(GetRed(ref this.members, 7)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 3 => GetRed(ref this.name, 3)!, 5 => GetRed(ref this.externs, 5)!, 6 => GetRed(ref this.usings, 6)!, 7 => GetRed(ref this.members, 7)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 3 => this.name, 5 => this.externs, 6 => this.usings, 7 => this.members, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitFileScopedNamespaceDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitFileScopedNamespaceDeclaration(this); public FileScopedNamespaceDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken namespaceKeyword, NameSyntax name, SyntaxToken semicolonToken, SyntaxList<ExternAliasDirectiveSyntax> externs, SyntaxList<UsingDirectiveSyntax> usings, SyntaxList<MemberDeclarationSyntax> members) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || namespaceKeyword != this.NamespaceKeyword || name != this.Name || semicolonToken != this.SemicolonToken || externs != this.Externs || usings != this.Usings || members != this.Members) { var newNode = SyntaxFactory.FileScopedNamespaceDeclaration(attributeLists, modifiers, namespaceKeyword, name, semicolonToken, externs, usings, members); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new FileScopedNamespaceDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.NamespaceKeyword, this.Name, this.SemicolonToken, this.Externs, this.Usings, this.Members); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new FileScopedNamespaceDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.NamespaceKeyword, this.Name, this.SemicolonToken, this.Externs, this.Usings, this.Members); internal override BaseNamespaceDeclarationSyntax WithNamespaceKeywordCore(SyntaxToken namespaceKeyword) => WithNamespaceKeyword(namespaceKeyword); public new FileScopedNamespaceDeclarationSyntax WithNamespaceKeyword(SyntaxToken namespaceKeyword) => Update(this.AttributeLists, this.Modifiers, namespaceKeyword, this.Name, this.SemicolonToken, this.Externs, this.Usings, this.Members); internal override BaseNamespaceDeclarationSyntax WithNameCore(NameSyntax name) => WithName(name); public new FileScopedNamespaceDeclarationSyntax WithName(NameSyntax name) => Update(this.AttributeLists, this.Modifiers, this.NamespaceKeyword, name, this.SemicolonToken, this.Externs, this.Usings, this.Members); public FileScopedNamespaceDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.NamespaceKeyword, this.Name, semicolonToken, this.Externs, this.Usings, this.Members); internal override BaseNamespaceDeclarationSyntax WithExternsCore(SyntaxList<ExternAliasDirectiveSyntax> externs) => WithExterns(externs); public new FileScopedNamespaceDeclarationSyntax WithExterns(SyntaxList<ExternAliasDirectiveSyntax> externs) => Update(this.AttributeLists, this.Modifiers, this.NamespaceKeyword, this.Name, this.SemicolonToken, externs, this.Usings, this.Members); internal override BaseNamespaceDeclarationSyntax WithUsingsCore(SyntaxList<UsingDirectiveSyntax> usings) => WithUsings(usings); public new FileScopedNamespaceDeclarationSyntax WithUsings(SyntaxList<UsingDirectiveSyntax> usings) => Update(this.AttributeLists, this.Modifiers, this.NamespaceKeyword, this.Name, this.SemicolonToken, this.Externs, usings, this.Members); internal override BaseNamespaceDeclarationSyntax WithMembersCore(SyntaxList<MemberDeclarationSyntax> members) => WithMembers(members); public new FileScopedNamespaceDeclarationSyntax WithMembers(SyntaxList<MemberDeclarationSyntax> members) => Update(this.AttributeLists, this.Modifiers, this.NamespaceKeyword, this.Name, this.SemicolonToken, this.Externs, this.Usings, members); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new FileScopedNamespaceDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new FileScopedNamespaceDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); internal override BaseNamespaceDeclarationSyntax AddExternsCore(params ExternAliasDirectiveSyntax[] items) => AddExterns(items); public new FileScopedNamespaceDeclarationSyntax AddExterns(params ExternAliasDirectiveSyntax[] items) => WithExterns(this.Externs.AddRange(items)); internal override BaseNamespaceDeclarationSyntax AddUsingsCore(params UsingDirectiveSyntax[] items) => AddUsings(items); public new FileScopedNamespaceDeclarationSyntax AddUsings(params UsingDirectiveSyntax[] items) => WithUsings(this.Usings.AddRange(items)); internal override BaseNamespaceDeclarationSyntax AddMembersCore(params MemberDeclarationSyntax[] items) => AddMembers(items); public new FileScopedNamespaceDeclarationSyntax AddMembers(params MemberDeclarationSyntax[] items) => WithMembers(this.Members.AddRange(items)); } /// <summary>Class representing one or more attributes applied to a language construct.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.AttributeList"/></description></item> /// </list> /// </remarks> public sealed partial class AttributeListSyntax : CSharpSyntaxNode { private AttributeTargetSpecifierSyntax? target; private SyntaxNode? attributes; internal AttributeListSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the open bracket token.</summary> public SyntaxToken OpenBracketToken => new SyntaxToken(this, ((Syntax.InternalSyntax.AttributeListSyntax)this.Green).openBracketToken, Position, 0); /// <summary>Gets the optional construct targeted by the attribute.</summary> public AttributeTargetSpecifierSyntax? Target => GetRed(ref this.target, 1); /// <summary>Gets the attribute declaration list.</summary> public SeparatedSyntaxList<AttributeSyntax> Attributes { get { var red = GetRed(ref this.attributes, 2); return red != null ? new SeparatedSyntaxList<AttributeSyntax>(red, GetChildIndex(2)) : default; } } /// <summary>Gets the close bracket token.</summary> public SyntaxToken CloseBracketToken => new SyntaxToken(this, ((Syntax.InternalSyntax.AttributeListSyntax)this.Green).closeBracketToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 1 => GetRed(ref this.target, 1), 2 => GetRed(ref this.attributes, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 1 => this.target, 2 => this.attributes, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitAttributeList(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitAttributeList(this); public AttributeListSyntax Update(SyntaxToken openBracketToken, AttributeTargetSpecifierSyntax? target, SeparatedSyntaxList<AttributeSyntax> attributes, SyntaxToken closeBracketToken) { if (openBracketToken != this.OpenBracketToken || target != this.Target || attributes != this.Attributes || closeBracketToken != this.CloseBracketToken) { var newNode = SyntaxFactory.AttributeList(openBracketToken, target, attributes, closeBracketToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public AttributeListSyntax WithOpenBracketToken(SyntaxToken openBracketToken) => Update(openBracketToken, this.Target, this.Attributes, this.CloseBracketToken); public AttributeListSyntax WithTarget(AttributeTargetSpecifierSyntax? target) => Update(this.OpenBracketToken, target, this.Attributes, this.CloseBracketToken); public AttributeListSyntax WithAttributes(SeparatedSyntaxList<AttributeSyntax> attributes) => Update(this.OpenBracketToken, this.Target, attributes, this.CloseBracketToken); public AttributeListSyntax WithCloseBracketToken(SyntaxToken closeBracketToken) => Update(this.OpenBracketToken, this.Target, this.Attributes, closeBracketToken); public AttributeListSyntax AddAttributes(params AttributeSyntax[] items) => WithAttributes(this.Attributes.AddRange(items)); } /// <summary>Class representing what language construct an attribute targets.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.AttributeTargetSpecifier"/></description></item> /// </list> /// </remarks> public sealed partial class AttributeTargetSpecifierSyntax : CSharpSyntaxNode { internal AttributeTargetSpecifierSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.AttributeTargetSpecifierSyntax)this.Green).identifier, Position, 0); /// <summary>Gets the colon token.</summary> public SyntaxToken ColonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.AttributeTargetSpecifierSyntax)this.Green).colonToken, GetChildPosition(1), GetChildIndex(1)); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitAttributeTargetSpecifier(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitAttributeTargetSpecifier(this); public AttributeTargetSpecifierSyntax Update(SyntaxToken identifier, SyntaxToken colonToken) { if (identifier != this.Identifier || colonToken != this.ColonToken) { var newNode = SyntaxFactory.AttributeTargetSpecifier(identifier, colonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public AttributeTargetSpecifierSyntax WithIdentifier(SyntaxToken identifier) => Update(identifier, this.ColonToken); public AttributeTargetSpecifierSyntax WithColonToken(SyntaxToken colonToken) => Update(this.Identifier, colonToken); } /// <summary>Attribute syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.Attribute"/></description></item> /// </list> /// </remarks> public sealed partial class AttributeSyntax : CSharpSyntaxNode { private NameSyntax? name; private AttributeArgumentListSyntax? argumentList; internal AttributeSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the name.</summary> public NameSyntax Name => GetRedAtZero(ref this.name)!; public AttributeArgumentListSyntax? ArgumentList => GetRed(ref this.argumentList, 1); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.name)!, 1 => GetRed(ref this.argumentList, 1), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.name, 1 => this.argumentList, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitAttribute(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitAttribute(this); public AttributeSyntax Update(NameSyntax name, AttributeArgumentListSyntax? argumentList) { if (name != this.Name || argumentList != this.ArgumentList) { var newNode = SyntaxFactory.Attribute(name, argumentList); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public AttributeSyntax WithName(NameSyntax name) => Update(name, this.ArgumentList); public AttributeSyntax WithArgumentList(AttributeArgumentListSyntax? argumentList) => Update(this.Name, argumentList); public AttributeSyntax AddArgumentListArguments(params AttributeArgumentSyntax[] items) { var argumentList = this.ArgumentList ?? SyntaxFactory.AttributeArgumentList(); return WithArgumentList(argumentList.WithArguments(argumentList.Arguments.AddRange(items))); } } /// <summary>Attribute argument list syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.AttributeArgumentList"/></description></item> /// </list> /// </remarks> public sealed partial class AttributeArgumentListSyntax : CSharpSyntaxNode { private SyntaxNode? arguments; internal AttributeArgumentListSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the open paren token.</summary> public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.AttributeArgumentListSyntax)this.Green).openParenToken, Position, 0); /// <summary>Gets the arguments syntax list.</summary> public SeparatedSyntaxList<AttributeArgumentSyntax> Arguments { get { var red = GetRed(ref this.arguments, 1); return red != null ? new SeparatedSyntaxList<AttributeArgumentSyntax>(red, GetChildIndex(1)) : default; } } /// <summary>Gets the close paren token.</summary> public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.AttributeArgumentListSyntax)this.Green).closeParenToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.arguments, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.arguments : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitAttributeArgumentList(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitAttributeArgumentList(this); public AttributeArgumentListSyntax Update(SyntaxToken openParenToken, SeparatedSyntaxList<AttributeArgumentSyntax> arguments, SyntaxToken closeParenToken) { if (openParenToken != this.OpenParenToken || arguments != this.Arguments || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.AttributeArgumentList(openParenToken, arguments, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public AttributeArgumentListSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(openParenToken, this.Arguments, this.CloseParenToken); public AttributeArgumentListSyntax WithArguments(SeparatedSyntaxList<AttributeArgumentSyntax> arguments) => Update(this.OpenParenToken, arguments, this.CloseParenToken); public AttributeArgumentListSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.OpenParenToken, this.Arguments, closeParenToken); public AttributeArgumentListSyntax AddArguments(params AttributeArgumentSyntax[] items) => WithArguments(this.Arguments.AddRange(items)); } /// <summary>Attribute argument syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.AttributeArgument"/></description></item> /// </list> /// </remarks> public sealed partial class AttributeArgumentSyntax : CSharpSyntaxNode { private NameEqualsSyntax? nameEquals; private NameColonSyntax? nameColon; private ExpressionSyntax? expression; internal AttributeArgumentSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public NameEqualsSyntax? NameEquals => GetRedAtZero(ref this.nameEquals); public NameColonSyntax? NameColon => GetRed(ref this.nameColon, 1); /// <summary>Gets the expression.</summary> public ExpressionSyntax Expression => GetRed(ref this.expression, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.nameEquals), 1 => GetRed(ref this.nameColon, 1), 2 => GetRed(ref this.expression, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.nameEquals, 1 => this.nameColon, 2 => this.expression, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitAttributeArgument(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitAttributeArgument(this); public AttributeArgumentSyntax Update(NameEqualsSyntax? nameEquals, NameColonSyntax? nameColon, ExpressionSyntax expression) { if (nameEquals != this.NameEquals || nameColon != this.NameColon || expression != this.Expression) { var newNode = SyntaxFactory.AttributeArgument(nameEquals, nameColon, expression); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public AttributeArgumentSyntax WithNameEquals(NameEqualsSyntax? nameEquals) => Update(nameEquals, this.NameColon, this.Expression); public AttributeArgumentSyntax WithNameColon(NameColonSyntax? nameColon) => Update(this.NameEquals, nameColon, this.Expression); public AttributeArgumentSyntax WithExpression(ExpressionSyntax expression) => Update(this.NameEquals, this.NameColon, expression); } /// <summary>Class representing an identifier name followed by an equals token.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.NameEquals"/></description></item> /// </list> /// </remarks> public sealed partial class NameEqualsSyntax : CSharpSyntaxNode { private IdentifierNameSyntax? name; internal NameEqualsSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the identifier name.</summary> public IdentifierNameSyntax Name => GetRedAtZero(ref this.name)!; public SyntaxToken EqualsToken => new SyntaxToken(this, ((Syntax.InternalSyntax.NameEqualsSyntax)this.Green).equalsToken, GetChildPosition(1), GetChildIndex(1)); internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.name)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.name : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitNameEquals(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitNameEquals(this); public NameEqualsSyntax Update(IdentifierNameSyntax name, SyntaxToken equalsToken) { if (name != this.Name || equalsToken != this.EqualsToken) { var newNode = SyntaxFactory.NameEquals(name, equalsToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public NameEqualsSyntax WithName(IdentifierNameSyntax name) => Update(name, this.EqualsToken); public NameEqualsSyntax WithEqualsToken(SyntaxToken equalsToken) => Update(this.Name, equalsToken); } /// <summary>Type parameter list syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.TypeParameterList"/></description></item> /// </list> /// </remarks> public sealed partial class TypeParameterListSyntax : CSharpSyntaxNode { private SyntaxNode? parameters; internal TypeParameterListSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the &lt; token.</summary> public SyntaxToken LessThanToken => new SyntaxToken(this, ((Syntax.InternalSyntax.TypeParameterListSyntax)this.Green).lessThanToken, Position, 0); /// <summary>Gets the parameter list.</summary> public SeparatedSyntaxList<TypeParameterSyntax> Parameters { get { var red = GetRed(ref this.parameters, 1); return red != null ? new SeparatedSyntaxList<TypeParameterSyntax>(red, GetChildIndex(1)) : default; } } /// <summary>Gets the &gt; token.</summary> public SyntaxToken GreaterThanToken => new SyntaxToken(this, ((Syntax.InternalSyntax.TypeParameterListSyntax)this.Green).greaterThanToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.parameters, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.parameters : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitTypeParameterList(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitTypeParameterList(this); public TypeParameterListSyntax Update(SyntaxToken lessThanToken, SeparatedSyntaxList<TypeParameterSyntax> parameters, SyntaxToken greaterThanToken) { if (lessThanToken != this.LessThanToken || parameters != this.Parameters || greaterThanToken != this.GreaterThanToken) { var newNode = SyntaxFactory.TypeParameterList(lessThanToken, parameters, greaterThanToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public TypeParameterListSyntax WithLessThanToken(SyntaxToken lessThanToken) => Update(lessThanToken, this.Parameters, this.GreaterThanToken); public TypeParameterListSyntax WithParameters(SeparatedSyntaxList<TypeParameterSyntax> parameters) => Update(this.LessThanToken, parameters, this.GreaterThanToken); public TypeParameterListSyntax WithGreaterThanToken(SyntaxToken greaterThanToken) => Update(this.LessThanToken, this.Parameters, greaterThanToken); public TypeParameterListSyntax AddParameters(params TypeParameterSyntax[] items) => WithParameters(this.Parameters.AddRange(items)); } /// <summary>Type parameter syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.TypeParameter"/></description></item> /// </list> /// </remarks> public sealed partial class TypeParameterSyntax : CSharpSyntaxNode { private SyntaxNode? attributeLists; internal TypeParameterSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the attribute declaration list.</summary> public SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public SyntaxToken VarianceKeyword { get { var slot = ((Syntax.InternalSyntax.TypeParameterSyntax)this.Green).varianceKeyword; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.TypeParameterSyntax)this.Green).identifier, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.attributeLists)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.attributeLists : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitTypeParameter(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitTypeParameter(this); public TypeParameterSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken varianceKeyword, SyntaxToken identifier) { if (attributeLists != this.AttributeLists || varianceKeyword != this.VarianceKeyword || identifier != this.Identifier) { var newNode = SyntaxFactory.TypeParameter(attributeLists, varianceKeyword, identifier); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public TypeParameterSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.VarianceKeyword, this.Identifier); public TypeParameterSyntax WithVarianceKeyword(SyntaxToken varianceKeyword) => Update(this.AttributeLists, varianceKeyword, this.Identifier); public TypeParameterSyntax WithIdentifier(SyntaxToken identifier) => Update(this.AttributeLists, this.VarianceKeyword, identifier); public TypeParameterSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); } /// <summary>Base class for type declaration syntax.</summary> public abstract partial class BaseTypeDeclarationSyntax : MemberDeclarationSyntax { internal BaseTypeDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the identifier.</summary> public abstract SyntaxToken Identifier { get; } public BaseTypeDeclarationSyntax WithIdentifier(SyntaxToken identifier) => WithIdentifierCore(identifier); internal abstract BaseTypeDeclarationSyntax WithIdentifierCore(SyntaxToken identifier); /// <summary>Gets the base type list.</summary> public abstract BaseListSyntax? BaseList { get; } public BaseTypeDeclarationSyntax WithBaseList(BaseListSyntax? baseList) => WithBaseListCore(baseList); internal abstract BaseTypeDeclarationSyntax WithBaseListCore(BaseListSyntax? baseList); public BaseTypeDeclarationSyntax AddBaseListTypes(params BaseTypeSyntax[] items) => AddBaseListTypesCore(items); internal abstract BaseTypeDeclarationSyntax AddBaseListTypesCore(params BaseTypeSyntax[] items); /// <summary>Gets the open brace token.</summary> public abstract SyntaxToken OpenBraceToken { get; } public BaseTypeDeclarationSyntax WithOpenBraceToken(SyntaxToken openBraceToken) => WithOpenBraceTokenCore(openBraceToken); internal abstract BaseTypeDeclarationSyntax WithOpenBraceTokenCore(SyntaxToken openBraceToken); /// <summary>Gets the close brace token.</summary> public abstract SyntaxToken CloseBraceToken { get; } public BaseTypeDeclarationSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) => WithCloseBraceTokenCore(closeBraceToken); internal abstract BaseTypeDeclarationSyntax WithCloseBraceTokenCore(SyntaxToken closeBraceToken); /// <summary>Gets the optional semicolon token.</summary> public abstract SyntaxToken SemicolonToken { get; } public BaseTypeDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => WithSemicolonTokenCore(semicolonToken); internal abstract BaseTypeDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken); public new BaseTypeDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => (BaseTypeDeclarationSyntax)WithAttributeListsCore(attributeLists); public new BaseTypeDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => (BaseTypeDeclarationSyntax)WithModifiersCore(modifiers); public new BaseTypeDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => (BaseTypeDeclarationSyntax)AddAttributeListsCore(items); public new BaseTypeDeclarationSyntax AddModifiers(params SyntaxToken[] items) => (BaseTypeDeclarationSyntax)AddModifiersCore(items); } /// <summary>Base class for type declaration syntax (class, struct, interface, record).</summary> public abstract partial class TypeDeclarationSyntax : BaseTypeDeclarationSyntax { internal TypeDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the type keyword token ("class", "struct", "interface", "record").</summary> public abstract SyntaxToken Keyword { get; } public TypeDeclarationSyntax WithKeyword(SyntaxToken keyword) => WithKeywordCore(keyword); internal abstract TypeDeclarationSyntax WithKeywordCore(SyntaxToken keyword); public abstract TypeParameterListSyntax? TypeParameterList { get; } public TypeDeclarationSyntax WithTypeParameterList(TypeParameterListSyntax? typeParameterList) => WithTypeParameterListCore(typeParameterList); internal abstract TypeDeclarationSyntax WithTypeParameterListCore(TypeParameterListSyntax? typeParameterList); public TypeDeclarationSyntax AddTypeParameterListParameters(params TypeParameterSyntax[] items) => AddTypeParameterListParametersCore(items); internal abstract TypeDeclarationSyntax AddTypeParameterListParametersCore(params TypeParameterSyntax[] items); /// <summary>Gets the type constraint list.</summary> public abstract SyntaxList<TypeParameterConstraintClauseSyntax> ConstraintClauses { get; } public TypeDeclarationSyntax WithConstraintClauses(SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses) => WithConstraintClausesCore(constraintClauses); internal abstract TypeDeclarationSyntax WithConstraintClausesCore(SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses); public TypeDeclarationSyntax AddConstraintClauses(params TypeParameterConstraintClauseSyntax[] items) => AddConstraintClausesCore(items); internal abstract TypeDeclarationSyntax AddConstraintClausesCore(params TypeParameterConstraintClauseSyntax[] items); /// <summary>Gets the member declarations.</summary> public abstract SyntaxList<MemberDeclarationSyntax> Members { get; } public TypeDeclarationSyntax WithMembers(SyntaxList<MemberDeclarationSyntax> members) => WithMembersCore(members); internal abstract TypeDeclarationSyntax WithMembersCore(SyntaxList<MemberDeclarationSyntax> members); public TypeDeclarationSyntax AddMembers(params MemberDeclarationSyntax[] items) => AddMembersCore(items); internal abstract TypeDeclarationSyntax AddMembersCore(params MemberDeclarationSyntax[] items); public new TypeDeclarationSyntax WithIdentifier(SyntaxToken identifier) => (TypeDeclarationSyntax)WithIdentifierCore(identifier); public new TypeDeclarationSyntax WithBaseList(BaseListSyntax? baseList) => (TypeDeclarationSyntax)WithBaseListCore(baseList); public new TypeDeclarationSyntax WithOpenBraceToken(SyntaxToken openBraceToken) => (TypeDeclarationSyntax)WithOpenBraceTokenCore(openBraceToken); public new TypeDeclarationSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) => (TypeDeclarationSyntax)WithCloseBraceTokenCore(closeBraceToken); public new TypeDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => (TypeDeclarationSyntax)WithSemicolonTokenCore(semicolonToken); public new BaseTypeDeclarationSyntax AddBaseListTypes(params BaseTypeSyntax[] items) => AddBaseListTypesCore(items); } /// <summary>Class type declaration syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ClassDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class ClassDeclarationSyntax : TypeDeclarationSyntax { private SyntaxNode? attributeLists; private TypeParameterListSyntax? typeParameterList; private BaseListSyntax? baseList; private SyntaxNode? constraintClauses; private SyntaxNode? members; internal ClassDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } /// <summary>Gets the class keyword token.</summary> public override SyntaxToken Keyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ClassDeclarationSyntax)this.Green).keyword, GetChildPosition(2), GetChildIndex(2)); public override SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.ClassDeclarationSyntax)this.Green).identifier, GetChildPosition(3), GetChildIndex(3)); public override TypeParameterListSyntax? TypeParameterList => GetRed(ref this.typeParameterList, 4); public override BaseListSyntax? BaseList => GetRed(ref this.baseList, 5); public override SyntaxList<TypeParameterConstraintClauseSyntax> ConstraintClauses => new SyntaxList<TypeParameterConstraintClauseSyntax>(GetRed(ref this.constraintClauses, 6)); public override SyntaxToken OpenBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ClassDeclarationSyntax)this.Green).openBraceToken, GetChildPosition(7), GetChildIndex(7)); public override SyntaxList<MemberDeclarationSyntax> Members => new SyntaxList<MemberDeclarationSyntax>(GetRed(ref this.members, 8)); public override SyntaxToken CloseBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ClassDeclarationSyntax)this.Green).closeBraceToken, GetChildPosition(9), GetChildIndex(9)); public override SyntaxToken SemicolonToken { get { var slot = ((Syntax.InternalSyntax.ClassDeclarationSyntax)this.Green).semicolonToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(10), GetChildIndex(10)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 4 => GetRed(ref this.typeParameterList, 4), 5 => GetRed(ref this.baseList, 5), 6 => GetRed(ref this.constraintClauses, 6)!, 8 => GetRed(ref this.members, 8)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 4 => this.typeParameterList, 5 => this.baseList, 6 => this.constraintClauses, 8 => this.members, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitClassDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitClassDeclaration(this); public ClassDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, BaseListSyntax? baseList, SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses, SyntaxToken openBraceToken, SyntaxList<MemberDeclarationSyntax> members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || keyword != this.Keyword || identifier != this.Identifier || typeParameterList != this.TypeParameterList || baseList != this.BaseList || constraintClauses != this.ConstraintClauses || openBraceToken != this.OpenBraceToken || members != this.Members || closeBraceToken != this.CloseBraceToken || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.ClassDeclaration(attributeLists, modifiers, keyword, identifier, typeParameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new ClassDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new ClassDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override TypeDeclarationSyntax WithKeywordCore(SyntaxToken keyword) => WithKeyword(keyword); public new ClassDeclarationSyntax WithKeyword(SyntaxToken keyword) => Update(this.AttributeLists, this.Modifiers, keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithIdentifierCore(SyntaxToken identifier) => WithIdentifier(identifier); public new ClassDeclarationSyntax WithIdentifier(SyntaxToken identifier) => Update(this.AttributeLists, this.Modifiers, this.Keyword, identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override TypeDeclarationSyntax WithTypeParameterListCore(TypeParameterListSyntax? typeParameterList) => WithTypeParameterList(typeParameterList); public new ClassDeclarationSyntax WithTypeParameterList(TypeParameterListSyntax? typeParameterList) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, typeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithBaseListCore(BaseListSyntax? baseList) => WithBaseList(baseList); public new ClassDeclarationSyntax WithBaseList(BaseListSyntax? baseList) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, baseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override TypeDeclarationSyntax WithConstraintClausesCore(SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses) => WithConstraintClauses(constraintClauses); public new ClassDeclarationSyntax WithConstraintClauses(SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, constraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithOpenBraceTokenCore(SyntaxToken openBraceToken) => WithOpenBraceToken(openBraceToken); public new ClassDeclarationSyntax WithOpenBraceToken(SyntaxToken openBraceToken) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, openBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override TypeDeclarationSyntax WithMembersCore(SyntaxList<MemberDeclarationSyntax> members) => WithMembers(members); public new ClassDeclarationSyntax WithMembers(SyntaxList<MemberDeclarationSyntax> members) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithCloseBraceTokenCore(SyntaxToken closeBraceToken) => WithCloseBraceToken(closeBraceToken); public new ClassDeclarationSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, closeBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken) => WithSemicolonToken(semicolonToken); public new ClassDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, semicolonToken); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new ClassDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new ClassDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); internal override TypeDeclarationSyntax AddTypeParameterListParametersCore(params TypeParameterSyntax[] items) => AddTypeParameterListParameters(items); public new ClassDeclarationSyntax AddTypeParameterListParameters(params TypeParameterSyntax[] items) { var typeParameterList = this.TypeParameterList ?? SyntaxFactory.TypeParameterList(); return WithTypeParameterList(typeParameterList.WithParameters(typeParameterList.Parameters.AddRange(items))); } internal override BaseTypeDeclarationSyntax AddBaseListTypesCore(params BaseTypeSyntax[] items) => AddBaseListTypes(items); public new ClassDeclarationSyntax AddBaseListTypes(params BaseTypeSyntax[] items) { var baseList = this.BaseList ?? SyntaxFactory.BaseList(); return WithBaseList(baseList.WithTypes(baseList.Types.AddRange(items))); } internal override TypeDeclarationSyntax AddConstraintClausesCore(params TypeParameterConstraintClauseSyntax[] items) => AddConstraintClauses(items); public new ClassDeclarationSyntax AddConstraintClauses(params TypeParameterConstraintClauseSyntax[] items) => WithConstraintClauses(this.ConstraintClauses.AddRange(items)); internal override TypeDeclarationSyntax AddMembersCore(params MemberDeclarationSyntax[] items) => AddMembers(items); public new ClassDeclarationSyntax AddMembers(params MemberDeclarationSyntax[] items) => WithMembers(this.Members.AddRange(items)); } /// <summary>Struct type declaration syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.StructDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class StructDeclarationSyntax : TypeDeclarationSyntax { private SyntaxNode? attributeLists; private TypeParameterListSyntax? typeParameterList; private BaseListSyntax? baseList; private SyntaxNode? constraintClauses; private SyntaxNode? members; internal StructDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } /// <summary>Gets the struct keyword token.</summary> public override SyntaxToken Keyword => new SyntaxToken(this, ((Syntax.InternalSyntax.StructDeclarationSyntax)this.Green).keyword, GetChildPosition(2), GetChildIndex(2)); public override SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.StructDeclarationSyntax)this.Green).identifier, GetChildPosition(3), GetChildIndex(3)); public override TypeParameterListSyntax? TypeParameterList => GetRed(ref this.typeParameterList, 4); public override BaseListSyntax? BaseList => GetRed(ref this.baseList, 5); public override SyntaxList<TypeParameterConstraintClauseSyntax> ConstraintClauses => new SyntaxList<TypeParameterConstraintClauseSyntax>(GetRed(ref this.constraintClauses, 6)); public override SyntaxToken OpenBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.StructDeclarationSyntax)this.Green).openBraceToken, GetChildPosition(7), GetChildIndex(7)); public override SyntaxList<MemberDeclarationSyntax> Members => new SyntaxList<MemberDeclarationSyntax>(GetRed(ref this.members, 8)); public override SyntaxToken CloseBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.StructDeclarationSyntax)this.Green).closeBraceToken, GetChildPosition(9), GetChildIndex(9)); public override SyntaxToken SemicolonToken { get { var slot = ((Syntax.InternalSyntax.StructDeclarationSyntax)this.Green).semicolonToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(10), GetChildIndex(10)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 4 => GetRed(ref this.typeParameterList, 4), 5 => GetRed(ref this.baseList, 5), 6 => GetRed(ref this.constraintClauses, 6)!, 8 => GetRed(ref this.members, 8)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 4 => this.typeParameterList, 5 => this.baseList, 6 => this.constraintClauses, 8 => this.members, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitStructDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitStructDeclaration(this); public StructDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, BaseListSyntax? baseList, SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses, SyntaxToken openBraceToken, SyntaxList<MemberDeclarationSyntax> members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || keyword != this.Keyword || identifier != this.Identifier || typeParameterList != this.TypeParameterList || baseList != this.BaseList || constraintClauses != this.ConstraintClauses || openBraceToken != this.OpenBraceToken || members != this.Members || closeBraceToken != this.CloseBraceToken || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.StructDeclaration(attributeLists, modifiers, keyword, identifier, typeParameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new StructDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new StructDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override TypeDeclarationSyntax WithKeywordCore(SyntaxToken keyword) => WithKeyword(keyword); public new StructDeclarationSyntax WithKeyword(SyntaxToken keyword) => Update(this.AttributeLists, this.Modifiers, keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithIdentifierCore(SyntaxToken identifier) => WithIdentifier(identifier); public new StructDeclarationSyntax WithIdentifier(SyntaxToken identifier) => Update(this.AttributeLists, this.Modifiers, this.Keyword, identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override TypeDeclarationSyntax WithTypeParameterListCore(TypeParameterListSyntax? typeParameterList) => WithTypeParameterList(typeParameterList); public new StructDeclarationSyntax WithTypeParameterList(TypeParameterListSyntax? typeParameterList) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, typeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithBaseListCore(BaseListSyntax? baseList) => WithBaseList(baseList); public new StructDeclarationSyntax WithBaseList(BaseListSyntax? baseList) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, baseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override TypeDeclarationSyntax WithConstraintClausesCore(SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses) => WithConstraintClauses(constraintClauses); public new StructDeclarationSyntax WithConstraintClauses(SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, constraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithOpenBraceTokenCore(SyntaxToken openBraceToken) => WithOpenBraceToken(openBraceToken); public new StructDeclarationSyntax WithOpenBraceToken(SyntaxToken openBraceToken) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, openBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override TypeDeclarationSyntax WithMembersCore(SyntaxList<MemberDeclarationSyntax> members) => WithMembers(members); public new StructDeclarationSyntax WithMembers(SyntaxList<MemberDeclarationSyntax> members) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithCloseBraceTokenCore(SyntaxToken closeBraceToken) => WithCloseBraceToken(closeBraceToken); public new StructDeclarationSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, closeBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken) => WithSemicolonToken(semicolonToken); public new StructDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, semicolonToken); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new StructDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new StructDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); internal override TypeDeclarationSyntax AddTypeParameterListParametersCore(params TypeParameterSyntax[] items) => AddTypeParameterListParameters(items); public new StructDeclarationSyntax AddTypeParameterListParameters(params TypeParameterSyntax[] items) { var typeParameterList = this.TypeParameterList ?? SyntaxFactory.TypeParameterList(); return WithTypeParameterList(typeParameterList.WithParameters(typeParameterList.Parameters.AddRange(items))); } internal override BaseTypeDeclarationSyntax AddBaseListTypesCore(params BaseTypeSyntax[] items) => AddBaseListTypes(items); public new StructDeclarationSyntax AddBaseListTypes(params BaseTypeSyntax[] items) { var baseList = this.BaseList ?? SyntaxFactory.BaseList(); return WithBaseList(baseList.WithTypes(baseList.Types.AddRange(items))); } internal override TypeDeclarationSyntax AddConstraintClausesCore(params TypeParameterConstraintClauseSyntax[] items) => AddConstraintClauses(items); public new StructDeclarationSyntax AddConstraintClauses(params TypeParameterConstraintClauseSyntax[] items) => WithConstraintClauses(this.ConstraintClauses.AddRange(items)); internal override TypeDeclarationSyntax AddMembersCore(params MemberDeclarationSyntax[] items) => AddMembers(items); public new StructDeclarationSyntax AddMembers(params MemberDeclarationSyntax[] items) => WithMembers(this.Members.AddRange(items)); } /// <summary>Interface type declaration syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.InterfaceDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class InterfaceDeclarationSyntax : TypeDeclarationSyntax { private SyntaxNode? attributeLists; private TypeParameterListSyntax? typeParameterList; private BaseListSyntax? baseList; private SyntaxNode? constraintClauses; private SyntaxNode? members; internal InterfaceDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } /// <summary>Gets the interface keyword token.</summary> public override SyntaxToken Keyword => new SyntaxToken(this, ((Syntax.InternalSyntax.InterfaceDeclarationSyntax)this.Green).keyword, GetChildPosition(2), GetChildIndex(2)); public override SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.InterfaceDeclarationSyntax)this.Green).identifier, GetChildPosition(3), GetChildIndex(3)); public override TypeParameterListSyntax? TypeParameterList => GetRed(ref this.typeParameterList, 4); public override BaseListSyntax? BaseList => GetRed(ref this.baseList, 5); public override SyntaxList<TypeParameterConstraintClauseSyntax> ConstraintClauses => new SyntaxList<TypeParameterConstraintClauseSyntax>(GetRed(ref this.constraintClauses, 6)); public override SyntaxToken OpenBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.InterfaceDeclarationSyntax)this.Green).openBraceToken, GetChildPosition(7), GetChildIndex(7)); public override SyntaxList<MemberDeclarationSyntax> Members => new SyntaxList<MemberDeclarationSyntax>(GetRed(ref this.members, 8)); public override SyntaxToken CloseBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.InterfaceDeclarationSyntax)this.Green).closeBraceToken, GetChildPosition(9), GetChildIndex(9)); public override SyntaxToken SemicolonToken { get { var slot = ((Syntax.InternalSyntax.InterfaceDeclarationSyntax)this.Green).semicolonToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(10), GetChildIndex(10)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 4 => GetRed(ref this.typeParameterList, 4), 5 => GetRed(ref this.baseList, 5), 6 => GetRed(ref this.constraintClauses, 6)!, 8 => GetRed(ref this.members, 8)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 4 => this.typeParameterList, 5 => this.baseList, 6 => this.constraintClauses, 8 => this.members, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitInterfaceDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitInterfaceDeclaration(this); public InterfaceDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, BaseListSyntax? baseList, SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses, SyntaxToken openBraceToken, SyntaxList<MemberDeclarationSyntax> members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || keyword != this.Keyword || identifier != this.Identifier || typeParameterList != this.TypeParameterList || baseList != this.BaseList || constraintClauses != this.ConstraintClauses || openBraceToken != this.OpenBraceToken || members != this.Members || closeBraceToken != this.CloseBraceToken || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.InterfaceDeclaration(attributeLists, modifiers, keyword, identifier, typeParameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new InterfaceDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new InterfaceDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override TypeDeclarationSyntax WithKeywordCore(SyntaxToken keyword) => WithKeyword(keyword); public new InterfaceDeclarationSyntax WithKeyword(SyntaxToken keyword) => Update(this.AttributeLists, this.Modifiers, keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithIdentifierCore(SyntaxToken identifier) => WithIdentifier(identifier); public new InterfaceDeclarationSyntax WithIdentifier(SyntaxToken identifier) => Update(this.AttributeLists, this.Modifiers, this.Keyword, identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override TypeDeclarationSyntax WithTypeParameterListCore(TypeParameterListSyntax? typeParameterList) => WithTypeParameterList(typeParameterList); public new InterfaceDeclarationSyntax WithTypeParameterList(TypeParameterListSyntax? typeParameterList) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, typeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithBaseListCore(BaseListSyntax? baseList) => WithBaseList(baseList); public new InterfaceDeclarationSyntax WithBaseList(BaseListSyntax? baseList) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, baseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override TypeDeclarationSyntax WithConstraintClausesCore(SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses) => WithConstraintClauses(constraintClauses); public new InterfaceDeclarationSyntax WithConstraintClauses(SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, constraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithOpenBraceTokenCore(SyntaxToken openBraceToken) => WithOpenBraceToken(openBraceToken); public new InterfaceDeclarationSyntax WithOpenBraceToken(SyntaxToken openBraceToken) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, openBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override TypeDeclarationSyntax WithMembersCore(SyntaxList<MemberDeclarationSyntax> members) => WithMembers(members); public new InterfaceDeclarationSyntax WithMembers(SyntaxList<MemberDeclarationSyntax> members) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithCloseBraceTokenCore(SyntaxToken closeBraceToken) => WithCloseBraceToken(closeBraceToken); public new InterfaceDeclarationSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, closeBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken) => WithSemicolonToken(semicolonToken); public new InterfaceDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Identifier, this.TypeParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, semicolonToken); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new InterfaceDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new InterfaceDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); internal override TypeDeclarationSyntax AddTypeParameterListParametersCore(params TypeParameterSyntax[] items) => AddTypeParameterListParameters(items); public new InterfaceDeclarationSyntax AddTypeParameterListParameters(params TypeParameterSyntax[] items) { var typeParameterList = this.TypeParameterList ?? SyntaxFactory.TypeParameterList(); return WithTypeParameterList(typeParameterList.WithParameters(typeParameterList.Parameters.AddRange(items))); } internal override BaseTypeDeclarationSyntax AddBaseListTypesCore(params BaseTypeSyntax[] items) => AddBaseListTypes(items); public new InterfaceDeclarationSyntax AddBaseListTypes(params BaseTypeSyntax[] items) { var baseList = this.BaseList ?? SyntaxFactory.BaseList(); return WithBaseList(baseList.WithTypes(baseList.Types.AddRange(items))); } internal override TypeDeclarationSyntax AddConstraintClausesCore(params TypeParameterConstraintClauseSyntax[] items) => AddConstraintClauses(items); public new InterfaceDeclarationSyntax AddConstraintClauses(params TypeParameterConstraintClauseSyntax[] items) => WithConstraintClauses(this.ConstraintClauses.AddRange(items)); internal override TypeDeclarationSyntax AddMembersCore(params MemberDeclarationSyntax[] items) => AddMembers(items); public new InterfaceDeclarationSyntax AddMembers(params MemberDeclarationSyntax[] items) => WithMembers(this.Members.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.RecordDeclaration"/></description></item> /// <item><description><see cref="SyntaxKind.RecordStructDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class RecordDeclarationSyntax : TypeDeclarationSyntax { private SyntaxNode? attributeLists; private TypeParameterListSyntax? typeParameterList; private ParameterListSyntax? parameterList; private BaseListSyntax? baseList; private SyntaxNode? constraintClauses; private SyntaxNode? members; internal RecordDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public override SyntaxToken Keyword => new SyntaxToken(this, ((Syntax.InternalSyntax.RecordDeclarationSyntax)this.Green).keyword, GetChildPosition(2), GetChildIndex(2)); public SyntaxToken ClassOrStructKeyword { get { var slot = ((Syntax.InternalSyntax.RecordDeclarationSyntax)this.Green).classOrStructKeyword; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(3), GetChildIndex(3)) : default; } } public override SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.RecordDeclarationSyntax)this.Green).identifier, GetChildPosition(4), GetChildIndex(4)); public override TypeParameterListSyntax? TypeParameterList => GetRed(ref this.typeParameterList, 5); public ParameterListSyntax? ParameterList => GetRed(ref this.parameterList, 6); public override BaseListSyntax? BaseList => GetRed(ref this.baseList, 7); public override SyntaxList<TypeParameterConstraintClauseSyntax> ConstraintClauses => new SyntaxList<TypeParameterConstraintClauseSyntax>(GetRed(ref this.constraintClauses, 8)); public override SyntaxToken OpenBraceToken { get { var slot = ((Syntax.InternalSyntax.RecordDeclarationSyntax)this.Green).openBraceToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(9), GetChildIndex(9)) : default; } } public override SyntaxList<MemberDeclarationSyntax> Members => new SyntaxList<MemberDeclarationSyntax>(GetRed(ref this.members, 10)); public override SyntaxToken CloseBraceToken { get { var slot = ((Syntax.InternalSyntax.RecordDeclarationSyntax)this.Green).closeBraceToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(11), GetChildIndex(11)) : default; } } public override SyntaxToken SemicolonToken { get { var slot = ((Syntax.InternalSyntax.RecordDeclarationSyntax)this.Green).semicolonToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(12), GetChildIndex(12)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 5 => GetRed(ref this.typeParameterList, 5), 6 => GetRed(ref this.parameterList, 6), 7 => GetRed(ref this.baseList, 7), 8 => GetRed(ref this.constraintClauses, 8)!, 10 => GetRed(ref this.members, 10)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 5 => this.typeParameterList, 6 => this.parameterList, 7 => this.baseList, 8 => this.constraintClauses, 10 => this.members, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitRecordDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitRecordDeclaration(this); public RecordDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, SyntaxToken classOrStructKeyword, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax? parameterList, BaseListSyntax? baseList, SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses, SyntaxToken openBraceToken, SyntaxList<MemberDeclarationSyntax> members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || keyword != this.Keyword || classOrStructKeyword != this.ClassOrStructKeyword || identifier != this.Identifier || typeParameterList != this.TypeParameterList || parameterList != this.ParameterList || baseList != this.BaseList || constraintClauses != this.ConstraintClauses || openBraceToken != this.OpenBraceToken || members != this.Members || closeBraceToken != this.CloseBraceToken || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.RecordDeclaration(this.Kind(), attributeLists, modifiers, keyword, classOrStructKeyword, identifier, typeParameterList, parameterList, baseList, constraintClauses, openBraceToken, members, closeBraceToken, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new RecordDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.Keyword, this.ClassOrStructKeyword, this.Identifier, this.TypeParameterList, this.ParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new RecordDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.Keyword, this.ClassOrStructKeyword, this.Identifier, this.TypeParameterList, this.ParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override TypeDeclarationSyntax WithKeywordCore(SyntaxToken keyword) => WithKeyword(keyword); public new RecordDeclarationSyntax WithKeyword(SyntaxToken keyword) => Update(this.AttributeLists, this.Modifiers, keyword, this.ClassOrStructKeyword, this.Identifier, this.TypeParameterList, this.ParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); public RecordDeclarationSyntax WithClassOrStructKeyword(SyntaxToken classOrStructKeyword) => Update(this.AttributeLists, this.Modifiers, this.Keyword, classOrStructKeyword, this.Identifier, this.TypeParameterList, this.ParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithIdentifierCore(SyntaxToken identifier) => WithIdentifier(identifier); public new RecordDeclarationSyntax WithIdentifier(SyntaxToken identifier) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.ClassOrStructKeyword, identifier, this.TypeParameterList, this.ParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override TypeDeclarationSyntax WithTypeParameterListCore(TypeParameterListSyntax? typeParameterList) => WithTypeParameterList(typeParameterList); public new RecordDeclarationSyntax WithTypeParameterList(TypeParameterListSyntax? typeParameterList) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.ClassOrStructKeyword, this.Identifier, typeParameterList, this.ParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); public RecordDeclarationSyntax WithParameterList(ParameterListSyntax? parameterList) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.ClassOrStructKeyword, this.Identifier, this.TypeParameterList, parameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithBaseListCore(BaseListSyntax? baseList) => WithBaseList(baseList); public new RecordDeclarationSyntax WithBaseList(BaseListSyntax? baseList) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.ClassOrStructKeyword, this.Identifier, this.TypeParameterList, this.ParameterList, baseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override TypeDeclarationSyntax WithConstraintClausesCore(SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses) => WithConstraintClauses(constraintClauses); public new RecordDeclarationSyntax WithConstraintClauses(SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.ClassOrStructKeyword, this.Identifier, this.TypeParameterList, this.ParameterList, this.BaseList, constraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithOpenBraceTokenCore(SyntaxToken openBraceToken) => WithOpenBraceToken(openBraceToken); public new RecordDeclarationSyntax WithOpenBraceToken(SyntaxToken openBraceToken) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.ClassOrStructKeyword, this.Identifier, this.TypeParameterList, this.ParameterList, this.BaseList, this.ConstraintClauses, openBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override TypeDeclarationSyntax WithMembersCore(SyntaxList<MemberDeclarationSyntax> members) => WithMembers(members); public new RecordDeclarationSyntax WithMembers(SyntaxList<MemberDeclarationSyntax> members) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.ClassOrStructKeyword, this.Identifier, this.TypeParameterList, this.ParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithCloseBraceTokenCore(SyntaxToken closeBraceToken) => WithCloseBraceToken(closeBraceToken); public new RecordDeclarationSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.ClassOrStructKeyword, this.Identifier, this.TypeParameterList, this.ParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, closeBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken) => WithSemicolonToken(semicolonToken); public new RecordDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.ClassOrStructKeyword, this.Identifier, this.TypeParameterList, this.ParameterList, this.BaseList, this.ConstraintClauses, this.OpenBraceToken, this.Members, this.CloseBraceToken, semicolonToken); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new RecordDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new RecordDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); internal override TypeDeclarationSyntax AddTypeParameterListParametersCore(params TypeParameterSyntax[] items) => AddTypeParameterListParameters(items); public new RecordDeclarationSyntax AddTypeParameterListParameters(params TypeParameterSyntax[] items) { var typeParameterList = this.TypeParameterList ?? SyntaxFactory.TypeParameterList(); return WithTypeParameterList(typeParameterList.WithParameters(typeParameterList.Parameters.AddRange(items))); } public RecordDeclarationSyntax AddParameterListParameters(params ParameterSyntax[] items) { var parameterList = this.ParameterList ?? SyntaxFactory.ParameterList(); return WithParameterList(parameterList.WithParameters(parameterList.Parameters.AddRange(items))); } internal override BaseTypeDeclarationSyntax AddBaseListTypesCore(params BaseTypeSyntax[] items) => AddBaseListTypes(items); public new RecordDeclarationSyntax AddBaseListTypes(params BaseTypeSyntax[] items) { var baseList = this.BaseList ?? SyntaxFactory.BaseList(); return WithBaseList(baseList.WithTypes(baseList.Types.AddRange(items))); } internal override TypeDeclarationSyntax AddConstraintClausesCore(params TypeParameterConstraintClauseSyntax[] items) => AddConstraintClauses(items); public new RecordDeclarationSyntax AddConstraintClauses(params TypeParameterConstraintClauseSyntax[] items) => WithConstraintClauses(this.ConstraintClauses.AddRange(items)); internal override TypeDeclarationSyntax AddMembersCore(params MemberDeclarationSyntax[] items) => AddMembers(items); public new RecordDeclarationSyntax AddMembers(params MemberDeclarationSyntax[] items) => WithMembers(this.Members.AddRange(items)); } /// <summary>Enum type declaration syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.EnumDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class EnumDeclarationSyntax : BaseTypeDeclarationSyntax { private SyntaxNode? attributeLists; private BaseListSyntax? baseList; private SyntaxNode? members; internal EnumDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } /// <summary>Gets the enum keyword token.</summary> public SyntaxToken EnumKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.EnumDeclarationSyntax)this.Green).enumKeyword, GetChildPosition(2), GetChildIndex(2)); public override SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.EnumDeclarationSyntax)this.Green).identifier, GetChildPosition(3), GetChildIndex(3)); public override BaseListSyntax? BaseList => GetRed(ref this.baseList, 4); public override SyntaxToken OpenBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.EnumDeclarationSyntax)this.Green).openBraceToken, GetChildPosition(5), GetChildIndex(5)); /// <summary>Gets the members declaration list.</summary> public SeparatedSyntaxList<EnumMemberDeclarationSyntax> Members { get { var red = GetRed(ref this.members, 6); return red != null ? new SeparatedSyntaxList<EnumMemberDeclarationSyntax>(red, GetChildIndex(6)) : default; } } public override SyntaxToken CloseBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.EnumDeclarationSyntax)this.Green).closeBraceToken, GetChildPosition(7), GetChildIndex(7)); /// <summary>Gets the optional semicolon token.</summary> public override SyntaxToken SemicolonToken { get { var slot = ((Syntax.InternalSyntax.EnumDeclarationSyntax)this.Green).semicolonToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(8), GetChildIndex(8)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 4 => GetRed(ref this.baseList, 4), 6 => GetRed(ref this.members, 6)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 4 => this.baseList, 6 => this.members, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitEnumDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitEnumDeclaration(this); public EnumDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken enumKeyword, SyntaxToken identifier, BaseListSyntax? baseList, SyntaxToken openBraceToken, SeparatedSyntaxList<EnumMemberDeclarationSyntax> members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || enumKeyword != this.EnumKeyword || identifier != this.Identifier || baseList != this.BaseList || openBraceToken != this.OpenBraceToken || members != this.Members || closeBraceToken != this.CloseBraceToken || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.EnumDeclaration(attributeLists, modifiers, enumKeyword, identifier, baseList, openBraceToken, members, closeBraceToken, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new EnumDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.EnumKeyword, this.Identifier, this.BaseList, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new EnumDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.EnumKeyword, this.Identifier, this.BaseList, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); public EnumDeclarationSyntax WithEnumKeyword(SyntaxToken enumKeyword) => Update(this.AttributeLists, this.Modifiers, enumKeyword, this.Identifier, this.BaseList, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithIdentifierCore(SyntaxToken identifier) => WithIdentifier(identifier); public new EnumDeclarationSyntax WithIdentifier(SyntaxToken identifier) => Update(this.AttributeLists, this.Modifiers, this.EnumKeyword, identifier, this.BaseList, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithBaseListCore(BaseListSyntax? baseList) => WithBaseList(baseList); public new EnumDeclarationSyntax WithBaseList(BaseListSyntax? baseList) => Update(this.AttributeLists, this.Modifiers, this.EnumKeyword, this.Identifier, baseList, this.OpenBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithOpenBraceTokenCore(SyntaxToken openBraceToken) => WithOpenBraceToken(openBraceToken); public new EnumDeclarationSyntax WithOpenBraceToken(SyntaxToken openBraceToken) => Update(this.AttributeLists, this.Modifiers, this.EnumKeyword, this.Identifier, this.BaseList, openBraceToken, this.Members, this.CloseBraceToken, this.SemicolonToken); public EnumDeclarationSyntax WithMembers(SeparatedSyntaxList<EnumMemberDeclarationSyntax> members) => Update(this.AttributeLists, this.Modifiers, this.EnumKeyword, this.Identifier, this.BaseList, this.OpenBraceToken, members, this.CloseBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithCloseBraceTokenCore(SyntaxToken closeBraceToken) => WithCloseBraceToken(closeBraceToken); public new EnumDeclarationSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) => Update(this.AttributeLists, this.Modifiers, this.EnumKeyword, this.Identifier, this.BaseList, this.OpenBraceToken, this.Members, closeBraceToken, this.SemicolonToken); internal override BaseTypeDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken) => WithSemicolonToken(semicolonToken); public new EnumDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.EnumKeyword, this.Identifier, this.BaseList, this.OpenBraceToken, this.Members, this.CloseBraceToken, semicolonToken); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new EnumDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new EnumDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); internal override BaseTypeDeclarationSyntax AddBaseListTypesCore(params BaseTypeSyntax[] items) => AddBaseListTypes(items); public new EnumDeclarationSyntax AddBaseListTypes(params BaseTypeSyntax[] items) { var baseList = this.BaseList ?? SyntaxFactory.BaseList(); return WithBaseList(baseList.WithTypes(baseList.Types.AddRange(items))); } public EnumDeclarationSyntax AddMembers(params EnumMemberDeclarationSyntax[] items) => WithMembers(this.Members.AddRange(items)); } /// <summary>Delegate declaration syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.DelegateDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class DelegateDeclarationSyntax : MemberDeclarationSyntax { private SyntaxNode? attributeLists; private TypeSyntax? returnType; private TypeParameterListSyntax? typeParameterList; private ParameterListSyntax? parameterList; private SyntaxNode? constraintClauses; internal DelegateDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } /// <summary>Gets the "delegate" keyword.</summary> public SyntaxToken DelegateKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.DelegateDeclarationSyntax)this.Green).delegateKeyword, GetChildPosition(2), GetChildIndex(2)); /// <summary>Gets the return type.</summary> public TypeSyntax ReturnType => GetRed(ref this.returnType, 3)!; /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.DelegateDeclarationSyntax)this.Green).identifier, GetChildPosition(4), GetChildIndex(4)); public TypeParameterListSyntax? TypeParameterList => GetRed(ref this.typeParameterList, 5); /// <summary>Gets the parameter list.</summary> public ParameterListSyntax ParameterList => GetRed(ref this.parameterList, 6)!; /// <summary>Gets the constraint clause list.</summary> public SyntaxList<TypeParameterConstraintClauseSyntax> ConstraintClauses => new SyntaxList<TypeParameterConstraintClauseSyntax>(GetRed(ref this.constraintClauses, 7)); /// <summary>Gets the semicolon token.</summary> public SyntaxToken SemicolonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.DelegateDeclarationSyntax)this.Green).semicolonToken, GetChildPosition(8), GetChildIndex(8)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 3 => GetRed(ref this.returnType, 3)!, 5 => GetRed(ref this.typeParameterList, 5), 6 => GetRed(ref this.parameterList, 6)!, 7 => GetRed(ref this.constraintClauses, 7)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 3 => this.returnType, 5 => this.typeParameterList, 6 => this.parameterList, 7 => this.constraintClauses, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitDelegateDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitDelegateDeclaration(this); public DelegateDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken delegateKeyword, TypeSyntax returnType, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax parameterList, SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || delegateKeyword != this.DelegateKeyword || returnType != this.ReturnType || identifier != this.Identifier || typeParameterList != this.TypeParameterList || parameterList != this.ParameterList || constraintClauses != this.ConstraintClauses || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.DelegateDeclaration(attributeLists, modifiers, delegateKeyword, returnType, identifier, typeParameterList, parameterList, constraintClauses, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new DelegateDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.DelegateKeyword, this.ReturnType, this.Identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, this.SemicolonToken); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new DelegateDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.DelegateKeyword, this.ReturnType, this.Identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, this.SemicolonToken); public DelegateDeclarationSyntax WithDelegateKeyword(SyntaxToken delegateKeyword) => Update(this.AttributeLists, this.Modifiers, delegateKeyword, this.ReturnType, this.Identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, this.SemicolonToken); public DelegateDeclarationSyntax WithReturnType(TypeSyntax returnType) => Update(this.AttributeLists, this.Modifiers, this.DelegateKeyword, returnType, this.Identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, this.SemicolonToken); public DelegateDeclarationSyntax WithIdentifier(SyntaxToken identifier) => Update(this.AttributeLists, this.Modifiers, this.DelegateKeyword, this.ReturnType, identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, this.SemicolonToken); public DelegateDeclarationSyntax WithTypeParameterList(TypeParameterListSyntax? typeParameterList) => Update(this.AttributeLists, this.Modifiers, this.DelegateKeyword, this.ReturnType, this.Identifier, typeParameterList, this.ParameterList, this.ConstraintClauses, this.SemicolonToken); public DelegateDeclarationSyntax WithParameterList(ParameterListSyntax parameterList) => Update(this.AttributeLists, this.Modifiers, this.DelegateKeyword, this.ReturnType, this.Identifier, this.TypeParameterList, parameterList, this.ConstraintClauses, this.SemicolonToken); public DelegateDeclarationSyntax WithConstraintClauses(SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses) => Update(this.AttributeLists, this.Modifiers, this.DelegateKeyword, this.ReturnType, this.Identifier, this.TypeParameterList, this.ParameterList, constraintClauses, this.SemicolonToken); public DelegateDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.DelegateKeyword, this.ReturnType, this.Identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, semicolonToken); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new DelegateDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new DelegateDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); public DelegateDeclarationSyntax AddTypeParameterListParameters(params TypeParameterSyntax[] items) { var typeParameterList = this.TypeParameterList ?? SyntaxFactory.TypeParameterList(); return WithTypeParameterList(typeParameterList.WithParameters(typeParameterList.Parameters.AddRange(items))); } public DelegateDeclarationSyntax AddParameterListParameters(params ParameterSyntax[] items) => WithParameterList(this.ParameterList.WithParameters(this.ParameterList.Parameters.AddRange(items))); public DelegateDeclarationSyntax AddConstraintClauses(params TypeParameterConstraintClauseSyntax[] items) => WithConstraintClauses(this.ConstraintClauses.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.EnumMemberDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class EnumMemberDeclarationSyntax : MemberDeclarationSyntax { private SyntaxNode? attributeLists; private EqualsValueClauseSyntax? equalsValue; internal EnumMemberDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.EnumMemberDeclarationSyntax)this.Green).identifier, GetChildPosition(2), GetChildIndex(2)); public EqualsValueClauseSyntax? EqualsValue => GetRed(ref this.equalsValue, 3); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 3 => GetRed(ref this.equalsValue, 3), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 3 => this.equalsValue, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitEnumMemberDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitEnumMemberDeclaration(this); public EnumMemberDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken identifier, EqualsValueClauseSyntax? equalsValue) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || identifier != this.Identifier || equalsValue != this.EqualsValue) { var newNode = SyntaxFactory.EnumMemberDeclaration(attributeLists, modifiers, identifier, equalsValue); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new EnumMemberDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.Identifier, this.EqualsValue); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new EnumMemberDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.Identifier, this.EqualsValue); public EnumMemberDeclarationSyntax WithIdentifier(SyntaxToken identifier) => Update(this.AttributeLists, this.Modifiers, identifier, this.EqualsValue); public EnumMemberDeclarationSyntax WithEqualsValue(EqualsValueClauseSyntax? equalsValue) => Update(this.AttributeLists, this.Modifiers, this.Identifier, equalsValue); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new EnumMemberDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new EnumMemberDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); } /// <summary>Base list syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.BaseList"/></description></item> /// </list> /// </remarks> public sealed partial class BaseListSyntax : CSharpSyntaxNode { private SyntaxNode? types; internal BaseListSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the colon token.</summary> public SyntaxToken ColonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.BaseListSyntax)this.Green).colonToken, Position, 0); /// <summary>Gets the base type references.</summary> public SeparatedSyntaxList<BaseTypeSyntax> Types { get { var red = GetRed(ref this.types, 1); return red != null ? new SeparatedSyntaxList<BaseTypeSyntax>(red, GetChildIndex(1)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.types, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.types : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitBaseList(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitBaseList(this); public BaseListSyntax Update(SyntaxToken colonToken, SeparatedSyntaxList<BaseTypeSyntax> types) { if (colonToken != this.ColonToken || types != this.Types) { var newNode = SyntaxFactory.BaseList(colonToken, types); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public BaseListSyntax WithColonToken(SyntaxToken colonToken) => Update(colonToken, this.Types); public BaseListSyntax WithTypes(SeparatedSyntaxList<BaseTypeSyntax> types) => Update(this.ColonToken, types); public BaseListSyntax AddTypes(params BaseTypeSyntax[] items) => WithTypes(this.Types.AddRange(items)); } /// <summary>Provides the base class from which the classes that represent base type syntax nodes are derived. This is an abstract class.</summary> public abstract partial class BaseTypeSyntax : CSharpSyntaxNode { internal BaseTypeSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public abstract TypeSyntax Type { get; } public BaseTypeSyntax WithType(TypeSyntax type) => WithTypeCore(type); internal abstract BaseTypeSyntax WithTypeCore(TypeSyntax type); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.SimpleBaseType"/></description></item> /// </list> /// </remarks> public sealed partial class SimpleBaseTypeSyntax : BaseTypeSyntax { private TypeSyntax? type; internal SimpleBaseTypeSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override TypeSyntax Type => GetRedAtZero(ref this.type)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.type)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.type : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitSimpleBaseType(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitSimpleBaseType(this); public SimpleBaseTypeSyntax Update(TypeSyntax type) { if (type != this.Type) { var newNode = SyntaxFactory.SimpleBaseType(type); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override BaseTypeSyntax WithTypeCore(TypeSyntax type) => WithType(type); public new SimpleBaseTypeSyntax WithType(TypeSyntax type) => Update(type); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.PrimaryConstructorBaseType"/></description></item> /// </list> /// </remarks> public sealed partial class PrimaryConstructorBaseTypeSyntax : BaseTypeSyntax { private TypeSyntax? type; private ArgumentListSyntax? argumentList; internal PrimaryConstructorBaseTypeSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override TypeSyntax Type => GetRedAtZero(ref this.type)!; public ArgumentListSyntax ArgumentList => GetRed(ref this.argumentList, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.type)!, 1 => GetRed(ref this.argumentList, 1)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.type, 1 => this.argumentList, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitPrimaryConstructorBaseType(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitPrimaryConstructorBaseType(this); public PrimaryConstructorBaseTypeSyntax Update(TypeSyntax type, ArgumentListSyntax argumentList) { if (type != this.Type || argumentList != this.ArgumentList) { var newNode = SyntaxFactory.PrimaryConstructorBaseType(type, argumentList); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override BaseTypeSyntax WithTypeCore(TypeSyntax type) => WithType(type); public new PrimaryConstructorBaseTypeSyntax WithType(TypeSyntax type) => Update(type, this.ArgumentList); public PrimaryConstructorBaseTypeSyntax WithArgumentList(ArgumentListSyntax argumentList) => Update(this.Type, argumentList); public PrimaryConstructorBaseTypeSyntax AddArgumentListArguments(params ArgumentSyntax[] items) => WithArgumentList(this.ArgumentList.WithArguments(this.ArgumentList.Arguments.AddRange(items))); } /// <summary>Type parameter constraint clause.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.TypeParameterConstraintClause"/></description></item> /// </list> /// </remarks> public sealed partial class TypeParameterConstraintClauseSyntax : CSharpSyntaxNode { private IdentifierNameSyntax? name; private SyntaxNode? constraints; internal TypeParameterConstraintClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken WhereKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.TypeParameterConstraintClauseSyntax)this.Green).whereKeyword, Position, 0); /// <summary>Gets the identifier.</summary> public IdentifierNameSyntax Name => GetRed(ref this.name, 1)!; /// <summary>Gets the colon token.</summary> public SyntaxToken ColonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.TypeParameterConstraintClauseSyntax)this.Green).colonToken, GetChildPosition(2), GetChildIndex(2)); /// <summary>Gets the constraints list.</summary> public SeparatedSyntaxList<TypeParameterConstraintSyntax> Constraints { get { var red = GetRed(ref this.constraints, 3); return red != null ? new SeparatedSyntaxList<TypeParameterConstraintSyntax>(red, GetChildIndex(3)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index switch { 1 => GetRed(ref this.name, 1)!, 3 => GetRed(ref this.constraints, 3)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 1 => this.name, 3 => this.constraints, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitTypeParameterConstraintClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitTypeParameterConstraintClause(this); public TypeParameterConstraintClauseSyntax Update(SyntaxToken whereKeyword, IdentifierNameSyntax name, SyntaxToken colonToken, SeparatedSyntaxList<TypeParameterConstraintSyntax> constraints) { if (whereKeyword != this.WhereKeyword || name != this.Name || colonToken != this.ColonToken || constraints != this.Constraints) { var newNode = SyntaxFactory.TypeParameterConstraintClause(whereKeyword, name, colonToken, constraints); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public TypeParameterConstraintClauseSyntax WithWhereKeyword(SyntaxToken whereKeyword) => Update(whereKeyword, this.Name, this.ColonToken, this.Constraints); public TypeParameterConstraintClauseSyntax WithName(IdentifierNameSyntax name) => Update(this.WhereKeyword, name, this.ColonToken, this.Constraints); public TypeParameterConstraintClauseSyntax WithColonToken(SyntaxToken colonToken) => Update(this.WhereKeyword, this.Name, colonToken, this.Constraints); public TypeParameterConstraintClauseSyntax WithConstraints(SeparatedSyntaxList<TypeParameterConstraintSyntax> constraints) => Update(this.WhereKeyword, this.Name, this.ColonToken, constraints); public TypeParameterConstraintClauseSyntax AddConstraints(params TypeParameterConstraintSyntax[] items) => WithConstraints(this.Constraints.AddRange(items)); } /// <summary>Base type for type parameter constraint syntax.</summary> public abstract partial class TypeParameterConstraintSyntax : CSharpSyntaxNode { internal TypeParameterConstraintSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } } /// <summary>Constructor constraint syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ConstructorConstraint"/></description></item> /// </list> /// </remarks> public sealed partial class ConstructorConstraintSyntax : TypeParameterConstraintSyntax { internal ConstructorConstraintSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the "new" keyword.</summary> public SyntaxToken NewKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ConstructorConstraintSyntax)this.Green).newKeyword, Position, 0); /// <summary>Gets the open paren keyword.</summary> public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ConstructorConstraintSyntax)this.Green).openParenToken, GetChildPosition(1), GetChildIndex(1)); /// <summary>Gets the close paren keyword.</summary> public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ConstructorConstraintSyntax)this.Green).closeParenToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitConstructorConstraint(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitConstructorConstraint(this); public ConstructorConstraintSyntax Update(SyntaxToken newKeyword, SyntaxToken openParenToken, SyntaxToken closeParenToken) { if (newKeyword != this.NewKeyword || openParenToken != this.OpenParenToken || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.ConstructorConstraint(newKeyword, openParenToken, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ConstructorConstraintSyntax WithNewKeyword(SyntaxToken newKeyword) => Update(newKeyword, this.OpenParenToken, this.CloseParenToken); public ConstructorConstraintSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(this.NewKeyword, openParenToken, this.CloseParenToken); public ConstructorConstraintSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.NewKeyword, this.OpenParenToken, closeParenToken); } /// <summary>Class or struct constraint syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ClassConstraint"/></description></item> /// <item><description><see cref="SyntaxKind.StructConstraint"/></description></item> /// </list> /// </remarks> public sealed partial class ClassOrStructConstraintSyntax : TypeParameterConstraintSyntax { internal ClassOrStructConstraintSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the constraint keyword ("class" or "struct").</summary> public SyntaxToken ClassOrStructKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ClassOrStructConstraintSyntax)this.Green).classOrStructKeyword, Position, 0); /// <summary>SyntaxToken representing the question mark.</summary> public SyntaxToken QuestionToken { get { var slot = ((Syntax.InternalSyntax.ClassOrStructConstraintSyntax)this.Green).questionToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitClassOrStructConstraint(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitClassOrStructConstraint(this); public ClassOrStructConstraintSyntax Update(SyntaxToken classOrStructKeyword, SyntaxToken questionToken) { if (classOrStructKeyword != this.ClassOrStructKeyword || questionToken != this.QuestionToken) { var newNode = SyntaxFactory.ClassOrStructConstraint(this.Kind(), classOrStructKeyword, questionToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ClassOrStructConstraintSyntax WithClassOrStructKeyword(SyntaxToken classOrStructKeyword) => Update(classOrStructKeyword, this.QuestionToken); public ClassOrStructConstraintSyntax WithQuestionToken(SyntaxToken questionToken) => Update(this.ClassOrStructKeyword, questionToken); } /// <summary>Type constraint syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.TypeConstraint"/></description></item> /// </list> /// </remarks> public sealed partial class TypeConstraintSyntax : TypeParameterConstraintSyntax { private TypeSyntax? type; internal TypeConstraintSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the type syntax.</summary> public TypeSyntax Type => GetRedAtZero(ref this.type)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.type)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.type : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitTypeConstraint(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitTypeConstraint(this); public TypeConstraintSyntax Update(TypeSyntax type) { if (type != this.Type) { var newNode = SyntaxFactory.TypeConstraint(type); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public TypeConstraintSyntax WithType(TypeSyntax type) => Update(type); } /// <summary>Default constraint syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.DefaultConstraint"/></description></item> /// </list> /// </remarks> public sealed partial class DefaultConstraintSyntax : TypeParameterConstraintSyntax { internal DefaultConstraintSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the "default" keyword.</summary> public SyntaxToken DefaultKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.DefaultConstraintSyntax)this.Green).defaultKeyword, Position, 0); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitDefaultConstraint(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitDefaultConstraint(this); public DefaultConstraintSyntax Update(SyntaxToken defaultKeyword) { if (defaultKeyword != this.DefaultKeyword) { var newNode = SyntaxFactory.DefaultConstraint(defaultKeyword); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public DefaultConstraintSyntax WithDefaultKeyword(SyntaxToken defaultKeyword) => Update(defaultKeyword); } public abstract partial class BaseFieldDeclarationSyntax : MemberDeclarationSyntax { internal BaseFieldDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public abstract VariableDeclarationSyntax Declaration { get; } public BaseFieldDeclarationSyntax WithDeclaration(VariableDeclarationSyntax declaration) => WithDeclarationCore(declaration); internal abstract BaseFieldDeclarationSyntax WithDeclarationCore(VariableDeclarationSyntax declaration); public BaseFieldDeclarationSyntax AddDeclarationVariables(params VariableDeclaratorSyntax[] items) => AddDeclarationVariablesCore(items); internal abstract BaseFieldDeclarationSyntax AddDeclarationVariablesCore(params VariableDeclaratorSyntax[] items); public abstract SyntaxToken SemicolonToken { get; } public BaseFieldDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => WithSemicolonTokenCore(semicolonToken); internal abstract BaseFieldDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken); public new BaseFieldDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => (BaseFieldDeclarationSyntax)WithAttributeListsCore(attributeLists); public new BaseFieldDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => (BaseFieldDeclarationSyntax)WithModifiersCore(modifiers); public new BaseFieldDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => (BaseFieldDeclarationSyntax)AddAttributeListsCore(items); public new BaseFieldDeclarationSyntax AddModifiers(params SyntaxToken[] items) => (BaseFieldDeclarationSyntax)AddModifiersCore(items); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.FieldDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class FieldDeclarationSyntax : BaseFieldDeclarationSyntax { private SyntaxNode? attributeLists; private VariableDeclarationSyntax? declaration; internal FieldDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public override VariableDeclarationSyntax Declaration => GetRed(ref this.declaration, 2)!; public override SyntaxToken SemicolonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.FieldDeclarationSyntax)this.Green).semicolonToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.declaration, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.declaration, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitFieldDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitFieldDeclaration(this); public FieldDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || declaration != this.Declaration || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.FieldDeclaration(attributeLists, modifiers, declaration, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new FieldDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.Declaration, this.SemicolonToken); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new FieldDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.Declaration, this.SemicolonToken); internal override BaseFieldDeclarationSyntax WithDeclarationCore(VariableDeclarationSyntax declaration) => WithDeclaration(declaration); public new FieldDeclarationSyntax WithDeclaration(VariableDeclarationSyntax declaration) => Update(this.AttributeLists, this.Modifiers, declaration, this.SemicolonToken); internal override BaseFieldDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken) => WithSemicolonToken(semicolonToken); public new FieldDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.Declaration, semicolonToken); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new FieldDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new FieldDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); internal override BaseFieldDeclarationSyntax AddDeclarationVariablesCore(params VariableDeclaratorSyntax[] items) => AddDeclarationVariables(items); public new FieldDeclarationSyntax AddDeclarationVariables(params VariableDeclaratorSyntax[] items) => WithDeclaration(this.Declaration.WithVariables(this.Declaration.Variables.AddRange(items))); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.EventFieldDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class EventFieldDeclarationSyntax : BaseFieldDeclarationSyntax { private SyntaxNode? attributeLists; private VariableDeclarationSyntax? declaration; internal EventFieldDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public SyntaxToken EventKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.EventFieldDeclarationSyntax)this.Green).eventKeyword, GetChildPosition(2), GetChildIndex(2)); public override VariableDeclarationSyntax Declaration => GetRed(ref this.declaration, 3)!; public override SyntaxToken SemicolonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.EventFieldDeclarationSyntax)this.Green).semicolonToken, GetChildPosition(4), GetChildIndex(4)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 3 => GetRed(ref this.declaration, 3)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 3 => this.declaration, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitEventFieldDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitEventFieldDeclaration(this); public EventFieldDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken eventKeyword, VariableDeclarationSyntax declaration, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || eventKeyword != this.EventKeyword || declaration != this.Declaration || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.EventFieldDeclaration(attributeLists, modifiers, eventKeyword, declaration, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new EventFieldDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.EventKeyword, this.Declaration, this.SemicolonToken); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new EventFieldDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.EventKeyword, this.Declaration, this.SemicolonToken); public EventFieldDeclarationSyntax WithEventKeyword(SyntaxToken eventKeyword) => Update(this.AttributeLists, this.Modifiers, eventKeyword, this.Declaration, this.SemicolonToken); internal override BaseFieldDeclarationSyntax WithDeclarationCore(VariableDeclarationSyntax declaration) => WithDeclaration(declaration); public new EventFieldDeclarationSyntax WithDeclaration(VariableDeclarationSyntax declaration) => Update(this.AttributeLists, this.Modifiers, this.EventKeyword, declaration, this.SemicolonToken); internal override BaseFieldDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken) => WithSemicolonToken(semicolonToken); public new EventFieldDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.EventKeyword, this.Declaration, semicolonToken); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new EventFieldDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new EventFieldDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); internal override BaseFieldDeclarationSyntax AddDeclarationVariablesCore(params VariableDeclaratorSyntax[] items) => AddDeclarationVariables(items); public new EventFieldDeclarationSyntax AddDeclarationVariables(params VariableDeclaratorSyntax[] items) => WithDeclaration(this.Declaration.WithVariables(this.Declaration.Variables.AddRange(items))); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ExplicitInterfaceSpecifier"/></description></item> /// </list> /// </remarks> public sealed partial class ExplicitInterfaceSpecifierSyntax : CSharpSyntaxNode { private NameSyntax? name; internal ExplicitInterfaceSpecifierSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public NameSyntax Name => GetRedAtZero(ref this.name)!; public SyntaxToken DotToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ExplicitInterfaceSpecifierSyntax)this.Green).dotToken, GetChildPosition(1), GetChildIndex(1)); internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.name)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.name : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitExplicitInterfaceSpecifier(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitExplicitInterfaceSpecifier(this); public ExplicitInterfaceSpecifierSyntax Update(NameSyntax name, SyntaxToken dotToken) { if (name != this.Name || dotToken != this.DotToken) { var newNode = SyntaxFactory.ExplicitInterfaceSpecifier(name, dotToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ExplicitInterfaceSpecifierSyntax WithName(NameSyntax name) => Update(name, this.DotToken); public ExplicitInterfaceSpecifierSyntax WithDotToken(SyntaxToken dotToken) => Update(this.Name, dotToken); } /// <summary>Base type for method declaration syntax.</summary> public abstract partial class BaseMethodDeclarationSyntax : MemberDeclarationSyntax { internal BaseMethodDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the parameter list.</summary> public abstract ParameterListSyntax ParameterList { get; } public BaseMethodDeclarationSyntax WithParameterList(ParameterListSyntax parameterList) => WithParameterListCore(parameterList); internal abstract BaseMethodDeclarationSyntax WithParameterListCore(ParameterListSyntax parameterList); public BaseMethodDeclarationSyntax AddParameterListParameters(params ParameterSyntax[] items) => AddParameterListParametersCore(items); internal abstract BaseMethodDeclarationSyntax AddParameterListParametersCore(params ParameterSyntax[] items); public abstract BlockSyntax? Body { get; } public BaseMethodDeclarationSyntax WithBody(BlockSyntax? body) => WithBodyCore(body); internal abstract BaseMethodDeclarationSyntax WithBodyCore(BlockSyntax? body); public BaseMethodDeclarationSyntax AddBodyAttributeLists(params AttributeListSyntax[] items) => AddBodyAttributeListsCore(items); internal abstract BaseMethodDeclarationSyntax AddBodyAttributeListsCore(params AttributeListSyntax[] items); public BaseMethodDeclarationSyntax AddBodyStatements(params StatementSyntax[] items) => AddBodyStatementsCore(items); internal abstract BaseMethodDeclarationSyntax AddBodyStatementsCore(params StatementSyntax[] items); public abstract ArrowExpressionClauseSyntax? ExpressionBody { get; } public BaseMethodDeclarationSyntax WithExpressionBody(ArrowExpressionClauseSyntax? expressionBody) => WithExpressionBodyCore(expressionBody); internal abstract BaseMethodDeclarationSyntax WithExpressionBodyCore(ArrowExpressionClauseSyntax? expressionBody); /// <summary>Gets the optional semicolon token.</summary> public abstract SyntaxToken SemicolonToken { get; } public BaseMethodDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => WithSemicolonTokenCore(semicolonToken); internal abstract BaseMethodDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken); public new BaseMethodDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => (BaseMethodDeclarationSyntax)WithAttributeListsCore(attributeLists); public new BaseMethodDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => (BaseMethodDeclarationSyntax)WithModifiersCore(modifiers); public new BaseMethodDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => (BaseMethodDeclarationSyntax)AddAttributeListsCore(items); public new BaseMethodDeclarationSyntax AddModifiers(params SyntaxToken[] items) => (BaseMethodDeclarationSyntax)AddModifiersCore(items); } /// <summary>Method declaration syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.MethodDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class MethodDeclarationSyntax : BaseMethodDeclarationSyntax { private SyntaxNode? attributeLists; private TypeSyntax? returnType; private ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier; private TypeParameterListSyntax? typeParameterList; private ParameterListSyntax? parameterList; private SyntaxNode? constraintClauses; private BlockSyntax? body; private ArrowExpressionClauseSyntax? expressionBody; internal MethodDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } /// <summary>Gets the return type syntax.</summary> public TypeSyntax ReturnType => GetRed(ref this.returnType, 2)!; public ExplicitInterfaceSpecifierSyntax? ExplicitInterfaceSpecifier => GetRed(ref this.explicitInterfaceSpecifier, 3); /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.MethodDeclarationSyntax)this.Green).identifier, GetChildPosition(4), GetChildIndex(4)); public TypeParameterListSyntax? TypeParameterList => GetRed(ref this.typeParameterList, 5); public override ParameterListSyntax ParameterList => GetRed(ref this.parameterList, 6)!; /// <summary>Gets the constraint clause list.</summary> public SyntaxList<TypeParameterConstraintClauseSyntax> ConstraintClauses => new SyntaxList<TypeParameterConstraintClauseSyntax>(GetRed(ref this.constraintClauses, 7)); public override BlockSyntax? Body => GetRed(ref this.body, 8); public override ArrowExpressionClauseSyntax? ExpressionBody => GetRed(ref this.expressionBody, 9); /// <summary>Gets the optional semicolon token.</summary> public override SyntaxToken SemicolonToken { get { var slot = ((Syntax.InternalSyntax.MethodDeclarationSyntax)this.Green).semicolonToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(10), GetChildIndex(10)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.returnType, 2)!, 3 => GetRed(ref this.explicitInterfaceSpecifier, 3), 5 => GetRed(ref this.typeParameterList, 5), 6 => GetRed(ref this.parameterList, 6)!, 7 => GetRed(ref this.constraintClauses, 7)!, 8 => GetRed(ref this.body, 8), 9 => GetRed(ref this.expressionBody, 9), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.returnType, 3 => this.explicitInterfaceSpecifier, 5 => this.typeParameterList, 6 => this.parameterList, 7 => this.constraintClauses, 8 => this.body, 9 => this.expressionBody, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitMethodDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitMethodDeclaration(this); public MethodDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, TypeSyntax returnType, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken identifier, TypeParameterListSyntax? typeParameterList, ParameterListSyntax parameterList, SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || returnType != this.ReturnType || explicitInterfaceSpecifier != this.ExplicitInterfaceSpecifier || identifier != this.Identifier || typeParameterList != this.TypeParameterList || parameterList != this.ParameterList || constraintClauses != this.ConstraintClauses || body != this.Body || expressionBody != this.ExpressionBody || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.MethodDeclaration(attributeLists, modifiers, returnType, explicitInterfaceSpecifier, identifier, typeParameterList, parameterList, constraintClauses, body, expressionBody, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new MethodDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.ReturnType, this.ExplicitInterfaceSpecifier, this.Identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, this.Body, this.ExpressionBody, this.SemicolonToken); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new MethodDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.ReturnType, this.ExplicitInterfaceSpecifier, this.Identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, this.Body, this.ExpressionBody, this.SemicolonToken); public MethodDeclarationSyntax WithReturnType(TypeSyntax returnType) => Update(this.AttributeLists, this.Modifiers, returnType, this.ExplicitInterfaceSpecifier, this.Identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, this.Body, this.ExpressionBody, this.SemicolonToken); public MethodDeclarationSyntax WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, explicitInterfaceSpecifier, this.Identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, this.Body, this.ExpressionBody, this.SemicolonToken); public MethodDeclarationSyntax WithIdentifier(SyntaxToken identifier) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.ExplicitInterfaceSpecifier, identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, this.Body, this.ExpressionBody, this.SemicolonToken); public MethodDeclarationSyntax WithTypeParameterList(TypeParameterListSyntax? typeParameterList) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.ExplicitInterfaceSpecifier, this.Identifier, typeParameterList, this.ParameterList, this.ConstraintClauses, this.Body, this.ExpressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithParameterListCore(ParameterListSyntax parameterList) => WithParameterList(parameterList); public new MethodDeclarationSyntax WithParameterList(ParameterListSyntax parameterList) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.ExplicitInterfaceSpecifier, this.Identifier, this.TypeParameterList, parameterList, this.ConstraintClauses, this.Body, this.ExpressionBody, this.SemicolonToken); public MethodDeclarationSyntax WithConstraintClauses(SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.ExplicitInterfaceSpecifier, this.Identifier, this.TypeParameterList, this.ParameterList, constraintClauses, this.Body, this.ExpressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithBodyCore(BlockSyntax? body) => WithBody(body); public new MethodDeclarationSyntax WithBody(BlockSyntax? body) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.ExplicitInterfaceSpecifier, this.Identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, body, this.ExpressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithExpressionBodyCore(ArrowExpressionClauseSyntax? expressionBody) => WithExpressionBody(expressionBody); public new MethodDeclarationSyntax WithExpressionBody(ArrowExpressionClauseSyntax? expressionBody) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.ExplicitInterfaceSpecifier, this.Identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, this.Body, expressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken) => WithSemicolonToken(semicolonToken); public new MethodDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.ExplicitInterfaceSpecifier, this.Identifier, this.TypeParameterList, this.ParameterList, this.ConstraintClauses, this.Body, this.ExpressionBody, semicolonToken); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new MethodDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new MethodDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); public MethodDeclarationSyntax AddTypeParameterListParameters(params TypeParameterSyntax[] items) { var typeParameterList = this.TypeParameterList ?? SyntaxFactory.TypeParameterList(); return WithTypeParameterList(typeParameterList.WithParameters(typeParameterList.Parameters.AddRange(items))); } internal override BaseMethodDeclarationSyntax AddParameterListParametersCore(params ParameterSyntax[] items) => AddParameterListParameters(items); public new MethodDeclarationSyntax AddParameterListParameters(params ParameterSyntax[] items) => WithParameterList(this.ParameterList.WithParameters(this.ParameterList.Parameters.AddRange(items))); public MethodDeclarationSyntax AddConstraintClauses(params TypeParameterConstraintClauseSyntax[] items) => WithConstraintClauses(this.ConstraintClauses.AddRange(items)); internal override BaseMethodDeclarationSyntax AddBodyAttributeListsCore(params AttributeListSyntax[] items) => AddBodyAttributeLists(items); public new MethodDeclarationSyntax AddBodyAttributeLists(params AttributeListSyntax[] items) { var body = this.Body ?? SyntaxFactory.Block(); return WithBody(body.WithAttributeLists(body.AttributeLists.AddRange(items))); } internal override BaseMethodDeclarationSyntax AddBodyStatementsCore(params StatementSyntax[] items) => AddBodyStatements(items); public new MethodDeclarationSyntax AddBodyStatements(params StatementSyntax[] items) { var body = this.Body ?? SyntaxFactory.Block(); return WithBody(body.WithStatements(body.Statements.AddRange(items))); } } /// <summary>Operator declaration syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.OperatorDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class OperatorDeclarationSyntax : BaseMethodDeclarationSyntax { private SyntaxNode? attributeLists; private TypeSyntax? returnType; private ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier; private ParameterListSyntax? parameterList; private BlockSyntax? body; private ArrowExpressionClauseSyntax? expressionBody; internal OperatorDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } /// <summary>Gets the return type.</summary> public TypeSyntax ReturnType => GetRed(ref this.returnType, 2)!; public ExplicitInterfaceSpecifierSyntax? ExplicitInterfaceSpecifier => GetRed(ref this.explicitInterfaceSpecifier, 3); /// <summary>Gets the "operator" keyword.</summary> public SyntaxToken OperatorKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.OperatorDeclarationSyntax)this.Green).operatorKeyword, GetChildPosition(4), GetChildIndex(4)); /// <summary>Gets the operator token.</summary> public SyntaxToken OperatorToken => new SyntaxToken(this, ((Syntax.InternalSyntax.OperatorDeclarationSyntax)this.Green).operatorToken, GetChildPosition(5), GetChildIndex(5)); public override ParameterListSyntax ParameterList => GetRed(ref this.parameterList, 6)!; public override BlockSyntax? Body => GetRed(ref this.body, 7); public override ArrowExpressionClauseSyntax? ExpressionBody => GetRed(ref this.expressionBody, 8); /// <summary>Gets the optional semicolon token.</summary> public override SyntaxToken SemicolonToken { get { var slot = ((Syntax.InternalSyntax.OperatorDeclarationSyntax)this.Green).semicolonToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(9), GetChildIndex(9)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.returnType, 2)!, 3 => GetRed(ref this.explicitInterfaceSpecifier, 3), 6 => GetRed(ref this.parameterList, 6)!, 7 => GetRed(ref this.body, 7), 8 => GetRed(ref this.expressionBody, 8), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.returnType, 3 => this.explicitInterfaceSpecifier, 6 => this.parameterList, 7 => this.body, 8 => this.expressionBody, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitOperatorDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitOperatorDeclaration(this); public OperatorDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, TypeSyntax returnType, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken operatorKeyword, SyntaxToken operatorToken, ParameterListSyntax parameterList, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || returnType != this.ReturnType || explicitInterfaceSpecifier != this.ExplicitInterfaceSpecifier || operatorKeyword != this.OperatorKeyword || operatorToken != this.OperatorToken || parameterList != this.ParameterList || body != this.Body || expressionBody != this.ExpressionBody || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.OperatorDeclaration(attributeLists, modifiers, returnType, explicitInterfaceSpecifier, operatorKeyword, operatorToken, parameterList, body, expressionBody, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new OperatorDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.ReturnType, this.ExplicitInterfaceSpecifier, this.OperatorKeyword, this.OperatorToken, this.ParameterList, this.Body, this.ExpressionBody, this.SemicolonToken); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new OperatorDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.ReturnType, this.ExplicitInterfaceSpecifier, this.OperatorKeyword, this.OperatorToken, this.ParameterList, this.Body, this.ExpressionBody, this.SemicolonToken); public OperatorDeclarationSyntax WithReturnType(TypeSyntax returnType) => Update(this.AttributeLists, this.Modifiers, returnType, this.ExplicitInterfaceSpecifier, this.OperatorKeyword, this.OperatorToken, this.ParameterList, this.Body, this.ExpressionBody, this.SemicolonToken); public OperatorDeclarationSyntax WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, explicitInterfaceSpecifier, this.OperatorKeyword, this.OperatorToken, this.ParameterList, this.Body, this.ExpressionBody, this.SemicolonToken); public OperatorDeclarationSyntax WithOperatorKeyword(SyntaxToken operatorKeyword) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.ExplicitInterfaceSpecifier, operatorKeyword, this.OperatorToken, this.ParameterList, this.Body, this.ExpressionBody, this.SemicolonToken); public OperatorDeclarationSyntax WithOperatorToken(SyntaxToken operatorToken) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.ExplicitInterfaceSpecifier, this.OperatorKeyword, operatorToken, this.ParameterList, this.Body, this.ExpressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithParameterListCore(ParameterListSyntax parameterList) => WithParameterList(parameterList); public new OperatorDeclarationSyntax WithParameterList(ParameterListSyntax parameterList) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.ExplicitInterfaceSpecifier, this.OperatorKeyword, this.OperatorToken, parameterList, this.Body, this.ExpressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithBodyCore(BlockSyntax? body) => WithBody(body); public new OperatorDeclarationSyntax WithBody(BlockSyntax? body) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.ExplicitInterfaceSpecifier, this.OperatorKeyword, this.OperatorToken, this.ParameterList, body, this.ExpressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithExpressionBodyCore(ArrowExpressionClauseSyntax? expressionBody) => WithExpressionBody(expressionBody); public new OperatorDeclarationSyntax WithExpressionBody(ArrowExpressionClauseSyntax? expressionBody) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.ExplicitInterfaceSpecifier, this.OperatorKeyword, this.OperatorToken, this.ParameterList, this.Body, expressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken) => WithSemicolonToken(semicolonToken); public new OperatorDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.ReturnType, this.ExplicitInterfaceSpecifier, this.OperatorKeyword, this.OperatorToken, this.ParameterList, this.Body, this.ExpressionBody, semicolonToken); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new OperatorDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new OperatorDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); internal override BaseMethodDeclarationSyntax AddParameterListParametersCore(params ParameterSyntax[] items) => AddParameterListParameters(items); public new OperatorDeclarationSyntax AddParameterListParameters(params ParameterSyntax[] items) => WithParameterList(this.ParameterList.WithParameters(this.ParameterList.Parameters.AddRange(items))); internal override BaseMethodDeclarationSyntax AddBodyAttributeListsCore(params AttributeListSyntax[] items) => AddBodyAttributeLists(items); public new OperatorDeclarationSyntax AddBodyAttributeLists(params AttributeListSyntax[] items) { var body = this.Body ?? SyntaxFactory.Block(); return WithBody(body.WithAttributeLists(body.AttributeLists.AddRange(items))); } internal override BaseMethodDeclarationSyntax AddBodyStatementsCore(params StatementSyntax[] items) => AddBodyStatements(items); public new OperatorDeclarationSyntax AddBodyStatements(params StatementSyntax[] items) { var body = this.Body ?? SyntaxFactory.Block(); return WithBody(body.WithStatements(body.Statements.AddRange(items))); } } /// <summary>Conversion operator declaration syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ConversionOperatorDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class ConversionOperatorDeclarationSyntax : BaseMethodDeclarationSyntax { private SyntaxNode? attributeLists; private ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier; private TypeSyntax? type; private ParameterListSyntax? parameterList; private BlockSyntax? body; private ArrowExpressionClauseSyntax? expressionBody; internal ConversionOperatorDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } /// <summary>Gets the "implicit" or "explicit" token.</summary> public SyntaxToken ImplicitOrExplicitKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ConversionOperatorDeclarationSyntax)this.Green).implicitOrExplicitKeyword, GetChildPosition(2), GetChildIndex(2)); public ExplicitInterfaceSpecifierSyntax? ExplicitInterfaceSpecifier => GetRed(ref this.explicitInterfaceSpecifier, 3); /// <summary>Gets the "operator" token.</summary> public SyntaxToken OperatorKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ConversionOperatorDeclarationSyntax)this.Green).operatorKeyword, GetChildPosition(4), GetChildIndex(4)); /// <summary>Gets the type.</summary> public TypeSyntax Type => GetRed(ref this.type, 5)!; public override ParameterListSyntax ParameterList => GetRed(ref this.parameterList, 6)!; public override BlockSyntax? Body => GetRed(ref this.body, 7); public override ArrowExpressionClauseSyntax? ExpressionBody => GetRed(ref this.expressionBody, 8); /// <summary>Gets the optional semicolon token.</summary> public override SyntaxToken SemicolonToken { get { var slot = ((Syntax.InternalSyntax.ConversionOperatorDeclarationSyntax)this.Green).semicolonToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(9), GetChildIndex(9)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 3 => GetRed(ref this.explicitInterfaceSpecifier, 3), 5 => GetRed(ref this.type, 5)!, 6 => GetRed(ref this.parameterList, 6)!, 7 => GetRed(ref this.body, 7), 8 => GetRed(ref this.expressionBody, 8), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 3 => this.explicitInterfaceSpecifier, 5 => this.type, 6 => this.parameterList, 7 => this.body, 8 => this.expressionBody, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitConversionOperatorDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitConversionOperatorDeclaration(this); public ConversionOperatorDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken implicitOrExplicitKeyword, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken operatorKeyword, TypeSyntax type, ParameterListSyntax parameterList, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || implicitOrExplicitKeyword != this.ImplicitOrExplicitKeyword || explicitInterfaceSpecifier != this.ExplicitInterfaceSpecifier || operatorKeyword != this.OperatorKeyword || type != this.Type || parameterList != this.ParameterList || body != this.Body || expressionBody != this.ExpressionBody || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.ConversionOperatorDeclaration(attributeLists, modifiers, implicitOrExplicitKeyword, explicitInterfaceSpecifier, operatorKeyword, type, parameterList, body, expressionBody, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new ConversionOperatorDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.ImplicitOrExplicitKeyword, this.ExplicitInterfaceSpecifier, this.OperatorKeyword, this.Type, this.ParameterList, this.Body, this.ExpressionBody, this.SemicolonToken); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new ConversionOperatorDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.ImplicitOrExplicitKeyword, this.ExplicitInterfaceSpecifier, this.OperatorKeyword, this.Type, this.ParameterList, this.Body, this.ExpressionBody, this.SemicolonToken); public ConversionOperatorDeclarationSyntax WithImplicitOrExplicitKeyword(SyntaxToken implicitOrExplicitKeyword) => Update(this.AttributeLists, this.Modifiers, implicitOrExplicitKeyword, this.ExplicitInterfaceSpecifier, this.OperatorKeyword, this.Type, this.ParameterList, this.Body, this.ExpressionBody, this.SemicolonToken); public ConversionOperatorDeclarationSyntax WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier) => Update(this.AttributeLists, this.Modifiers, this.ImplicitOrExplicitKeyword, explicitInterfaceSpecifier, this.OperatorKeyword, this.Type, this.ParameterList, this.Body, this.ExpressionBody, this.SemicolonToken); public ConversionOperatorDeclarationSyntax WithOperatorKeyword(SyntaxToken operatorKeyword) => Update(this.AttributeLists, this.Modifiers, this.ImplicitOrExplicitKeyword, this.ExplicitInterfaceSpecifier, operatorKeyword, this.Type, this.ParameterList, this.Body, this.ExpressionBody, this.SemicolonToken); public ConversionOperatorDeclarationSyntax WithType(TypeSyntax type) => Update(this.AttributeLists, this.Modifiers, this.ImplicitOrExplicitKeyword, this.ExplicitInterfaceSpecifier, this.OperatorKeyword, type, this.ParameterList, this.Body, this.ExpressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithParameterListCore(ParameterListSyntax parameterList) => WithParameterList(parameterList); public new ConversionOperatorDeclarationSyntax WithParameterList(ParameterListSyntax parameterList) => Update(this.AttributeLists, this.Modifiers, this.ImplicitOrExplicitKeyword, this.ExplicitInterfaceSpecifier, this.OperatorKeyword, this.Type, parameterList, this.Body, this.ExpressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithBodyCore(BlockSyntax? body) => WithBody(body); public new ConversionOperatorDeclarationSyntax WithBody(BlockSyntax? body) => Update(this.AttributeLists, this.Modifiers, this.ImplicitOrExplicitKeyword, this.ExplicitInterfaceSpecifier, this.OperatorKeyword, this.Type, this.ParameterList, body, this.ExpressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithExpressionBodyCore(ArrowExpressionClauseSyntax? expressionBody) => WithExpressionBody(expressionBody); public new ConversionOperatorDeclarationSyntax WithExpressionBody(ArrowExpressionClauseSyntax? expressionBody) => Update(this.AttributeLists, this.Modifiers, this.ImplicitOrExplicitKeyword, this.ExplicitInterfaceSpecifier, this.OperatorKeyword, this.Type, this.ParameterList, this.Body, expressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken) => WithSemicolonToken(semicolonToken); public new ConversionOperatorDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.ImplicitOrExplicitKeyword, this.ExplicitInterfaceSpecifier, this.OperatorKeyword, this.Type, this.ParameterList, this.Body, this.ExpressionBody, semicolonToken); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new ConversionOperatorDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new ConversionOperatorDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); internal override BaseMethodDeclarationSyntax AddParameterListParametersCore(params ParameterSyntax[] items) => AddParameterListParameters(items); public new ConversionOperatorDeclarationSyntax AddParameterListParameters(params ParameterSyntax[] items) => WithParameterList(this.ParameterList.WithParameters(this.ParameterList.Parameters.AddRange(items))); internal override BaseMethodDeclarationSyntax AddBodyAttributeListsCore(params AttributeListSyntax[] items) => AddBodyAttributeLists(items); public new ConversionOperatorDeclarationSyntax AddBodyAttributeLists(params AttributeListSyntax[] items) { var body = this.Body ?? SyntaxFactory.Block(); return WithBody(body.WithAttributeLists(body.AttributeLists.AddRange(items))); } internal override BaseMethodDeclarationSyntax AddBodyStatementsCore(params StatementSyntax[] items) => AddBodyStatements(items); public new ConversionOperatorDeclarationSyntax AddBodyStatements(params StatementSyntax[] items) { var body = this.Body ?? SyntaxFactory.Block(); return WithBody(body.WithStatements(body.Statements.AddRange(items))); } } /// <summary>Constructor declaration syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ConstructorDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class ConstructorDeclarationSyntax : BaseMethodDeclarationSyntax { private SyntaxNode? attributeLists; private ParameterListSyntax? parameterList; private ConstructorInitializerSyntax? initializer; private BlockSyntax? body; private ArrowExpressionClauseSyntax? expressionBody; internal ConstructorDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.ConstructorDeclarationSyntax)this.Green).identifier, GetChildPosition(2), GetChildIndex(2)); public override ParameterListSyntax ParameterList => GetRed(ref this.parameterList, 3)!; public ConstructorInitializerSyntax? Initializer => GetRed(ref this.initializer, 4); public override BlockSyntax? Body => GetRed(ref this.body, 5); public override ArrowExpressionClauseSyntax? ExpressionBody => GetRed(ref this.expressionBody, 6); /// <summary>Gets the optional semicolon token.</summary> public override SyntaxToken SemicolonToken { get { var slot = ((Syntax.InternalSyntax.ConstructorDeclarationSyntax)this.Green).semicolonToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(7), GetChildIndex(7)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 3 => GetRed(ref this.parameterList, 3)!, 4 => GetRed(ref this.initializer, 4), 5 => GetRed(ref this.body, 5), 6 => GetRed(ref this.expressionBody, 6), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 3 => this.parameterList, 4 => this.initializer, 5 => this.body, 6 => this.expressionBody, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitConstructorDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitConstructorDeclaration(this); public ConstructorDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken identifier, ParameterListSyntax parameterList, ConstructorInitializerSyntax? initializer, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || identifier != this.Identifier || parameterList != this.ParameterList || initializer != this.Initializer || body != this.Body || expressionBody != this.ExpressionBody || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.ConstructorDeclaration(attributeLists, modifiers, identifier, parameterList, initializer, body, expressionBody, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new ConstructorDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.Identifier, this.ParameterList, this.Initializer, this.Body, this.ExpressionBody, this.SemicolonToken); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new ConstructorDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.Identifier, this.ParameterList, this.Initializer, this.Body, this.ExpressionBody, this.SemicolonToken); public ConstructorDeclarationSyntax WithIdentifier(SyntaxToken identifier) => Update(this.AttributeLists, this.Modifiers, identifier, this.ParameterList, this.Initializer, this.Body, this.ExpressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithParameterListCore(ParameterListSyntax parameterList) => WithParameterList(parameterList); public new ConstructorDeclarationSyntax WithParameterList(ParameterListSyntax parameterList) => Update(this.AttributeLists, this.Modifiers, this.Identifier, parameterList, this.Initializer, this.Body, this.ExpressionBody, this.SemicolonToken); public ConstructorDeclarationSyntax WithInitializer(ConstructorInitializerSyntax? initializer) => Update(this.AttributeLists, this.Modifiers, this.Identifier, this.ParameterList, initializer, this.Body, this.ExpressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithBodyCore(BlockSyntax? body) => WithBody(body); public new ConstructorDeclarationSyntax WithBody(BlockSyntax? body) => Update(this.AttributeLists, this.Modifiers, this.Identifier, this.ParameterList, this.Initializer, body, this.ExpressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithExpressionBodyCore(ArrowExpressionClauseSyntax? expressionBody) => WithExpressionBody(expressionBody); public new ConstructorDeclarationSyntax WithExpressionBody(ArrowExpressionClauseSyntax? expressionBody) => Update(this.AttributeLists, this.Modifiers, this.Identifier, this.ParameterList, this.Initializer, this.Body, expressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken) => WithSemicolonToken(semicolonToken); public new ConstructorDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.Identifier, this.ParameterList, this.Initializer, this.Body, this.ExpressionBody, semicolonToken); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new ConstructorDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new ConstructorDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); internal override BaseMethodDeclarationSyntax AddParameterListParametersCore(params ParameterSyntax[] items) => AddParameterListParameters(items); public new ConstructorDeclarationSyntax AddParameterListParameters(params ParameterSyntax[] items) => WithParameterList(this.ParameterList.WithParameters(this.ParameterList.Parameters.AddRange(items))); internal override BaseMethodDeclarationSyntax AddBodyAttributeListsCore(params AttributeListSyntax[] items) => AddBodyAttributeLists(items); public new ConstructorDeclarationSyntax AddBodyAttributeLists(params AttributeListSyntax[] items) { var body = this.Body ?? SyntaxFactory.Block(); return WithBody(body.WithAttributeLists(body.AttributeLists.AddRange(items))); } internal override BaseMethodDeclarationSyntax AddBodyStatementsCore(params StatementSyntax[] items) => AddBodyStatements(items); public new ConstructorDeclarationSyntax AddBodyStatements(params StatementSyntax[] items) { var body = this.Body ?? SyntaxFactory.Block(); return WithBody(body.WithStatements(body.Statements.AddRange(items))); } } /// <summary>Constructor initializer syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.BaseConstructorInitializer"/></description></item> /// <item><description><see cref="SyntaxKind.ThisConstructorInitializer"/></description></item> /// </list> /// </remarks> public sealed partial class ConstructorInitializerSyntax : CSharpSyntaxNode { private ArgumentListSyntax? argumentList; internal ConstructorInitializerSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the colon token.</summary> public SyntaxToken ColonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ConstructorInitializerSyntax)this.Green).colonToken, Position, 0); /// <summary>Gets the "this" or "base" keyword.</summary> public SyntaxToken ThisOrBaseKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ConstructorInitializerSyntax)this.Green).thisOrBaseKeyword, GetChildPosition(1), GetChildIndex(1)); public ArgumentListSyntax ArgumentList => GetRed(ref this.argumentList, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 2 ? GetRed(ref this.argumentList, 2)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 2 ? this.argumentList : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitConstructorInitializer(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitConstructorInitializer(this); public ConstructorInitializerSyntax Update(SyntaxToken colonToken, SyntaxToken thisOrBaseKeyword, ArgumentListSyntax argumentList) { if (colonToken != this.ColonToken || thisOrBaseKeyword != this.ThisOrBaseKeyword || argumentList != this.ArgumentList) { var newNode = SyntaxFactory.ConstructorInitializer(this.Kind(), colonToken, thisOrBaseKeyword, argumentList); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ConstructorInitializerSyntax WithColonToken(SyntaxToken colonToken) => Update(colonToken, this.ThisOrBaseKeyword, this.ArgumentList); public ConstructorInitializerSyntax WithThisOrBaseKeyword(SyntaxToken thisOrBaseKeyword) => Update(this.ColonToken, thisOrBaseKeyword, this.ArgumentList); public ConstructorInitializerSyntax WithArgumentList(ArgumentListSyntax argumentList) => Update(this.ColonToken, this.ThisOrBaseKeyword, argumentList); public ConstructorInitializerSyntax AddArgumentListArguments(params ArgumentSyntax[] items) => WithArgumentList(this.ArgumentList.WithArguments(this.ArgumentList.Arguments.AddRange(items))); } /// <summary>Destructor declaration syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.DestructorDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class DestructorDeclarationSyntax : BaseMethodDeclarationSyntax { private SyntaxNode? attributeLists; private ParameterListSyntax? parameterList; private BlockSyntax? body; private ArrowExpressionClauseSyntax? expressionBody; internal DestructorDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } /// <summary>Gets the tilde token.</summary> public SyntaxToken TildeToken => new SyntaxToken(this, ((Syntax.InternalSyntax.DestructorDeclarationSyntax)this.Green).tildeToken, GetChildPosition(2), GetChildIndex(2)); /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.DestructorDeclarationSyntax)this.Green).identifier, GetChildPosition(3), GetChildIndex(3)); public override ParameterListSyntax ParameterList => GetRed(ref this.parameterList, 4)!; public override BlockSyntax? Body => GetRed(ref this.body, 5); public override ArrowExpressionClauseSyntax? ExpressionBody => GetRed(ref this.expressionBody, 6); /// <summary>Gets the optional semicolon token.</summary> public override SyntaxToken SemicolonToken { get { var slot = ((Syntax.InternalSyntax.DestructorDeclarationSyntax)this.Green).semicolonToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(7), GetChildIndex(7)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 4 => GetRed(ref this.parameterList, 4)!, 5 => GetRed(ref this.body, 5), 6 => GetRed(ref this.expressionBody, 6), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 4 => this.parameterList, 5 => this.body, 6 => this.expressionBody, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitDestructorDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitDestructorDeclaration(this); public DestructorDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken tildeToken, SyntaxToken identifier, ParameterListSyntax parameterList, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || tildeToken != this.TildeToken || identifier != this.Identifier || parameterList != this.ParameterList || body != this.Body || expressionBody != this.ExpressionBody || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.DestructorDeclaration(attributeLists, modifiers, tildeToken, identifier, parameterList, body, expressionBody, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new DestructorDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.TildeToken, this.Identifier, this.ParameterList, this.Body, this.ExpressionBody, this.SemicolonToken); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new DestructorDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.TildeToken, this.Identifier, this.ParameterList, this.Body, this.ExpressionBody, this.SemicolonToken); public DestructorDeclarationSyntax WithTildeToken(SyntaxToken tildeToken) => Update(this.AttributeLists, this.Modifiers, tildeToken, this.Identifier, this.ParameterList, this.Body, this.ExpressionBody, this.SemicolonToken); public DestructorDeclarationSyntax WithIdentifier(SyntaxToken identifier) => Update(this.AttributeLists, this.Modifiers, this.TildeToken, identifier, this.ParameterList, this.Body, this.ExpressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithParameterListCore(ParameterListSyntax parameterList) => WithParameterList(parameterList); public new DestructorDeclarationSyntax WithParameterList(ParameterListSyntax parameterList) => Update(this.AttributeLists, this.Modifiers, this.TildeToken, this.Identifier, parameterList, this.Body, this.ExpressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithBodyCore(BlockSyntax? body) => WithBody(body); public new DestructorDeclarationSyntax WithBody(BlockSyntax? body) => Update(this.AttributeLists, this.Modifiers, this.TildeToken, this.Identifier, this.ParameterList, body, this.ExpressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithExpressionBodyCore(ArrowExpressionClauseSyntax? expressionBody) => WithExpressionBody(expressionBody); public new DestructorDeclarationSyntax WithExpressionBody(ArrowExpressionClauseSyntax? expressionBody) => Update(this.AttributeLists, this.Modifiers, this.TildeToken, this.Identifier, this.ParameterList, this.Body, expressionBody, this.SemicolonToken); internal override BaseMethodDeclarationSyntax WithSemicolonTokenCore(SyntaxToken semicolonToken) => WithSemicolonToken(semicolonToken); public new DestructorDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.TildeToken, this.Identifier, this.ParameterList, this.Body, this.ExpressionBody, semicolonToken); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new DestructorDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new DestructorDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); internal override BaseMethodDeclarationSyntax AddParameterListParametersCore(params ParameterSyntax[] items) => AddParameterListParameters(items); public new DestructorDeclarationSyntax AddParameterListParameters(params ParameterSyntax[] items) => WithParameterList(this.ParameterList.WithParameters(this.ParameterList.Parameters.AddRange(items))); internal override BaseMethodDeclarationSyntax AddBodyAttributeListsCore(params AttributeListSyntax[] items) => AddBodyAttributeLists(items); public new DestructorDeclarationSyntax AddBodyAttributeLists(params AttributeListSyntax[] items) { var body = this.Body ?? SyntaxFactory.Block(); return WithBody(body.WithAttributeLists(body.AttributeLists.AddRange(items))); } internal override BaseMethodDeclarationSyntax AddBodyStatementsCore(params StatementSyntax[] items) => AddBodyStatements(items); public new DestructorDeclarationSyntax AddBodyStatements(params StatementSyntax[] items) { var body = this.Body ?? SyntaxFactory.Block(); return WithBody(body.WithStatements(body.Statements.AddRange(items))); } } /// <summary>Base type for property declaration syntax.</summary> public abstract partial class BasePropertyDeclarationSyntax : MemberDeclarationSyntax { internal BasePropertyDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the type syntax.</summary> public abstract TypeSyntax Type { get; } public BasePropertyDeclarationSyntax WithType(TypeSyntax type) => WithTypeCore(type); internal abstract BasePropertyDeclarationSyntax WithTypeCore(TypeSyntax type); /// <summary>Gets the optional explicit interface specifier.</summary> public abstract ExplicitInterfaceSpecifierSyntax? ExplicitInterfaceSpecifier { get; } public BasePropertyDeclarationSyntax WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier) => WithExplicitInterfaceSpecifierCore(explicitInterfaceSpecifier); internal abstract BasePropertyDeclarationSyntax WithExplicitInterfaceSpecifierCore(ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier); public abstract AccessorListSyntax? AccessorList { get; } public BasePropertyDeclarationSyntax WithAccessorList(AccessorListSyntax? accessorList) => WithAccessorListCore(accessorList); internal abstract BasePropertyDeclarationSyntax WithAccessorListCore(AccessorListSyntax? accessorList); public BasePropertyDeclarationSyntax AddAccessorListAccessors(params AccessorDeclarationSyntax[] items) => AddAccessorListAccessorsCore(items); internal abstract BasePropertyDeclarationSyntax AddAccessorListAccessorsCore(params AccessorDeclarationSyntax[] items); public new BasePropertyDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => (BasePropertyDeclarationSyntax)WithAttributeListsCore(attributeLists); public new BasePropertyDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => (BasePropertyDeclarationSyntax)WithModifiersCore(modifiers); public new BasePropertyDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => (BasePropertyDeclarationSyntax)AddAttributeListsCore(items); public new BasePropertyDeclarationSyntax AddModifiers(params SyntaxToken[] items) => (BasePropertyDeclarationSyntax)AddModifiersCore(items); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.PropertyDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class PropertyDeclarationSyntax : BasePropertyDeclarationSyntax { private SyntaxNode? attributeLists; private TypeSyntax? type; private ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier; private AccessorListSyntax? accessorList; private ArrowExpressionClauseSyntax? expressionBody; private EqualsValueClauseSyntax? initializer; internal PropertyDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public override TypeSyntax Type => GetRed(ref this.type, 2)!; public override ExplicitInterfaceSpecifierSyntax? ExplicitInterfaceSpecifier => GetRed(ref this.explicitInterfaceSpecifier, 3); /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.PropertyDeclarationSyntax)this.Green).identifier, GetChildPosition(4), GetChildIndex(4)); public override AccessorListSyntax? AccessorList => GetRed(ref this.accessorList, 5); public ArrowExpressionClauseSyntax? ExpressionBody => GetRed(ref this.expressionBody, 6); public EqualsValueClauseSyntax? Initializer => GetRed(ref this.initializer, 7); public SyntaxToken SemicolonToken { get { var slot = ((Syntax.InternalSyntax.PropertyDeclarationSyntax)this.Green).semicolonToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(8), GetChildIndex(8)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.type, 2)!, 3 => GetRed(ref this.explicitInterfaceSpecifier, 3), 5 => GetRed(ref this.accessorList, 5), 6 => GetRed(ref this.expressionBody, 6), 7 => GetRed(ref this.initializer, 7), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.type, 3 => this.explicitInterfaceSpecifier, 5 => this.accessorList, 6 => this.expressionBody, 7 => this.initializer, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitPropertyDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitPropertyDeclaration(this); public PropertyDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken identifier, AccessorListSyntax? accessorList, ArrowExpressionClauseSyntax? expressionBody, EqualsValueClauseSyntax? initializer, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || type != this.Type || explicitInterfaceSpecifier != this.ExplicitInterfaceSpecifier || identifier != this.Identifier || accessorList != this.AccessorList || expressionBody != this.ExpressionBody || initializer != this.Initializer || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.PropertyDeclaration(attributeLists, modifiers, type, explicitInterfaceSpecifier, identifier, accessorList, expressionBody, initializer, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new PropertyDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.Type, this.ExplicitInterfaceSpecifier, this.Identifier, this.AccessorList, this.ExpressionBody, this.Initializer, this.SemicolonToken); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new PropertyDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.Type, this.ExplicitInterfaceSpecifier, this.Identifier, this.AccessorList, this.ExpressionBody, this.Initializer, this.SemicolonToken); internal override BasePropertyDeclarationSyntax WithTypeCore(TypeSyntax type) => WithType(type); public new PropertyDeclarationSyntax WithType(TypeSyntax type) => Update(this.AttributeLists, this.Modifiers, type, this.ExplicitInterfaceSpecifier, this.Identifier, this.AccessorList, this.ExpressionBody, this.Initializer, this.SemicolonToken); internal override BasePropertyDeclarationSyntax WithExplicitInterfaceSpecifierCore(ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier) => WithExplicitInterfaceSpecifier(explicitInterfaceSpecifier); public new PropertyDeclarationSyntax WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier) => Update(this.AttributeLists, this.Modifiers, this.Type, explicitInterfaceSpecifier, this.Identifier, this.AccessorList, this.ExpressionBody, this.Initializer, this.SemicolonToken); public PropertyDeclarationSyntax WithIdentifier(SyntaxToken identifier) => Update(this.AttributeLists, this.Modifiers, this.Type, this.ExplicitInterfaceSpecifier, identifier, this.AccessorList, this.ExpressionBody, this.Initializer, this.SemicolonToken); internal override BasePropertyDeclarationSyntax WithAccessorListCore(AccessorListSyntax? accessorList) => WithAccessorList(accessorList); public new PropertyDeclarationSyntax WithAccessorList(AccessorListSyntax? accessorList) => Update(this.AttributeLists, this.Modifiers, this.Type, this.ExplicitInterfaceSpecifier, this.Identifier, accessorList, this.ExpressionBody, this.Initializer, this.SemicolonToken); public PropertyDeclarationSyntax WithExpressionBody(ArrowExpressionClauseSyntax? expressionBody) => Update(this.AttributeLists, this.Modifiers, this.Type, this.ExplicitInterfaceSpecifier, this.Identifier, this.AccessorList, expressionBody, this.Initializer, this.SemicolonToken); public PropertyDeclarationSyntax WithInitializer(EqualsValueClauseSyntax? initializer) => Update(this.AttributeLists, this.Modifiers, this.Type, this.ExplicitInterfaceSpecifier, this.Identifier, this.AccessorList, this.ExpressionBody, initializer, this.SemicolonToken); public PropertyDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.Type, this.ExplicitInterfaceSpecifier, this.Identifier, this.AccessorList, this.ExpressionBody, this.Initializer, semicolonToken); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new PropertyDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new PropertyDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); internal override BasePropertyDeclarationSyntax AddAccessorListAccessorsCore(params AccessorDeclarationSyntax[] items) => AddAccessorListAccessors(items); public new PropertyDeclarationSyntax AddAccessorListAccessors(params AccessorDeclarationSyntax[] items) { var accessorList = this.AccessorList ?? SyntaxFactory.AccessorList(); return WithAccessorList(accessorList.WithAccessors(accessorList.Accessors.AddRange(items))); } } /// <summary>The syntax for the expression body of an expression-bodied member.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ArrowExpressionClause"/></description></item> /// </list> /// </remarks> public sealed partial class ArrowExpressionClauseSyntax : CSharpSyntaxNode { private ExpressionSyntax? expression; internal ArrowExpressionClauseSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken ArrowToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ArrowExpressionClauseSyntax)this.Green).arrowToken, Position, 0); public ExpressionSyntax Expression => GetRed(ref this.expression, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.expression, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.expression : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitArrowExpressionClause(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitArrowExpressionClause(this); public ArrowExpressionClauseSyntax Update(SyntaxToken arrowToken, ExpressionSyntax expression) { if (arrowToken != this.ArrowToken || expression != this.Expression) { var newNode = SyntaxFactory.ArrowExpressionClause(arrowToken, expression); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ArrowExpressionClauseSyntax WithArrowToken(SyntaxToken arrowToken) => Update(arrowToken, this.Expression); public ArrowExpressionClauseSyntax WithExpression(ExpressionSyntax expression) => Update(this.ArrowToken, expression); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.EventDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class EventDeclarationSyntax : BasePropertyDeclarationSyntax { private SyntaxNode? attributeLists; private TypeSyntax? type; private ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier; private AccessorListSyntax? accessorList; internal EventDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public SyntaxToken EventKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.EventDeclarationSyntax)this.Green).eventKeyword, GetChildPosition(2), GetChildIndex(2)); public override TypeSyntax Type => GetRed(ref this.type, 3)!; public override ExplicitInterfaceSpecifierSyntax? ExplicitInterfaceSpecifier => GetRed(ref this.explicitInterfaceSpecifier, 4); /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.EventDeclarationSyntax)this.Green).identifier, GetChildPosition(5), GetChildIndex(5)); public override AccessorListSyntax? AccessorList => GetRed(ref this.accessorList, 6); public SyntaxToken SemicolonToken { get { var slot = ((Syntax.InternalSyntax.EventDeclarationSyntax)this.Green).semicolonToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(7), GetChildIndex(7)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 3 => GetRed(ref this.type, 3)!, 4 => GetRed(ref this.explicitInterfaceSpecifier, 4), 6 => GetRed(ref this.accessorList, 6), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 3 => this.type, 4 => this.explicitInterfaceSpecifier, 6 => this.accessorList, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitEventDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitEventDeclaration(this); public EventDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken eventKeyword, TypeSyntax type, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken identifier, AccessorListSyntax? accessorList, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || eventKeyword != this.EventKeyword || type != this.Type || explicitInterfaceSpecifier != this.ExplicitInterfaceSpecifier || identifier != this.Identifier || accessorList != this.AccessorList || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.EventDeclaration(attributeLists, modifiers, eventKeyword, type, explicitInterfaceSpecifier, identifier, accessorList, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new EventDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.EventKeyword, this.Type, this.ExplicitInterfaceSpecifier, this.Identifier, this.AccessorList, this.SemicolonToken); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new EventDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.EventKeyword, this.Type, this.ExplicitInterfaceSpecifier, this.Identifier, this.AccessorList, this.SemicolonToken); public EventDeclarationSyntax WithEventKeyword(SyntaxToken eventKeyword) => Update(this.AttributeLists, this.Modifiers, eventKeyword, this.Type, this.ExplicitInterfaceSpecifier, this.Identifier, this.AccessorList, this.SemicolonToken); internal override BasePropertyDeclarationSyntax WithTypeCore(TypeSyntax type) => WithType(type); public new EventDeclarationSyntax WithType(TypeSyntax type) => Update(this.AttributeLists, this.Modifiers, this.EventKeyword, type, this.ExplicitInterfaceSpecifier, this.Identifier, this.AccessorList, this.SemicolonToken); internal override BasePropertyDeclarationSyntax WithExplicitInterfaceSpecifierCore(ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier) => WithExplicitInterfaceSpecifier(explicitInterfaceSpecifier); public new EventDeclarationSyntax WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier) => Update(this.AttributeLists, this.Modifiers, this.EventKeyword, this.Type, explicitInterfaceSpecifier, this.Identifier, this.AccessorList, this.SemicolonToken); public EventDeclarationSyntax WithIdentifier(SyntaxToken identifier) => Update(this.AttributeLists, this.Modifiers, this.EventKeyword, this.Type, this.ExplicitInterfaceSpecifier, identifier, this.AccessorList, this.SemicolonToken); internal override BasePropertyDeclarationSyntax WithAccessorListCore(AccessorListSyntax? accessorList) => WithAccessorList(accessorList); public new EventDeclarationSyntax WithAccessorList(AccessorListSyntax? accessorList) => Update(this.AttributeLists, this.Modifiers, this.EventKeyword, this.Type, this.ExplicitInterfaceSpecifier, this.Identifier, accessorList, this.SemicolonToken); public EventDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.EventKeyword, this.Type, this.ExplicitInterfaceSpecifier, this.Identifier, this.AccessorList, semicolonToken); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new EventDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new EventDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); internal override BasePropertyDeclarationSyntax AddAccessorListAccessorsCore(params AccessorDeclarationSyntax[] items) => AddAccessorListAccessors(items); public new EventDeclarationSyntax AddAccessorListAccessors(params AccessorDeclarationSyntax[] items) { var accessorList = this.AccessorList ?? SyntaxFactory.AccessorList(); return WithAccessorList(accessorList.WithAccessors(accessorList.Accessors.AddRange(items))); } } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.IndexerDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class IndexerDeclarationSyntax : BasePropertyDeclarationSyntax { private SyntaxNode? attributeLists; private TypeSyntax? type; private ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier; private BracketedParameterListSyntax? parameterList; private AccessorListSyntax? accessorList; private ArrowExpressionClauseSyntax? expressionBody; internal IndexerDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public override TypeSyntax Type => GetRed(ref this.type, 2)!; public override ExplicitInterfaceSpecifierSyntax? ExplicitInterfaceSpecifier => GetRed(ref this.explicitInterfaceSpecifier, 3); public SyntaxToken ThisKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.IndexerDeclarationSyntax)this.Green).thisKeyword, GetChildPosition(4), GetChildIndex(4)); /// <summary>Gets the parameter list.</summary> public BracketedParameterListSyntax ParameterList => GetRed(ref this.parameterList, 5)!; public override AccessorListSyntax? AccessorList => GetRed(ref this.accessorList, 6); public ArrowExpressionClauseSyntax? ExpressionBody => GetRed(ref this.expressionBody, 7); public SyntaxToken SemicolonToken { get { var slot = ((Syntax.InternalSyntax.IndexerDeclarationSyntax)this.Green).semicolonToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(8), GetChildIndex(8)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.type, 2)!, 3 => GetRed(ref this.explicitInterfaceSpecifier, 3), 5 => GetRed(ref this.parameterList, 5)!, 6 => GetRed(ref this.accessorList, 6), 7 => GetRed(ref this.expressionBody, 7), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.type, 3 => this.explicitInterfaceSpecifier, 5 => this.parameterList, 6 => this.accessorList, 7 => this.expressionBody, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitIndexerDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitIndexerDeclaration(this); public IndexerDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, TypeSyntax type, ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier, SyntaxToken thisKeyword, BracketedParameterListSyntax parameterList, AccessorListSyntax? accessorList, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || type != this.Type || explicitInterfaceSpecifier != this.ExplicitInterfaceSpecifier || thisKeyword != this.ThisKeyword || parameterList != this.ParameterList || accessorList != this.AccessorList || expressionBody != this.ExpressionBody || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.IndexerDeclaration(attributeLists, modifiers, type, explicitInterfaceSpecifier, thisKeyword, parameterList, accessorList, expressionBody, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new IndexerDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.Type, this.ExplicitInterfaceSpecifier, this.ThisKeyword, this.ParameterList, this.AccessorList, this.ExpressionBody, this.SemicolonToken); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new IndexerDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.Type, this.ExplicitInterfaceSpecifier, this.ThisKeyword, this.ParameterList, this.AccessorList, this.ExpressionBody, this.SemicolonToken); internal override BasePropertyDeclarationSyntax WithTypeCore(TypeSyntax type) => WithType(type); public new IndexerDeclarationSyntax WithType(TypeSyntax type) => Update(this.AttributeLists, this.Modifiers, type, this.ExplicitInterfaceSpecifier, this.ThisKeyword, this.ParameterList, this.AccessorList, this.ExpressionBody, this.SemicolonToken); internal override BasePropertyDeclarationSyntax WithExplicitInterfaceSpecifierCore(ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier) => WithExplicitInterfaceSpecifier(explicitInterfaceSpecifier); public new IndexerDeclarationSyntax WithExplicitInterfaceSpecifier(ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier) => Update(this.AttributeLists, this.Modifiers, this.Type, explicitInterfaceSpecifier, this.ThisKeyword, this.ParameterList, this.AccessorList, this.ExpressionBody, this.SemicolonToken); public IndexerDeclarationSyntax WithThisKeyword(SyntaxToken thisKeyword) => Update(this.AttributeLists, this.Modifiers, this.Type, this.ExplicitInterfaceSpecifier, thisKeyword, this.ParameterList, this.AccessorList, this.ExpressionBody, this.SemicolonToken); public IndexerDeclarationSyntax WithParameterList(BracketedParameterListSyntax parameterList) => Update(this.AttributeLists, this.Modifiers, this.Type, this.ExplicitInterfaceSpecifier, this.ThisKeyword, parameterList, this.AccessorList, this.ExpressionBody, this.SemicolonToken); internal override BasePropertyDeclarationSyntax WithAccessorListCore(AccessorListSyntax? accessorList) => WithAccessorList(accessorList); public new IndexerDeclarationSyntax WithAccessorList(AccessorListSyntax? accessorList) => Update(this.AttributeLists, this.Modifiers, this.Type, this.ExplicitInterfaceSpecifier, this.ThisKeyword, this.ParameterList, accessorList, this.ExpressionBody, this.SemicolonToken); public IndexerDeclarationSyntax WithExpressionBody(ArrowExpressionClauseSyntax? expressionBody) => Update(this.AttributeLists, this.Modifiers, this.Type, this.ExplicitInterfaceSpecifier, this.ThisKeyword, this.ParameterList, this.AccessorList, expressionBody, this.SemicolonToken); public IndexerDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.Type, this.ExplicitInterfaceSpecifier, this.ThisKeyword, this.ParameterList, this.AccessorList, this.ExpressionBody, semicolonToken); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new IndexerDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new IndexerDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); public IndexerDeclarationSyntax AddParameterListParameters(params ParameterSyntax[] items) => WithParameterList(this.ParameterList.WithParameters(this.ParameterList.Parameters.AddRange(items))); internal override BasePropertyDeclarationSyntax AddAccessorListAccessorsCore(params AccessorDeclarationSyntax[] items) => AddAccessorListAccessors(items); public new IndexerDeclarationSyntax AddAccessorListAccessors(params AccessorDeclarationSyntax[] items) { var accessorList = this.AccessorList ?? SyntaxFactory.AccessorList(); return WithAccessorList(accessorList.WithAccessors(accessorList.Accessors.AddRange(items))); } } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.AccessorList"/></description></item> /// </list> /// </remarks> public sealed partial class AccessorListSyntax : CSharpSyntaxNode { private SyntaxNode? accessors; internal AccessorListSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken OpenBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.AccessorListSyntax)this.Green).openBraceToken, Position, 0); public SyntaxList<AccessorDeclarationSyntax> Accessors => new SyntaxList<AccessorDeclarationSyntax>(GetRed(ref this.accessors, 1)); public SyntaxToken CloseBraceToken => new SyntaxToken(this, ((Syntax.InternalSyntax.AccessorListSyntax)this.Green).closeBraceToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.accessors, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.accessors : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitAccessorList(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitAccessorList(this); public AccessorListSyntax Update(SyntaxToken openBraceToken, SyntaxList<AccessorDeclarationSyntax> accessors, SyntaxToken closeBraceToken) { if (openBraceToken != this.OpenBraceToken || accessors != this.Accessors || closeBraceToken != this.CloseBraceToken) { var newNode = SyntaxFactory.AccessorList(openBraceToken, accessors, closeBraceToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public AccessorListSyntax WithOpenBraceToken(SyntaxToken openBraceToken) => Update(openBraceToken, this.Accessors, this.CloseBraceToken); public AccessorListSyntax WithAccessors(SyntaxList<AccessorDeclarationSyntax> accessors) => Update(this.OpenBraceToken, accessors, this.CloseBraceToken); public AccessorListSyntax WithCloseBraceToken(SyntaxToken closeBraceToken) => Update(this.OpenBraceToken, this.Accessors, closeBraceToken); public AccessorListSyntax AddAccessors(params AccessorDeclarationSyntax[] items) => WithAccessors(this.Accessors.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.GetAccessorDeclaration"/></description></item> /// <item><description><see cref="SyntaxKind.SetAccessorDeclaration"/></description></item> /// <item><description><see cref="SyntaxKind.InitAccessorDeclaration"/></description></item> /// <item><description><see cref="SyntaxKind.AddAccessorDeclaration"/></description></item> /// <item><description><see cref="SyntaxKind.RemoveAccessorDeclaration"/></description></item> /// <item><description><see cref="SyntaxKind.UnknownAccessorDeclaration"/></description></item> /// </list> /// </remarks> public sealed partial class AccessorDeclarationSyntax : CSharpSyntaxNode { private SyntaxNode? attributeLists; private BlockSyntax? body; private ArrowExpressionClauseSyntax? expressionBody; internal AccessorDeclarationSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the attribute declaration list.</summary> public SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); /// <summary>Gets the modifier list.</summary> public SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } /// <summary>Gets the keyword token, or identifier if an erroneous accessor declaration.</summary> public SyntaxToken Keyword => new SyntaxToken(this, ((Syntax.InternalSyntax.AccessorDeclarationSyntax)this.Green).keyword, GetChildPosition(2), GetChildIndex(2)); /// <summary>Gets the optional body block which may be empty, but it is null if there are no braces.</summary> public BlockSyntax? Body => GetRed(ref this.body, 3); /// <summary>Gets the optional expression body.</summary> public ArrowExpressionClauseSyntax? ExpressionBody => GetRed(ref this.expressionBody, 4); /// <summary>Gets the optional semicolon token.</summary> public SyntaxToken SemicolonToken { get { var slot = ((Syntax.InternalSyntax.AccessorDeclarationSyntax)this.Green).semicolonToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(5), GetChildIndex(5)) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 3 => GetRed(ref this.body, 3), 4 => GetRed(ref this.expressionBody, 4), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 3 => this.body, 4 => this.expressionBody, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitAccessorDeclaration(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitAccessorDeclaration(this); public AccessorDeclarationSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, BlockSyntax? body, ArrowExpressionClauseSyntax? expressionBody, SyntaxToken semicolonToken) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || keyword != this.Keyword || body != this.Body || expressionBody != this.ExpressionBody || semicolonToken != this.SemicolonToken) { var newNode = SyntaxFactory.AccessorDeclaration(this.Kind(), attributeLists, modifiers, keyword, body, expressionBody, semicolonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public AccessorDeclarationSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.Keyword, this.Body, this.ExpressionBody, this.SemicolonToken); public AccessorDeclarationSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.Keyword, this.Body, this.ExpressionBody, this.SemicolonToken); public AccessorDeclarationSyntax WithKeyword(SyntaxToken keyword) => Update(this.AttributeLists, this.Modifiers, keyword, this.Body, this.ExpressionBody, this.SemicolonToken); public AccessorDeclarationSyntax WithBody(BlockSyntax? body) => Update(this.AttributeLists, this.Modifiers, this.Keyword, body, this.ExpressionBody, this.SemicolonToken); public AccessorDeclarationSyntax WithExpressionBody(ArrowExpressionClauseSyntax? expressionBody) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Body, expressionBody, this.SemicolonToken); public AccessorDeclarationSyntax WithSemicolonToken(SyntaxToken semicolonToken) => Update(this.AttributeLists, this.Modifiers, this.Keyword, this.Body, this.ExpressionBody, semicolonToken); public AccessorDeclarationSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); public AccessorDeclarationSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); public AccessorDeclarationSyntax AddBodyAttributeLists(params AttributeListSyntax[] items) { var body = this.Body ?? SyntaxFactory.Block(); return WithBody(body.WithAttributeLists(body.AttributeLists.AddRange(items))); } public AccessorDeclarationSyntax AddBodyStatements(params StatementSyntax[] items) { var body = this.Body ?? SyntaxFactory.Block(); return WithBody(body.WithStatements(body.Statements.AddRange(items))); } } /// <summary>Base type for parameter list syntax.</summary> public abstract partial class BaseParameterListSyntax : CSharpSyntaxNode { internal BaseParameterListSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the parameter list.</summary> public abstract SeparatedSyntaxList<ParameterSyntax> Parameters { get; } public BaseParameterListSyntax WithParameters(SeparatedSyntaxList<ParameterSyntax> parameters) => WithParametersCore(parameters); internal abstract BaseParameterListSyntax WithParametersCore(SeparatedSyntaxList<ParameterSyntax> parameters); public BaseParameterListSyntax AddParameters(params ParameterSyntax[] items) => AddParametersCore(items); internal abstract BaseParameterListSyntax AddParametersCore(params ParameterSyntax[] items); } /// <summary>Parameter list syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ParameterList"/></description></item> /// </list> /// </remarks> public sealed partial class ParameterListSyntax : BaseParameterListSyntax { private SyntaxNode? parameters; internal ParameterListSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the open paren token.</summary> public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ParameterListSyntax)this.Green).openParenToken, Position, 0); public override SeparatedSyntaxList<ParameterSyntax> Parameters { get { var red = GetRed(ref this.parameters, 1); return red != null ? new SeparatedSyntaxList<ParameterSyntax>(red, GetChildIndex(1)) : default; } } /// <summary>Gets the close paren token.</summary> public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ParameterListSyntax)this.Green).closeParenToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.parameters, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.parameters : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitParameterList(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitParameterList(this); public ParameterListSyntax Update(SyntaxToken openParenToken, SeparatedSyntaxList<ParameterSyntax> parameters, SyntaxToken closeParenToken) { if (openParenToken != this.OpenParenToken || parameters != this.Parameters || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.ParameterList(openParenToken, parameters, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ParameterListSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(openParenToken, this.Parameters, this.CloseParenToken); internal override BaseParameterListSyntax WithParametersCore(SeparatedSyntaxList<ParameterSyntax> parameters) => WithParameters(parameters); public new ParameterListSyntax WithParameters(SeparatedSyntaxList<ParameterSyntax> parameters) => Update(this.OpenParenToken, parameters, this.CloseParenToken); public ParameterListSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.OpenParenToken, this.Parameters, closeParenToken); internal override BaseParameterListSyntax AddParametersCore(params ParameterSyntax[] items) => AddParameters(items); public new ParameterListSyntax AddParameters(params ParameterSyntax[] items) => WithParameters(this.Parameters.AddRange(items)); } /// <summary>Parameter list syntax with surrounding brackets.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.BracketedParameterList"/></description></item> /// </list> /// </remarks> public sealed partial class BracketedParameterListSyntax : BaseParameterListSyntax { private SyntaxNode? parameters; internal BracketedParameterListSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the open bracket token.</summary> public SyntaxToken OpenBracketToken => new SyntaxToken(this, ((Syntax.InternalSyntax.BracketedParameterListSyntax)this.Green).openBracketToken, Position, 0); public override SeparatedSyntaxList<ParameterSyntax> Parameters { get { var red = GetRed(ref this.parameters, 1); return red != null ? new SeparatedSyntaxList<ParameterSyntax>(red, GetChildIndex(1)) : default; } } /// <summary>Gets the close bracket token.</summary> public SyntaxToken CloseBracketToken => new SyntaxToken(this, ((Syntax.InternalSyntax.BracketedParameterListSyntax)this.Green).closeBracketToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.parameters, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.parameters : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitBracketedParameterList(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitBracketedParameterList(this); public BracketedParameterListSyntax Update(SyntaxToken openBracketToken, SeparatedSyntaxList<ParameterSyntax> parameters, SyntaxToken closeBracketToken) { if (openBracketToken != this.OpenBracketToken || parameters != this.Parameters || closeBracketToken != this.CloseBracketToken) { var newNode = SyntaxFactory.BracketedParameterList(openBracketToken, parameters, closeBracketToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public BracketedParameterListSyntax WithOpenBracketToken(SyntaxToken openBracketToken) => Update(openBracketToken, this.Parameters, this.CloseBracketToken); internal override BaseParameterListSyntax WithParametersCore(SeparatedSyntaxList<ParameterSyntax> parameters) => WithParameters(parameters); public new BracketedParameterListSyntax WithParameters(SeparatedSyntaxList<ParameterSyntax> parameters) => Update(this.OpenBracketToken, parameters, this.CloseBracketToken); public BracketedParameterListSyntax WithCloseBracketToken(SyntaxToken closeBracketToken) => Update(this.OpenBracketToken, this.Parameters, closeBracketToken); internal override BaseParameterListSyntax AddParametersCore(params ParameterSyntax[] items) => AddParameters(items); public new BracketedParameterListSyntax AddParameters(params ParameterSyntax[] items) => WithParameters(this.Parameters.AddRange(items)); } /// <summary>Base parameter syntax.</summary> public abstract partial class BaseParameterSyntax : CSharpSyntaxNode { internal BaseParameterSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the attribute declaration list.</summary> public abstract SyntaxList<AttributeListSyntax> AttributeLists { get; } public BaseParameterSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeListsCore(attributeLists); internal abstract BaseParameterSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists); public BaseParameterSyntax AddAttributeLists(params AttributeListSyntax[] items) => AddAttributeListsCore(items); internal abstract BaseParameterSyntax AddAttributeListsCore(params AttributeListSyntax[] items); /// <summary>Gets the modifier list.</summary> public abstract SyntaxTokenList Modifiers { get; } public BaseParameterSyntax WithModifiers(SyntaxTokenList modifiers) => WithModifiersCore(modifiers); internal abstract BaseParameterSyntax WithModifiersCore(SyntaxTokenList modifiers); public BaseParameterSyntax AddModifiers(params SyntaxToken[] items) => AddModifiersCore(items); internal abstract BaseParameterSyntax AddModifiersCore(params SyntaxToken[] items); public abstract TypeSyntax? Type { get; } public BaseParameterSyntax WithType(TypeSyntax? type) => WithTypeCore(type); internal abstract BaseParameterSyntax WithTypeCore(TypeSyntax? type); } /// <summary>Parameter syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.Parameter"/></description></item> /// </list> /// </remarks> public sealed partial class ParameterSyntax : BaseParameterSyntax { private SyntaxNode? attributeLists; private TypeSyntax? type; private EqualsValueClauseSyntax? @default; internal ParameterSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the attribute declaration list.</summary> public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); /// <summary>Gets the modifier list.</summary> public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public override TypeSyntax? Type => GetRed(ref this.type, 2); /// <summary>Gets the identifier.</summary> public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.ParameterSyntax)this.Green).identifier, GetChildPosition(3), GetChildIndex(3)); public EqualsValueClauseSyntax? Default => GetRed(ref this.@default, 4); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.type, 2), 4 => GetRed(ref this.@default, 4), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.type, 4 => this.@default, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitParameter(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitParameter(this); public ParameterSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, TypeSyntax? type, SyntaxToken identifier, EqualsValueClauseSyntax? @default) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || type != this.Type || identifier != this.Identifier || @default != this.Default) { var newNode = SyntaxFactory.Parameter(attributeLists, modifiers, type, identifier, @default); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override BaseParameterSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new ParameterSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.Type, this.Identifier, this.Default); internal override BaseParameterSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new ParameterSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.Type, this.Identifier, this.Default); internal override BaseParameterSyntax WithTypeCore(TypeSyntax? type) => WithType(type); public new ParameterSyntax WithType(TypeSyntax? type) => Update(this.AttributeLists, this.Modifiers, type, this.Identifier, this.Default); public ParameterSyntax WithIdentifier(SyntaxToken identifier) => Update(this.AttributeLists, this.Modifiers, this.Type, identifier, this.Default); public ParameterSyntax WithDefault(EqualsValueClauseSyntax? @default) => Update(this.AttributeLists, this.Modifiers, this.Type, this.Identifier, @default); internal override BaseParameterSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new ParameterSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override BaseParameterSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new ParameterSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); } /// <summary>Parameter syntax.</summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.FunctionPointerParameter"/></description></item> /// </list> /// </remarks> public sealed partial class FunctionPointerParameterSyntax : BaseParameterSyntax { private SyntaxNode? attributeLists; private TypeSyntax? type; internal FunctionPointerParameterSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the attribute declaration list.</summary> public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); /// <summary>Gets the modifier list.</summary> public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public override TypeSyntax Type => GetRed(ref this.type, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.type, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.type, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitFunctionPointerParameter(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitFunctionPointerParameter(this); public FunctionPointerParameterSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, TypeSyntax type) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || type != this.Type) { var newNode = SyntaxFactory.FunctionPointerParameter(attributeLists, modifiers, type); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override BaseParameterSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new FunctionPointerParameterSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.Type); internal override BaseParameterSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new FunctionPointerParameterSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.Type); internal override BaseParameterSyntax WithTypeCore(TypeSyntax? type) => WithType(type ?? throw new ArgumentNullException(nameof(type))); public new FunctionPointerParameterSyntax WithType(TypeSyntax type) => Update(this.AttributeLists, this.Modifiers, type); internal override BaseParameterSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new FunctionPointerParameterSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override BaseParameterSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new FunctionPointerParameterSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.IncompleteMember"/></description></item> /// </list> /// </remarks> public sealed partial class IncompleteMemberSyntax : MemberDeclarationSyntax { private SyntaxNode? attributeLists; private TypeSyntax? type; internal IncompleteMemberSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxList<AttributeListSyntax> AttributeLists => new SyntaxList<AttributeListSyntax>(GetRed(ref this.attributeLists, 0)); public override SyntaxTokenList Modifiers { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public TypeSyntax? Type => GetRed(ref this.type, 2); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.attributeLists)!, 2 => GetRed(ref this.type, 2), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.attributeLists, 2 => this.type, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitIncompleteMember(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitIncompleteMember(this); public IncompleteMemberSyntax Update(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, TypeSyntax? type) { if (attributeLists != this.AttributeLists || modifiers != this.Modifiers || type != this.Type) { var newNode = SyntaxFactory.IncompleteMember(attributeLists, modifiers, type); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override MemberDeclarationSyntax WithAttributeListsCore(SyntaxList<AttributeListSyntax> attributeLists) => WithAttributeLists(attributeLists); public new IncompleteMemberSyntax WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) => Update(attributeLists, this.Modifiers, this.Type); internal override MemberDeclarationSyntax WithModifiersCore(SyntaxTokenList modifiers) => WithModifiers(modifiers); public new IncompleteMemberSyntax WithModifiers(SyntaxTokenList modifiers) => Update(this.AttributeLists, modifiers, this.Type); public IncompleteMemberSyntax WithType(TypeSyntax? type) => Update(this.AttributeLists, this.Modifiers, type); internal override MemberDeclarationSyntax AddAttributeListsCore(params AttributeListSyntax[] items) => AddAttributeLists(items); public new IncompleteMemberSyntax AddAttributeLists(params AttributeListSyntax[] items) => WithAttributeLists(this.AttributeLists.AddRange(items)); internal override MemberDeclarationSyntax AddModifiersCore(params SyntaxToken[] items) => AddModifiers(items); public new IncompleteMemberSyntax AddModifiers(params SyntaxToken[] items) => WithModifiers(this.Modifiers.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.SkippedTokensTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class SkippedTokensTriviaSyntax : StructuredTriviaSyntax { internal SkippedTokensTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxTokenList Tokens { get { var slot = this.Green.GetSlot(0); return slot != null ? new SyntaxTokenList(this, slot, Position, 0) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitSkippedTokensTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitSkippedTokensTrivia(this); public SkippedTokensTriviaSyntax Update(SyntaxTokenList tokens) { if (tokens != this.Tokens) { var newNode = SyntaxFactory.SkippedTokensTrivia(tokens); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public SkippedTokensTriviaSyntax WithTokens(SyntaxTokenList tokens) => Update(tokens); public SkippedTokensTriviaSyntax AddTokens(params SyntaxToken[] items) => WithTokens(this.Tokens.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.SingleLineDocumentationCommentTrivia"/></description></item> /// <item><description><see cref="SyntaxKind.MultiLineDocumentationCommentTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class DocumentationCommentTriviaSyntax : StructuredTriviaSyntax { private SyntaxNode? content; internal DocumentationCommentTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxList<XmlNodeSyntax> Content => new SyntaxList<XmlNodeSyntax>(GetRed(ref this.content, 0)); public SyntaxToken EndOfComment => new SyntaxToken(this, ((Syntax.InternalSyntax.DocumentationCommentTriviaSyntax)this.Green).endOfComment, GetChildPosition(1), GetChildIndex(1)); internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.content)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.content : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitDocumentationCommentTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitDocumentationCommentTrivia(this); public DocumentationCommentTriviaSyntax Update(SyntaxList<XmlNodeSyntax> content, SyntaxToken endOfComment) { if (content != this.Content || endOfComment != this.EndOfComment) { var newNode = SyntaxFactory.DocumentationCommentTrivia(this.Kind(), content, endOfComment); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public DocumentationCommentTriviaSyntax WithContent(SyntaxList<XmlNodeSyntax> content) => Update(content, this.EndOfComment); public DocumentationCommentTriviaSyntax WithEndOfComment(SyntaxToken endOfComment) => Update(this.Content, endOfComment); public DocumentationCommentTriviaSyntax AddContent(params XmlNodeSyntax[] items) => WithContent(this.Content.AddRange(items)); } /// <summary> /// A symbol referenced by a cref attribute (e.g. in a &lt;see&gt; or &lt;seealso&gt; documentation comment tag). /// For example, the M in &lt;see cref="M" /&gt;. /// </summary> public abstract partial class CrefSyntax : CSharpSyntaxNode { internal CrefSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } } /// <summary> /// A symbol reference that definitely refers to a type. /// For example, "int", "A::B", "A.B", "A&lt;T&gt;", but not "M()" (has parameter list) or "this" (indexer). /// NOTE: TypeCrefSyntax, QualifiedCrefSyntax, and MemberCrefSyntax overlap. The syntax in a TypeCrefSyntax /// will always be bound as type, so it's safer to use QualifiedCrefSyntax or MemberCrefSyntax if the symbol /// might be a non-type member. /// </summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.TypeCref"/></description></item> /// </list> /// </remarks> public sealed partial class TypeCrefSyntax : CrefSyntax { private TypeSyntax? type; internal TypeCrefSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public TypeSyntax Type => GetRedAtZero(ref this.type)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.type)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.type : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitTypeCref(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitTypeCref(this); public TypeCrefSyntax Update(TypeSyntax type) { if (type != this.Type) { var newNode = SyntaxFactory.TypeCref(type); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public TypeCrefSyntax WithType(TypeSyntax type) => Update(type); } /// <summary> /// A symbol reference to a type or non-type member that is qualified by an enclosing type or namespace. /// For example, cref="System.String.ToString()". /// NOTE: TypeCrefSyntax, QualifiedCrefSyntax, and MemberCrefSyntax overlap. The syntax in a TypeCrefSyntax /// will always be bound as type, so it's safer to use QualifiedCrefSyntax or MemberCrefSyntax if the symbol /// might be a non-type member. /// </summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.QualifiedCref"/></description></item> /// </list> /// </remarks> public sealed partial class QualifiedCrefSyntax : CrefSyntax { private TypeSyntax? container; private MemberCrefSyntax? member; internal QualifiedCrefSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public TypeSyntax Container => GetRedAtZero(ref this.container)!; public SyntaxToken DotToken => new SyntaxToken(this, ((Syntax.InternalSyntax.QualifiedCrefSyntax)this.Green).dotToken, GetChildPosition(1), GetChildIndex(1)); public MemberCrefSyntax Member => GetRed(ref this.member, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.container)!, 2 => GetRed(ref this.member, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.container, 2 => this.member, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitQualifiedCref(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitQualifiedCref(this); public QualifiedCrefSyntax Update(TypeSyntax container, SyntaxToken dotToken, MemberCrefSyntax member) { if (container != this.Container || dotToken != this.DotToken || member != this.Member) { var newNode = SyntaxFactory.QualifiedCref(container, dotToken, member); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public QualifiedCrefSyntax WithContainer(TypeSyntax container) => Update(container, this.DotToken, this.Member); public QualifiedCrefSyntax WithDotToken(SyntaxToken dotToken) => Update(this.Container, dotToken, this.Member); public QualifiedCrefSyntax WithMember(MemberCrefSyntax member) => Update(this.Container, this.DotToken, member); } /// <summary> /// The unqualified part of a CrefSyntax. /// For example, "ToString()" in "object.ToString()". /// NOTE: TypeCrefSyntax, QualifiedCrefSyntax, and MemberCrefSyntax overlap. The syntax in a TypeCrefSyntax /// will always be bound as type, so it's safer to use QualifiedCrefSyntax or MemberCrefSyntax if the symbol /// might be a non-type member. /// </summary> public abstract partial class MemberCrefSyntax : CrefSyntax { internal MemberCrefSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } } /// <summary> /// A MemberCrefSyntax specified by a name (an identifier, predefined type keyword, or an alias-qualified name, /// with an optional type parameter list) and an optional parameter list. /// For example, "M", "M&lt;T&gt;" or "M(int)". /// Also, "A::B()" or "string()". /// </summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.NameMemberCref"/></description></item> /// </list> /// </remarks> public sealed partial class NameMemberCrefSyntax : MemberCrefSyntax { private TypeSyntax? name; private CrefParameterListSyntax? parameters; internal NameMemberCrefSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public TypeSyntax Name => GetRedAtZero(ref this.name)!; public CrefParameterListSyntax? Parameters => GetRed(ref this.parameters, 1); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.name)!, 1 => GetRed(ref this.parameters, 1), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.name, 1 => this.parameters, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitNameMemberCref(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitNameMemberCref(this); public NameMemberCrefSyntax Update(TypeSyntax name, CrefParameterListSyntax? parameters) { if (name != this.Name || parameters != this.Parameters) { var newNode = SyntaxFactory.NameMemberCref(name, parameters); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public NameMemberCrefSyntax WithName(TypeSyntax name) => Update(name, this.Parameters); public NameMemberCrefSyntax WithParameters(CrefParameterListSyntax? parameters) => Update(this.Name, parameters); public NameMemberCrefSyntax AddParametersParameters(params CrefParameterSyntax[] items) { var parameters = this.Parameters ?? SyntaxFactory.CrefParameterList(); return WithParameters(parameters.WithParameters(parameters.Parameters.AddRange(items))); } } /// <summary> /// A MemberCrefSyntax specified by a this keyword and an optional parameter list. /// For example, "this" or "this[int]". /// </summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.IndexerMemberCref"/></description></item> /// </list> /// </remarks> public sealed partial class IndexerMemberCrefSyntax : MemberCrefSyntax { private CrefBracketedParameterListSyntax? parameters; internal IndexerMemberCrefSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken ThisKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.IndexerMemberCrefSyntax)this.Green).thisKeyword, Position, 0); public CrefBracketedParameterListSyntax? Parameters => GetRed(ref this.parameters, 1); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.parameters, 1) : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.parameters : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitIndexerMemberCref(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitIndexerMemberCref(this); public IndexerMemberCrefSyntax Update(SyntaxToken thisKeyword, CrefBracketedParameterListSyntax? parameters) { if (thisKeyword != this.ThisKeyword || parameters != this.Parameters) { var newNode = SyntaxFactory.IndexerMemberCref(thisKeyword, parameters); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public IndexerMemberCrefSyntax WithThisKeyword(SyntaxToken thisKeyword) => Update(thisKeyword, this.Parameters); public IndexerMemberCrefSyntax WithParameters(CrefBracketedParameterListSyntax? parameters) => Update(this.ThisKeyword, parameters); public IndexerMemberCrefSyntax AddParametersParameters(params CrefParameterSyntax[] items) { var parameters = this.Parameters ?? SyntaxFactory.CrefBracketedParameterList(); return WithParameters(parameters.WithParameters(parameters.Parameters.AddRange(items))); } } /// <summary> /// A MemberCrefSyntax specified by an operator keyword, an operator symbol and an optional parameter list. /// For example, "operator +" or "operator -[int]". /// NOTE: the operator must be overloadable. /// </summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.OperatorMemberCref"/></description></item> /// </list> /// </remarks> public sealed partial class OperatorMemberCrefSyntax : MemberCrefSyntax { private CrefParameterListSyntax? parameters; internal OperatorMemberCrefSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken OperatorKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.OperatorMemberCrefSyntax)this.Green).operatorKeyword, Position, 0); /// <summary>Gets the operator token.</summary> public SyntaxToken OperatorToken => new SyntaxToken(this, ((Syntax.InternalSyntax.OperatorMemberCrefSyntax)this.Green).operatorToken, GetChildPosition(1), GetChildIndex(1)); public CrefParameterListSyntax? Parameters => GetRed(ref this.parameters, 2); internal override SyntaxNode? GetNodeSlot(int index) => index == 2 ? GetRed(ref this.parameters, 2) : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 2 ? this.parameters : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitOperatorMemberCref(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitOperatorMemberCref(this); public OperatorMemberCrefSyntax Update(SyntaxToken operatorKeyword, SyntaxToken operatorToken, CrefParameterListSyntax? parameters) { if (operatorKeyword != this.OperatorKeyword || operatorToken != this.OperatorToken || parameters != this.Parameters) { var newNode = SyntaxFactory.OperatorMemberCref(operatorKeyword, operatorToken, parameters); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public OperatorMemberCrefSyntax WithOperatorKeyword(SyntaxToken operatorKeyword) => Update(operatorKeyword, this.OperatorToken, this.Parameters); public OperatorMemberCrefSyntax WithOperatorToken(SyntaxToken operatorToken) => Update(this.OperatorKeyword, operatorToken, this.Parameters); public OperatorMemberCrefSyntax WithParameters(CrefParameterListSyntax? parameters) => Update(this.OperatorKeyword, this.OperatorToken, parameters); public OperatorMemberCrefSyntax AddParametersParameters(params CrefParameterSyntax[] items) { var parameters = this.Parameters ?? SyntaxFactory.CrefParameterList(); return WithParameters(parameters.WithParameters(parameters.Parameters.AddRange(items))); } } /// <summary> /// A MemberCrefSyntax specified by an implicit or explicit keyword, an operator keyword, a destination type, and an optional parameter list. /// For example, "implicit operator int" or "explicit operator MyType(int)". /// </summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ConversionOperatorMemberCref"/></description></item> /// </list> /// </remarks> public sealed partial class ConversionOperatorMemberCrefSyntax : MemberCrefSyntax { private TypeSyntax? type; private CrefParameterListSyntax? parameters; internal ConversionOperatorMemberCrefSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken ImplicitOrExplicitKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ConversionOperatorMemberCrefSyntax)this.Green).implicitOrExplicitKeyword, Position, 0); public SyntaxToken OperatorKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ConversionOperatorMemberCrefSyntax)this.Green).operatorKeyword, GetChildPosition(1), GetChildIndex(1)); public TypeSyntax Type => GetRed(ref this.type, 2)!; public CrefParameterListSyntax? Parameters => GetRed(ref this.parameters, 3); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 2 => GetRed(ref this.type, 2)!, 3 => GetRed(ref this.parameters, 3), _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 2 => this.type, 3 => this.parameters, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitConversionOperatorMemberCref(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitConversionOperatorMemberCref(this); public ConversionOperatorMemberCrefSyntax Update(SyntaxToken implicitOrExplicitKeyword, SyntaxToken operatorKeyword, TypeSyntax type, CrefParameterListSyntax? parameters) { if (implicitOrExplicitKeyword != this.ImplicitOrExplicitKeyword || operatorKeyword != this.OperatorKeyword || type != this.Type || parameters != this.Parameters) { var newNode = SyntaxFactory.ConversionOperatorMemberCref(implicitOrExplicitKeyword, operatorKeyword, type, parameters); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public ConversionOperatorMemberCrefSyntax WithImplicitOrExplicitKeyword(SyntaxToken implicitOrExplicitKeyword) => Update(implicitOrExplicitKeyword, this.OperatorKeyword, this.Type, this.Parameters); public ConversionOperatorMemberCrefSyntax WithOperatorKeyword(SyntaxToken operatorKeyword) => Update(this.ImplicitOrExplicitKeyword, operatorKeyword, this.Type, this.Parameters); public ConversionOperatorMemberCrefSyntax WithType(TypeSyntax type) => Update(this.ImplicitOrExplicitKeyword, this.OperatorKeyword, type, this.Parameters); public ConversionOperatorMemberCrefSyntax WithParameters(CrefParameterListSyntax? parameters) => Update(this.ImplicitOrExplicitKeyword, this.OperatorKeyword, this.Type, parameters); public ConversionOperatorMemberCrefSyntax AddParametersParameters(params CrefParameterSyntax[] items) { var parameters = this.Parameters ?? SyntaxFactory.CrefParameterList(); return WithParameters(parameters.WithParameters(parameters.Parameters.AddRange(items))); } } /// <summary> /// A list of cref parameters with surrounding punctuation. /// Unlike regular parameters, cref parameters do not have names. /// </summary> public abstract partial class BaseCrefParameterListSyntax : CSharpSyntaxNode { internal BaseCrefParameterListSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the parameter list.</summary> public abstract SeparatedSyntaxList<CrefParameterSyntax> Parameters { get; } public BaseCrefParameterListSyntax WithParameters(SeparatedSyntaxList<CrefParameterSyntax> parameters) => WithParametersCore(parameters); internal abstract BaseCrefParameterListSyntax WithParametersCore(SeparatedSyntaxList<CrefParameterSyntax> parameters); public BaseCrefParameterListSyntax AddParameters(params CrefParameterSyntax[] items) => AddParametersCore(items); internal abstract BaseCrefParameterListSyntax AddParametersCore(params CrefParameterSyntax[] items); } /// <summary> /// A parenthesized list of cref parameters. /// </summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.CrefParameterList"/></description></item> /// </list> /// </remarks> public sealed partial class CrefParameterListSyntax : BaseCrefParameterListSyntax { private SyntaxNode? parameters; internal CrefParameterListSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the open paren token.</summary> public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.CrefParameterListSyntax)this.Green).openParenToken, Position, 0); public override SeparatedSyntaxList<CrefParameterSyntax> Parameters { get { var red = GetRed(ref this.parameters, 1); return red != null ? new SeparatedSyntaxList<CrefParameterSyntax>(red, GetChildIndex(1)) : default; } } /// <summary>Gets the close paren token.</summary> public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.CrefParameterListSyntax)this.Green).closeParenToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.parameters, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.parameters : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitCrefParameterList(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitCrefParameterList(this); public CrefParameterListSyntax Update(SyntaxToken openParenToken, SeparatedSyntaxList<CrefParameterSyntax> parameters, SyntaxToken closeParenToken) { if (openParenToken != this.OpenParenToken || parameters != this.Parameters || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.CrefParameterList(openParenToken, parameters, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public CrefParameterListSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(openParenToken, this.Parameters, this.CloseParenToken); internal override BaseCrefParameterListSyntax WithParametersCore(SeparatedSyntaxList<CrefParameterSyntax> parameters) => WithParameters(parameters); public new CrefParameterListSyntax WithParameters(SeparatedSyntaxList<CrefParameterSyntax> parameters) => Update(this.OpenParenToken, parameters, this.CloseParenToken); public CrefParameterListSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.OpenParenToken, this.Parameters, closeParenToken); internal override BaseCrefParameterListSyntax AddParametersCore(params CrefParameterSyntax[] items) => AddParameters(items); public new CrefParameterListSyntax AddParameters(params CrefParameterSyntax[] items) => WithParameters(this.Parameters.AddRange(items)); } /// <summary> /// A bracketed list of cref parameters. /// </summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.CrefBracketedParameterList"/></description></item> /// </list> /// </remarks> public sealed partial class CrefBracketedParameterListSyntax : BaseCrefParameterListSyntax { private SyntaxNode? parameters; internal CrefBracketedParameterListSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } /// <summary>Gets the open bracket token.</summary> public SyntaxToken OpenBracketToken => new SyntaxToken(this, ((Syntax.InternalSyntax.CrefBracketedParameterListSyntax)this.Green).openBracketToken, Position, 0); public override SeparatedSyntaxList<CrefParameterSyntax> Parameters { get { var red = GetRed(ref this.parameters, 1); return red != null ? new SeparatedSyntaxList<CrefParameterSyntax>(red, GetChildIndex(1)) : default; } } /// <summary>Gets the close bracket token.</summary> public SyntaxToken CloseBracketToken => new SyntaxToken(this, ((Syntax.InternalSyntax.CrefBracketedParameterListSyntax)this.Green).closeBracketToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.parameters, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.parameters : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitCrefBracketedParameterList(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitCrefBracketedParameterList(this); public CrefBracketedParameterListSyntax Update(SyntaxToken openBracketToken, SeparatedSyntaxList<CrefParameterSyntax> parameters, SyntaxToken closeBracketToken) { if (openBracketToken != this.OpenBracketToken || parameters != this.Parameters || closeBracketToken != this.CloseBracketToken) { var newNode = SyntaxFactory.CrefBracketedParameterList(openBracketToken, parameters, closeBracketToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public CrefBracketedParameterListSyntax WithOpenBracketToken(SyntaxToken openBracketToken) => Update(openBracketToken, this.Parameters, this.CloseBracketToken); internal override BaseCrefParameterListSyntax WithParametersCore(SeparatedSyntaxList<CrefParameterSyntax> parameters) => WithParameters(parameters); public new CrefBracketedParameterListSyntax WithParameters(SeparatedSyntaxList<CrefParameterSyntax> parameters) => Update(this.OpenBracketToken, parameters, this.CloseBracketToken); public CrefBracketedParameterListSyntax WithCloseBracketToken(SyntaxToken closeBracketToken) => Update(this.OpenBracketToken, this.Parameters, closeBracketToken); internal override BaseCrefParameterListSyntax AddParametersCore(params CrefParameterSyntax[] items) => AddParameters(items); public new CrefBracketedParameterListSyntax AddParameters(params CrefParameterSyntax[] items) => WithParameters(this.Parameters.AddRange(items)); } /// <summary> /// An element of a BaseCrefParameterListSyntax. /// Unlike a regular parameter, a cref parameter has only an optional ref or out keyword and a type - /// there is no name and there are no attributes or other modifiers. /// </summary> /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.CrefParameter"/></description></item> /// </list> /// </remarks> public sealed partial class CrefParameterSyntax : CSharpSyntaxNode { private TypeSyntax? type; internal CrefParameterSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken RefKindKeyword { get { var slot = ((Syntax.InternalSyntax.CrefParameterSyntax)this.Green).refKindKeyword; return slot != null ? new SyntaxToken(this, slot, Position, 0) : default; } } public TypeSyntax Type => GetRed(ref this.type, 1)!; internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.type, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.type : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitCrefParameter(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitCrefParameter(this); public CrefParameterSyntax Update(SyntaxToken refKindKeyword, TypeSyntax type) { if (refKindKeyword != this.RefKindKeyword || type != this.Type) { var newNode = SyntaxFactory.CrefParameter(refKindKeyword, type); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public CrefParameterSyntax WithRefKindKeyword(SyntaxToken refKindKeyword) => Update(refKindKeyword, this.Type); public CrefParameterSyntax WithType(TypeSyntax type) => Update(this.RefKindKeyword, type); } public abstract partial class XmlNodeSyntax : CSharpSyntaxNode { internal XmlNodeSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.XmlElement"/></description></item> /// </list> /// </remarks> public sealed partial class XmlElementSyntax : XmlNodeSyntax { private XmlElementStartTagSyntax? startTag; private SyntaxNode? content; private XmlElementEndTagSyntax? endTag; internal XmlElementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public XmlElementStartTagSyntax StartTag => GetRedAtZero(ref this.startTag)!; public SyntaxList<XmlNodeSyntax> Content => new SyntaxList<XmlNodeSyntax>(GetRed(ref this.content, 1)); public XmlElementEndTagSyntax EndTag => GetRed(ref this.endTag, 2)!; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.startTag)!, 1 => GetRed(ref this.content, 1)!, 2 => GetRed(ref this.endTag, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.startTag, 1 => this.content, 2 => this.endTag, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitXmlElement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitXmlElement(this); public XmlElementSyntax Update(XmlElementStartTagSyntax startTag, SyntaxList<XmlNodeSyntax> content, XmlElementEndTagSyntax endTag) { if (startTag != this.StartTag || content != this.Content || endTag != this.EndTag) { var newNode = SyntaxFactory.XmlElement(startTag, content, endTag); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public XmlElementSyntax WithStartTag(XmlElementStartTagSyntax startTag) => Update(startTag, this.Content, this.EndTag); public XmlElementSyntax WithContent(SyntaxList<XmlNodeSyntax> content) => Update(this.StartTag, content, this.EndTag); public XmlElementSyntax WithEndTag(XmlElementEndTagSyntax endTag) => Update(this.StartTag, this.Content, endTag); public XmlElementSyntax AddStartTagAttributes(params XmlAttributeSyntax[] items) => WithStartTag(this.StartTag.WithAttributes(this.StartTag.Attributes.AddRange(items))); public XmlElementSyntax AddContent(params XmlNodeSyntax[] items) => WithContent(this.Content.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.XmlElementStartTag"/></description></item> /// </list> /// </remarks> public sealed partial class XmlElementStartTagSyntax : CSharpSyntaxNode { private XmlNameSyntax? name; private SyntaxNode? attributes; internal XmlElementStartTagSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken LessThanToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlElementStartTagSyntax)this.Green).lessThanToken, Position, 0); public XmlNameSyntax Name => GetRed(ref this.name, 1)!; public SyntaxList<XmlAttributeSyntax> Attributes => new SyntaxList<XmlAttributeSyntax>(GetRed(ref this.attributes, 2)); public SyntaxToken GreaterThanToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlElementStartTagSyntax)this.Green).greaterThanToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 1 => GetRed(ref this.name, 1)!, 2 => GetRed(ref this.attributes, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 1 => this.name, 2 => this.attributes, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitXmlElementStartTag(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitXmlElementStartTag(this); public XmlElementStartTagSyntax Update(SyntaxToken lessThanToken, XmlNameSyntax name, SyntaxList<XmlAttributeSyntax> attributes, SyntaxToken greaterThanToken) { if (lessThanToken != this.LessThanToken || name != this.Name || attributes != this.Attributes || greaterThanToken != this.GreaterThanToken) { var newNode = SyntaxFactory.XmlElementStartTag(lessThanToken, name, attributes, greaterThanToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public XmlElementStartTagSyntax WithLessThanToken(SyntaxToken lessThanToken) => Update(lessThanToken, this.Name, this.Attributes, this.GreaterThanToken); public XmlElementStartTagSyntax WithName(XmlNameSyntax name) => Update(this.LessThanToken, name, this.Attributes, this.GreaterThanToken); public XmlElementStartTagSyntax WithAttributes(SyntaxList<XmlAttributeSyntax> attributes) => Update(this.LessThanToken, this.Name, attributes, this.GreaterThanToken); public XmlElementStartTagSyntax WithGreaterThanToken(SyntaxToken greaterThanToken) => Update(this.LessThanToken, this.Name, this.Attributes, greaterThanToken); public XmlElementStartTagSyntax AddAttributes(params XmlAttributeSyntax[] items) => WithAttributes(this.Attributes.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.XmlElementEndTag"/></description></item> /// </list> /// </remarks> public sealed partial class XmlElementEndTagSyntax : CSharpSyntaxNode { private XmlNameSyntax? name; internal XmlElementEndTagSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken LessThanSlashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlElementEndTagSyntax)this.Green).lessThanSlashToken, Position, 0); public XmlNameSyntax Name => GetRed(ref this.name, 1)!; public SyntaxToken GreaterThanToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlElementEndTagSyntax)this.Green).greaterThanToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.name, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.name : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitXmlElementEndTag(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitXmlElementEndTag(this); public XmlElementEndTagSyntax Update(SyntaxToken lessThanSlashToken, XmlNameSyntax name, SyntaxToken greaterThanToken) { if (lessThanSlashToken != this.LessThanSlashToken || name != this.Name || greaterThanToken != this.GreaterThanToken) { var newNode = SyntaxFactory.XmlElementEndTag(lessThanSlashToken, name, greaterThanToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public XmlElementEndTagSyntax WithLessThanSlashToken(SyntaxToken lessThanSlashToken) => Update(lessThanSlashToken, this.Name, this.GreaterThanToken); public XmlElementEndTagSyntax WithName(XmlNameSyntax name) => Update(this.LessThanSlashToken, name, this.GreaterThanToken); public XmlElementEndTagSyntax WithGreaterThanToken(SyntaxToken greaterThanToken) => Update(this.LessThanSlashToken, this.Name, greaterThanToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.XmlEmptyElement"/></description></item> /// </list> /// </remarks> public sealed partial class XmlEmptyElementSyntax : XmlNodeSyntax { private XmlNameSyntax? name; private SyntaxNode? attributes; internal XmlEmptyElementSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken LessThanToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlEmptyElementSyntax)this.Green).lessThanToken, Position, 0); public XmlNameSyntax Name => GetRed(ref this.name, 1)!; public SyntaxList<XmlAttributeSyntax> Attributes => new SyntaxList<XmlAttributeSyntax>(GetRed(ref this.attributes, 2)); public SyntaxToken SlashGreaterThanToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlEmptyElementSyntax)this.Green).slashGreaterThanToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 1 => GetRed(ref this.name, 1)!, 2 => GetRed(ref this.attributes, 2)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 1 => this.name, 2 => this.attributes, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitXmlEmptyElement(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitXmlEmptyElement(this); public XmlEmptyElementSyntax Update(SyntaxToken lessThanToken, XmlNameSyntax name, SyntaxList<XmlAttributeSyntax> attributes, SyntaxToken slashGreaterThanToken) { if (lessThanToken != this.LessThanToken || name != this.Name || attributes != this.Attributes || slashGreaterThanToken != this.SlashGreaterThanToken) { var newNode = SyntaxFactory.XmlEmptyElement(lessThanToken, name, attributes, slashGreaterThanToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public XmlEmptyElementSyntax WithLessThanToken(SyntaxToken lessThanToken) => Update(lessThanToken, this.Name, this.Attributes, this.SlashGreaterThanToken); public XmlEmptyElementSyntax WithName(XmlNameSyntax name) => Update(this.LessThanToken, name, this.Attributes, this.SlashGreaterThanToken); public XmlEmptyElementSyntax WithAttributes(SyntaxList<XmlAttributeSyntax> attributes) => Update(this.LessThanToken, this.Name, attributes, this.SlashGreaterThanToken); public XmlEmptyElementSyntax WithSlashGreaterThanToken(SyntaxToken slashGreaterThanToken) => Update(this.LessThanToken, this.Name, this.Attributes, slashGreaterThanToken); public XmlEmptyElementSyntax AddAttributes(params XmlAttributeSyntax[] items) => WithAttributes(this.Attributes.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.XmlName"/></description></item> /// </list> /// </remarks> public sealed partial class XmlNameSyntax : CSharpSyntaxNode { private XmlPrefixSyntax? prefix; internal XmlNameSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public XmlPrefixSyntax? Prefix => GetRedAtZero(ref this.prefix); public SyntaxToken LocalName => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlNameSyntax)this.Green).localName, GetChildPosition(1), GetChildIndex(1)); internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.prefix) : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.prefix : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitXmlName(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitXmlName(this); public XmlNameSyntax Update(XmlPrefixSyntax? prefix, SyntaxToken localName) { if (prefix != this.Prefix || localName != this.LocalName) { var newNode = SyntaxFactory.XmlName(prefix, localName); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public XmlNameSyntax WithPrefix(XmlPrefixSyntax? prefix) => Update(prefix, this.LocalName); public XmlNameSyntax WithLocalName(SyntaxToken localName) => Update(this.Prefix, localName); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.XmlPrefix"/></description></item> /// </list> /// </remarks> public sealed partial class XmlPrefixSyntax : CSharpSyntaxNode { internal XmlPrefixSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken Prefix => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlPrefixSyntax)this.Green).prefix, Position, 0); public SyntaxToken ColonToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlPrefixSyntax)this.Green).colonToken, GetChildPosition(1), GetChildIndex(1)); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitXmlPrefix(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitXmlPrefix(this); public XmlPrefixSyntax Update(SyntaxToken prefix, SyntaxToken colonToken) { if (prefix != this.Prefix || colonToken != this.ColonToken) { var newNode = SyntaxFactory.XmlPrefix(prefix, colonToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public XmlPrefixSyntax WithPrefix(SyntaxToken prefix) => Update(prefix, this.ColonToken); public XmlPrefixSyntax WithColonToken(SyntaxToken colonToken) => Update(this.Prefix, colonToken); } public abstract partial class XmlAttributeSyntax : CSharpSyntaxNode { internal XmlAttributeSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public abstract XmlNameSyntax Name { get; } public XmlAttributeSyntax WithName(XmlNameSyntax name) => WithNameCore(name); internal abstract XmlAttributeSyntax WithNameCore(XmlNameSyntax name); public abstract SyntaxToken EqualsToken { get; } public XmlAttributeSyntax WithEqualsToken(SyntaxToken equalsToken) => WithEqualsTokenCore(equalsToken); internal abstract XmlAttributeSyntax WithEqualsTokenCore(SyntaxToken equalsToken); public abstract SyntaxToken StartQuoteToken { get; } public XmlAttributeSyntax WithStartQuoteToken(SyntaxToken startQuoteToken) => WithStartQuoteTokenCore(startQuoteToken); internal abstract XmlAttributeSyntax WithStartQuoteTokenCore(SyntaxToken startQuoteToken); public abstract SyntaxToken EndQuoteToken { get; } public XmlAttributeSyntax WithEndQuoteToken(SyntaxToken endQuoteToken) => WithEndQuoteTokenCore(endQuoteToken); internal abstract XmlAttributeSyntax WithEndQuoteTokenCore(SyntaxToken endQuoteToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.XmlTextAttribute"/></description></item> /// </list> /// </remarks> public sealed partial class XmlTextAttributeSyntax : XmlAttributeSyntax { private XmlNameSyntax? name; internal XmlTextAttributeSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override XmlNameSyntax Name => GetRedAtZero(ref this.name)!; public override SyntaxToken EqualsToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlTextAttributeSyntax)this.Green).equalsToken, GetChildPosition(1), GetChildIndex(1)); public override SyntaxToken StartQuoteToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlTextAttributeSyntax)this.Green).startQuoteToken, GetChildPosition(2), GetChildIndex(2)); public SyntaxTokenList TextTokens { get { var slot = this.Green.GetSlot(3); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(3), GetChildIndex(3)) : default; } } public override SyntaxToken EndQuoteToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlTextAttributeSyntax)this.Green).endQuoteToken, GetChildPosition(4), GetChildIndex(4)); internal override SyntaxNode? GetNodeSlot(int index) => index == 0 ? GetRedAtZero(ref this.name)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 0 ? this.name : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitXmlTextAttribute(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitXmlTextAttribute(this); public XmlTextAttributeSyntax Update(XmlNameSyntax name, SyntaxToken equalsToken, SyntaxToken startQuoteToken, SyntaxTokenList textTokens, SyntaxToken endQuoteToken) { if (name != this.Name || equalsToken != this.EqualsToken || startQuoteToken != this.StartQuoteToken || textTokens != this.TextTokens || endQuoteToken != this.EndQuoteToken) { var newNode = SyntaxFactory.XmlTextAttribute(name, equalsToken, startQuoteToken, textTokens, endQuoteToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override XmlAttributeSyntax WithNameCore(XmlNameSyntax name) => WithName(name); public new XmlTextAttributeSyntax WithName(XmlNameSyntax name) => Update(name, this.EqualsToken, this.StartQuoteToken, this.TextTokens, this.EndQuoteToken); internal override XmlAttributeSyntax WithEqualsTokenCore(SyntaxToken equalsToken) => WithEqualsToken(equalsToken); public new XmlTextAttributeSyntax WithEqualsToken(SyntaxToken equalsToken) => Update(this.Name, equalsToken, this.StartQuoteToken, this.TextTokens, this.EndQuoteToken); internal override XmlAttributeSyntax WithStartQuoteTokenCore(SyntaxToken startQuoteToken) => WithStartQuoteToken(startQuoteToken); public new XmlTextAttributeSyntax WithStartQuoteToken(SyntaxToken startQuoteToken) => Update(this.Name, this.EqualsToken, startQuoteToken, this.TextTokens, this.EndQuoteToken); public XmlTextAttributeSyntax WithTextTokens(SyntaxTokenList textTokens) => Update(this.Name, this.EqualsToken, this.StartQuoteToken, textTokens, this.EndQuoteToken); internal override XmlAttributeSyntax WithEndQuoteTokenCore(SyntaxToken endQuoteToken) => WithEndQuoteToken(endQuoteToken); public new XmlTextAttributeSyntax WithEndQuoteToken(SyntaxToken endQuoteToken) => Update(this.Name, this.EqualsToken, this.StartQuoteToken, this.TextTokens, endQuoteToken); public XmlTextAttributeSyntax AddTextTokens(params SyntaxToken[] items) => WithTextTokens(this.TextTokens.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.XmlCrefAttribute"/></description></item> /// </list> /// </remarks> public sealed partial class XmlCrefAttributeSyntax : XmlAttributeSyntax { private XmlNameSyntax? name; private CrefSyntax? cref; internal XmlCrefAttributeSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override XmlNameSyntax Name => GetRedAtZero(ref this.name)!; public override SyntaxToken EqualsToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlCrefAttributeSyntax)this.Green).equalsToken, GetChildPosition(1), GetChildIndex(1)); public override SyntaxToken StartQuoteToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlCrefAttributeSyntax)this.Green).startQuoteToken, GetChildPosition(2), GetChildIndex(2)); public CrefSyntax Cref => GetRed(ref this.cref, 3)!; public override SyntaxToken EndQuoteToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlCrefAttributeSyntax)this.Green).endQuoteToken, GetChildPosition(4), GetChildIndex(4)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.name)!, 3 => GetRed(ref this.cref, 3)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.name, 3 => this.cref, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitXmlCrefAttribute(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitXmlCrefAttribute(this); public XmlCrefAttributeSyntax Update(XmlNameSyntax name, SyntaxToken equalsToken, SyntaxToken startQuoteToken, CrefSyntax cref, SyntaxToken endQuoteToken) { if (name != this.Name || equalsToken != this.EqualsToken || startQuoteToken != this.StartQuoteToken || cref != this.Cref || endQuoteToken != this.EndQuoteToken) { var newNode = SyntaxFactory.XmlCrefAttribute(name, equalsToken, startQuoteToken, cref, endQuoteToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override XmlAttributeSyntax WithNameCore(XmlNameSyntax name) => WithName(name); public new XmlCrefAttributeSyntax WithName(XmlNameSyntax name) => Update(name, this.EqualsToken, this.StartQuoteToken, this.Cref, this.EndQuoteToken); internal override XmlAttributeSyntax WithEqualsTokenCore(SyntaxToken equalsToken) => WithEqualsToken(equalsToken); public new XmlCrefAttributeSyntax WithEqualsToken(SyntaxToken equalsToken) => Update(this.Name, equalsToken, this.StartQuoteToken, this.Cref, this.EndQuoteToken); internal override XmlAttributeSyntax WithStartQuoteTokenCore(SyntaxToken startQuoteToken) => WithStartQuoteToken(startQuoteToken); public new XmlCrefAttributeSyntax WithStartQuoteToken(SyntaxToken startQuoteToken) => Update(this.Name, this.EqualsToken, startQuoteToken, this.Cref, this.EndQuoteToken); public XmlCrefAttributeSyntax WithCref(CrefSyntax cref) => Update(this.Name, this.EqualsToken, this.StartQuoteToken, cref, this.EndQuoteToken); internal override XmlAttributeSyntax WithEndQuoteTokenCore(SyntaxToken endQuoteToken) => WithEndQuoteToken(endQuoteToken); public new XmlCrefAttributeSyntax WithEndQuoteToken(SyntaxToken endQuoteToken) => Update(this.Name, this.EqualsToken, this.StartQuoteToken, this.Cref, endQuoteToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.XmlNameAttribute"/></description></item> /// </list> /// </remarks> public sealed partial class XmlNameAttributeSyntax : XmlAttributeSyntax { private XmlNameSyntax? name; private IdentifierNameSyntax? identifier; internal XmlNameAttributeSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override XmlNameSyntax Name => GetRedAtZero(ref this.name)!; public override SyntaxToken EqualsToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlNameAttributeSyntax)this.Green).equalsToken, GetChildPosition(1), GetChildIndex(1)); public override SyntaxToken StartQuoteToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlNameAttributeSyntax)this.Green).startQuoteToken, GetChildPosition(2), GetChildIndex(2)); public IdentifierNameSyntax Identifier => GetRed(ref this.identifier, 3)!; public override SyntaxToken EndQuoteToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlNameAttributeSyntax)this.Green).endQuoteToken, GetChildPosition(4), GetChildIndex(4)); internal override SyntaxNode? GetNodeSlot(int index) => index switch { 0 => GetRedAtZero(ref this.name)!, 3 => GetRed(ref this.identifier, 3)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 0 => this.name, 3 => this.identifier, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitXmlNameAttribute(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitXmlNameAttribute(this); public XmlNameAttributeSyntax Update(XmlNameSyntax name, SyntaxToken equalsToken, SyntaxToken startQuoteToken, IdentifierNameSyntax identifier, SyntaxToken endQuoteToken) { if (name != this.Name || equalsToken != this.EqualsToken || startQuoteToken != this.StartQuoteToken || identifier != this.Identifier || endQuoteToken != this.EndQuoteToken) { var newNode = SyntaxFactory.XmlNameAttribute(name, equalsToken, startQuoteToken, identifier, endQuoteToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override XmlAttributeSyntax WithNameCore(XmlNameSyntax name) => WithName(name); public new XmlNameAttributeSyntax WithName(XmlNameSyntax name) => Update(name, this.EqualsToken, this.StartQuoteToken, this.Identifier, this.EndQuoteToken); internal override XmlAttributeSyntax WithEqualsTokenCore(SyntaxToken equalsToken) => WithEqualsToken(equalsToken); public new XmlNameAttributeSyntax WithEqualsToken(SyntaxToken equalsToken) => Update(this.Name, equalsToken, this.StartQuoteToken, this.Identifier, this.EndQuoteToken); internal override XmlAttributeSyntax WithStartQuoteTokenCore(SyntaxToken startQuoteToken) => WithStartQuoteToken(startQuoteToken); public new XmlNameAttributeSyntax WithStartQuoteToken(SyntaxToken startQuoteToken) => Update(this.Name, this.EqualsToken, startQuoteToken, this.Identifier, this.EndQuoteToken); public XmlNameAttributeSyntax WithIdentifier(IdentifierNameSyntax identifier) => Update(this.Name, this.EqualsToken, this.StartQuoteToken, identifier, this.EndQuoteToken); internal override XmlAttributeSyntax WithEndQuoteTokenCore(SyntaxToken endQuoteToken) => WithEndQuoteToken(endQuoteToken); public new XmlNameAttributeSyntax WithEndQuoteToken(SyntaxToken endQuoteToken) => Update(this.Name, this.EqualsToken, this.StartQuoteToken, this.Identifier, endQuoteToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.XmlText"/></description></item> /// </list> /// </remarks> public sealed partial class XmlTextSyntax : XmlNodeSyntax { internal XmlTextSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxTokenList TextTokens { get { var slot = this.Green.GetSlot(0); return slot != null ? new SyntaxTokenList(this, slot, Position, 0) : default; } } internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitXmlText(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitXmlText(this); public XmlTextSyntax Update(SyntaxTokenList textTokens) { if (textTokens != this.TextTokens) { var newNode = SyntaxFactory.XmlText(textTokens); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public XmlTextSyntax WithTextTokens(SyntaxTokenList textTokens) => Update(textTokens); public XmlTextSyntax AddTextTokens(params SyntaxToken[] items) => WithTextTokens(this.TextTokens.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.XmlCDataSection"/></description></item> /// </list> /// </remarks> public sealed partial class XmlCDataSectionSyntax : XmlNodeSyntax { internal XmlCDataSectionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken StartCDataToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlCDataSectionSyntax)this.Green).startCDataToken, Position, 0); public SyntaxTokenList TextTokens { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public SyntaxToken EndCDataToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlCDataSectionSyntax)this.Green).endCDataToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitXmlCDataSection(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitXmlCDataSection(this); public XmlCDataSectionSyntax Update(SyntaxToken startCDataToken, SyntaxTokenList textTokens, SyntaxToken endCDataToken) { if (startCDataToken != this.StartCDataToken || textTokens != this.TextTokens || endCDataToken != this.EndCDataToken) { var newNode = SyntaxFactory.XmlCDataSection(startCDataToken, textTokens, endCDataToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public XmlCDataSectionSyntax WithStartCDataToken(SyntaxToken startCDataToken) => Update(startCDataToken, this.TextTokens, this.EndCDataToken); public XmlCDataSectionSyntax WithTextTokens(SyntaxTokenList textTokens) => Update(this.StartCDataToken, textTokens, this.EndCDataToken); public XmlCDataSectionSyntax WithEndCDataToken(SyntaxToken endCDataToken) => Update(this.StartCDataToken, this.TextTokens, endCDataToken); public XmlCDataSectionSyntax AddTextTokens(params SyntaxToken[] items) => WithTextTokens(this.TextTokens.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.XmlProcessingInstruction"/></description></item> /// </list> /// </remarks> public sealed partial class XmlProcessingInstructionSyntax : XmlNodeSyntax { private XmlNameSyntax? name; internal XmlProcessingInstructionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken StartProcessingInstructionToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlProcessingInstructionSyntax)this.Green).startProcessingInstructionToken, Position, 0); public XmlNameSyntax Name => GetRed(ref this.name, 1)!; public SyntaxTokenList TextTokens { get { var slot = this.Green.GetSlot(2); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(2), GetChildIndex(2)) : default; } } public SyntaxToken EndProcessingInstructionToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlProcessingInstructionSyntax)this.Green).endProcessingInstructionToken, GetChildPosition(3), GetChildIndex(3)); internal override SyntaxNode? GetNodeSlot(int index) => index == 1 ? GetRed(ref this.name, 1)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 1 ? this.name : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitXmlProcessingInstruction(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitXmlProcessingInstruction(this); public XmlProcessingInstructionSyntax Update(SyntaxToken startProcessingInstructionToken, XmlNameSyntax name, SyntaxTokenList textTokens, SyntaxToken endProcessingInstructionToken) { if (startProcessingInstructionToken != this.StartProcessingInstructionToken || name != this.Name || textTokens != this.TextTokens || endProcessingInstructionToken != this.EndProcessingInstructionToken) { var newNode = SyntaxFactory.XmlProcessingInstruction(startProcessingInstructionToken, name, textTokens, endProcessingInstructionToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public XmlProcessingInstructionSyntax WithStartProcessingInstructionToken(SyntaxToken startProcessingInstructionToken) => Update(startProcessingInstructionToken, this.Name, this.TextTokens, this.EndProcessingInstructionToken); public XmlProcessingInstructionSyntax WithName(XmlNameSyntax name) => Update(this.StartProcessingInstructionToken, name, this.TextTokens, this.EndProcessingInstructionToken); public XmlProcessingInstructionSyntax WithTextTokens(SyntaxTokenList textTokens) => Update(this.StartProcessingInstructionToken, this.Name, textTokens, this.EndProcessingInstructionToken); public XmlProcessingInstructionSyntax WithEndProcessingInstructionToken(SyntaxToken endProcessingInstructionToken) => Update(this.StartProcessingInstructionToken, this.Name, this.TextTokens, endProcessingInstructionToken); public XmlProcessingInstructionSyntax AddTextTokens(params SyntaxToken[] items) => WithTextTokens(this.TextTokens.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.XmlComment"/></description></item> /// </list> /// </remarks> public sealed partial class XmlCommentSyntax : XmlNodeSyntax { internal XmlCommentSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken LessThanExclamationMinusMinusToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlCommentSyntax)this.Green).lessThanExclamationMinusMinusToken, Position, 0); public SyntaxTokenList TextTokens { get { var slot = this.Green.GetSlot(1); return slot != null ? new SyntaxTokenList(this, slot, GetChildPosition(1), GetChildIndex(1)) : default; } } public SyntaxToken MinusMinusGreaterThanToken => new SyntaxToken(this, ((Syntax.InternalSyntax.XmlCommentSyntax)this.Green).minusMinusGreaterThanToken, GetChildPosition(2), GetChildIndex(2)); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitXmlComment(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitXmlComment(this); public XmlCommentSyntax Update(SyntaxToken lessThanExclamationMinusMinusToken, SyntaxTokenList textTokens, SyntaxToken minusMinusGreaterThanToken) { if (lessThanExclamationMinusMinusToken != this.LessThanExclamationMinusMinusToken || textTokens != this.TextTokens || minusMinusGreaterThanToken != this.MinusMinusGreaterThanToken) { var newNode = SyntaxFactory.XmlComment(lessThanExclamationMinusMinusToken, textTokens, minusMinusGreaterThanToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public XmlCommentSyntax WithLessThanExclamationMinusMinusToken(SyntaxToken lessThanExclamationMinusMinusToken) => Update(lessThanExclamationMinusMinusToken, this.TextTokens, this.MinusMinusGreaterThanToken); public XmlCommentSyntax WithTextTokens(SyntaxTokenList textTokens) => Update(this.LessThanExclamationMinusMinusToken, textTokens, this.MinusMinusGreaterThanToken); public XmlCommentSyntax WithMinusMinusGreaterThanToken(SyntaxToken minusMinusGreaterThanToken) => Update(this.LessThanExclamationMinusMinusToken, this.TextTokens, minusMinusGreaterThanToken); public XmlCommentSyntax AddTextTokens(params SyntaxToken[] items) => WithTextTokens(this.TextTokens.AddRange(items)); } public abstract partial class DirectiveTriviaSyntax : StructuredTriviaSyntax { internal DirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public abstract SyntaxToken HashToken { get; } public DirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => WithHashTokenCore(hashToken); internal abstract DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken); public abstract SyntaxToken EndOfDirectiveToken { get; } public DirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveTokenCore(endOfDirectiveToken); internal abstract DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken); public abstract bool IsActive { get; } } public abstract partial class BranchingDirectiveTriviaSyntax : DirectiveTriviaSyntax { internal BranchingDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public abstract bool BranchTaken { get; } public new BranchingDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => (BranchingDirectiveTriviaSyntax)WithHashTokenCore(hashToken); public new BranchingDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => (BranchingDirectiveTriviaSyntax)WithEndOfDirectiveTokenCore(endOfDirectiveToken); } public abstract partial class ConditionalDirectiveTriviaSyntax : BranchingDirectiveTriviaSyntax { internal ConditionalDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public abstract ExpressionSyntax Condition { get; } public ConditionalDirectiveTriviaSyntax WithCondition(ExpressionSyntax condition) => WithConditionCore(condition); internal abstract ConditionalDirectiveTriviaSyntax WithConditionCore(ExpressionSyntax condition); public abstract bool ConditionValue { get; } } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.IfDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class IfDirectiveTriviaSyntax : ConditionalDirectiveTriviaSyntax { private ExpressionSyntax? condition; internal IfDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.IfDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public SyntaxToken IfKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.IfDirectiveTriviaSyntax)this.Green).ifKeyword, GetChildPosition(1), GetChildIndex(1)); public override ExpressionSyntax Condition => GetRed(ref this.condition, 2)!; public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.IfDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(3), GetChildIndex(3)); public override bool IsActive => ((Syntax.InternalSyntax.IfDirectiveTriviaSyntax)this.Green).IsActive; public override bool BranchTaken => ((Syntax.InternalSyntax.IfDirectiveTriviaSyntax)this.Green).BranchTaken; public override bool ConditionValue => ((Syntax.InternalSyntax.IfDirectiveTriviaSyntax)this.Green).ConditionValue; internal override SyntaxNode? GetNodeSlot(int index) => index == 2 ? GetRed(ref this.condition, 2)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 2 ? this.condition : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitIfDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitIfDirectiveTrivia(this); public IfDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken ifKeyword, ExpressionSyntax condition, SyntaxToken endOfDirectiveToken, bool isActive, bool branchTaken, bool conditionValue) { if (hashToken != this.HashToken || ifKeyword != this.IfKeyword || condition != this.Condition || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.IfDirectiveTrivia(hashToken, ifKeyword, condition, endOfDirectiveToken, isActive, branchTaken, conditionValue); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new IfDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.IfKeyword, this.Condition, this.EndOfDirectiveToken, this.IsActive, this.BranchTaken, this.ConditionValue); public IfDirectiveTriviaSyntax WithIfKeyword(SyntaxToken ifKeyword) => Update(this.HashToken, ifKeyword, this.Condition, this.EndOfDirectiveToken, this.IsActive, this.BranchTaken, this.ConditionValue); internal override ConditionalDirectiveTriviaSyntax WithConditionCore(ExpressionSyntax condition) => WithCondition(condition); public new IfDirectiveTriviaSyntax WithCondition(ExpressionSyntax condition) => Update(this.HashToken, this.IfKeyword, condition, this.EndOfDirectiveToken, this.IsActive, this.BranchTaken, this.ConditionValue); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new IfDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.IfKeyword, this.Condition, endOfDirectiveToken, this.IsActive, this.BranchTaken, this.ConditionValue); public IfDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.IfKeyword, this.Condition, this.EndOfDirectiveToken, isActive, this.BranchTaken, this.ConditionValue); public IfDirectiveTriviaSyntax WithBranchTaken(bool branchTaken) => Update(this.HashToken, this.IfKeyword, this.Condition, this.EndOfDirectiveToken, this.IsActive, branchTaken, this.ConditionValue); public IfDirectiveTriviaSyntax WithConditionValue(bool conditionValue) => Update(this.HashToken, this.IfKeyword, this.Condition, this.EndOfDirectiveToken, this.IsActive, this.BranchTaken, conditionValue); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ElifDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class ElifDirectiveTriviaSyntax : ConditionalDirectiveTriviaSyntax { private ExpressionSyntax? condition; internal ElifDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ElifDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public SyntaxToken ElifKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ElifDirectiveTriviaSyntax)this.Green).elifKeyword, GetChildPosition(1), GetChildIndex(1)); public override ExpressionSyntax Condition => GetRed(ref this.condition, 2)!; public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ElifDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(3), GetChildIndex(3)); public override bool IsActive => ((Syntax.InternalSyntax.ElifDirectiveTriviaSyntax)this.Green).IsActive; public override bool BranchTaken => ((Syntax.InternalSyntax.ElifDirectiveTriviaSyntax)this.Green).BranchTaken; public override bool ConditionValue => ((Syntax.InternalSyntax.ElifDirectiveTriviaSyntax)this.Green).ConditionValue; internal override SyntaxNode? GetNodeSlot(int index) => index == 2 ? GetRed(ref this.condition, 2)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 2 ? this.condition : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitElifDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitElifDirectiveTrivia(this); public ElifDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken elifKeyword, ExpressionSyntax condition, SyntaxToken endOfDirectiveToken, bool isActive, bool branchTaken, bool conditionValue) { if (hashToken != this.HashToken || elifKeyword != this.ElifKeyword || condition != this.Condition || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.ElifDirectiveTrivia(hashToken, elifKeyword, condition, endOfDirectiveToken, isActive, branchTaken, conditionValue); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new ElifDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.ElifKeyword, this.Condition, this.EndOfDirectiveToken, this.IsActive, this.BranchTaken, this.ConditionValue); public ElifDirectiveTriviaSyntax WithElifKeyword(SyntaxToken elifKeyword) => Update(this.HashToken, elifKeyword, this.Condition, this.EndOfDirectiveToken, this.IsActive, this.BranchTaken, this.ConditionValue); internal override ConditionalDirectiveTriviaSyntax WithConditionCore(ExpressionSyntax condition) => WithCondition(condition); public new ElifDirectiveTriviaSyntax WithCondition(ExpressionSyntax condition) => Update(this.HashToken, this.ElifKeyword, condition, this.EndOfDirectiveToken, this.IsActive, this.BranchTaken, this.ConditionValue); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new ElifDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.ElifKeyword, this.Condition, endOfDirectiveToken, this.IsActive, this.BranchTaken, this.ConditionValue); public ElifDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.ElifKeyword, this.Condition, this.EndOfDirectiveToken, isActive, this.BranchTaken, this.ConditionValue); public ElifDirectiveTriviaSyntax WithBranchTaken(bool branchTaken) => Update(this.HashToken, this.ElifKeyword, this.Condition, this.EndOfDirectiveToken, this.IsActive, branchTaken, this.ConditionValue); public ElifDirectiveTriviaSyntax WithConditionValue(bool conditionValue) => Update(this.HashToken, this.ElifKeyword, this.Condition, this.EndOfDirectiveToken, this.IsActive, this.BranchTaken, conditionValue); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ElseDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class ElseDirectiveTriviaSyntax : BranchingDirectiveTriviaSyntax { internal ElseDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ElseDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public SyntaxToken ElseKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ElseDirectiveTriviaSyntax)this.Green).elseKeyword, GetChildPosition(1), GetChildIndex(1)); public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ElseDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(2), GetChildIndex(2)); public override bool IsActive => ((Syntax.InternalSyntax.ElseDirectiveTriviaSyntax)this.Green).IsActive; public override bool BranchTaken => ((Syntax.InternalSyntax.ElseDirectiveTriviaSyntax)this.Green).BranchTaken; internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitElseDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitElseDirectiveTrivia(this); public ElseDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken elseKeyword, SyntaxToken endOfDirectiveToken, bool isActive, bool branchTaken) { if (hashToken != this.HashToken || elseKeyword != this.ElseKeyword || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.ElseDirectiveTrivia(hashToken, elseKeyword, endOfDirectiveToken, isActive, branchTaken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new ElseDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.ElseKeyword, this.EndOfDirectiveToken, this.IsActive, this.BranchTaken); public ElseDirectiveTriviaSyntax WithElseKeyword(SyntaxToken elseKeyword) => Update(this.HashToken, elseKeyword, this.EndOfDirectiveToken, this.IsActive, this.BranchTaken); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new ElseDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.ElseKeyword, endOfDirectiveToken, this.IsActive, this.BranchTaken); public ElseDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.ElseKeyword, this.EndOfDirectiveToken, isActive, this.BranchTaken); public ElseDirectiveTriviaSyntax WithBranchTaken(bool branchTaken) => Update(this.HashToken, this.ElseKeyword, this.EndOfDirectiveToken, this.IsActive, branchTaken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.EndIfDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class EndIfDirectiveTriviaSyntax : DirectiveTriviaSyntax { internal EndIfDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.EndIfDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public SyntaxToken EndIfKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.EndIfDirectiveTriviaSyntax)this.Green).endIfKeyword, GetChildPosition(1), GetChildIndex(1)); public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.EndIfDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(2), GetChildIndex(2)); public override bool IsActive => ((Syntax.InternalSyntax.EndIfDirectiveTriviaSyntax)this.Green).IsActive; internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitEndIfDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitEndIfDirectiveTrivia(this); public EndIfDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken endIfKeyword, SyntaxToken endOfDirectiveToken, bool isActive) { if (hashToken != this.HashToken || endIfKeyword != this.EndIfKeyword || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.EndIfDirectiveTrivia(hashToken, endIfKeyword, endOfDirectiveToken, isActive); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new EndIfDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.EndIfKeyword, this.EndOfDirectiveToken, this.IsActive); public EndIfDirectiveTriviaSyntax WithEndIfKeyword(SyntaxToken endIfKeyword) => Update(this.HashToken, endIfKeyword, this.EndOfDirectiveToken, this.IsActive); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new EndIfDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.EndIfKeyword, endOfDirectiveToken, this.IsActive); public EndIfDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.EndIfKeyword, this.EndOfDirectiveToken, isActive); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.RegionDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class RegionDirectiveTriviaSyntax : DirectiveTriviaSyntax { internal RegionDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.RegionDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public SyntaxToken RegionKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.RegionDirectiveTriviaSyntax)this.Green).regionKeyword, GetChildPosition(1), GetChildIndex(1)); public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.RegionDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(2), GetChildIndex(2)); public override bool IsActive => ((Syntax.InternalSyntax.RegionDirectiveTriviaSyntax)this.Green).IsActive; internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitRegionDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitRegionDirectiveTrivia(this); public RegionDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken regionKeyword, SyntaxToken endOfDirectiveToken, bool isActive) { if (hashToken != this.HashToken || regionKeyword != this.RegionKeyword || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.RegionDirectiveTrivia(hashToken, regionKeyword, endOfDirectiveToken, isActive); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new RegionDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.RegionKeyword, this.EndOfDirectiveToken, this.IsActive); public RegionDirectiveTriviaSyntax WithRegionKeyword(SyntaxToken regionKeyword) => Update(this.HashToken, regionKeyword, this.EndOfDirectiveToken, this.IsActive); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new RegionDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.RegionKeyword, endOfDirectiveToken, this.IsActive); public RegionDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.RegionKeyword, this.EndOfDirectiveToken, isActive); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.EndRegionDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class EndRegionDirectiveTriviaSyntax : DirectiveTriviaSyntax { internal EndRegionDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.EndRegionDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public SyntaxToken EndRegionKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.EndRegionDirectiveTriviaSyntax)this.Green).endRegionKeyword, GetChildPosition(1), GetChildIndex(1)); public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.EndRegionDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(2), GetChildIndex(2)); public override bool IsActive => ((Syntax.InternalSyntax.EndRegionDirectiveTriviaSyntax)this.Green).IsActive; internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitEndRegionDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitEndRegionDirectiveTrivia(this); public EndRegionDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken endRegionKeyword, SyntaxToken endOfDirectiveToken, bool isActive) { if (hashToken != this.HashToken || endRegionKeyword != this.EndRegionKeyword || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.EndRegionDirectiveTrivia(hashToken, endRegionKeyword, endOfDirectiveToken, isActive); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new EndRegionDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.EndRegionKeyword, this.EndOfDirectiveToken, this.IsActive); public EndRegionDirectiveTriviaSyntax WithEndRegionKeyword(SyntaxToken endRegionKeyword) => Update(this.HashToken, endRegionKeyword, this.EndOfDirectiveToken, this.IsActive); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new EndRegionDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.EndRegionKeyword, endOfDirectiveToken, this.IsActive); public EndRegionDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.EndRegionKeyword, this.EndOfDirectiveToken, isActive); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ErrorDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class ErrorDirectiveTriviaSyntax : DirectiveTriviaSyntax { internal ErrorDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ErrorDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public SyntaxToken ErrorKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ErrorDirectiveTriviaSyntax)this.Green).errorKeyword, GetChildPosition(1), GetChildIndex(1)); public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ErrorDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(2), GetChildIndex(2)); public override bool IsActive => ((Syntax.InternalSyntax.ErrorDirectiveTriviaSyntax)this.Green).IsActive; internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitErrorDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitErrorDirectiveTrivia(this); public ErrorDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken errorKeyword, SyntaxToken endOfDirectiveToken, bool isActive) { if (hashToken != this.HashToken || errorKeyword != this.ErrorKeyword || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.ErrorDirectiveTrivia(hashToken, errorKeyword, endOfDirectiveToken, isActive); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new ErrorDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.ErrorKeyword, this.EndOfDirectiveToken, this.IsActive); public ErrorDirectiveTriviaSyntax WithErrorKeyword(SyntaxToken errorKeyword) => Update(this.HashToken, errorKeyword, this.EndOfDirectiveToken, this.IsActive); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new ErrorDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.ErrorKeyword, endOfDirectiveToken, this.IsActive); public ErrorDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.ErrorKeyword, this.EndOfDirectiveToken, isActive); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.WarningDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class WarningDirectiveTriviaSyntax : DirectiveTriviaSyntax { internal WarningDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.WarningDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public SyntaxToken WarningKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.WarningDirectiveTriviaSyntax)this.Green).warningKeyword, GetChildPosition(1), GetChildIndex(1)); public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.WarningDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(2), GetChildIndex(2)); public override bool IsActive => ((Syntax.InternalSyntax.WarningDirectiveTriviaSyntax)this.Green).IsActive; internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitWarningDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitWarningDirectiveTrivia(this); public WarningDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken warningKeyword, SyntaxToken endOfDirectiveToken, bool isActive) { if (hashToken != this.HashToken || warningKeyword != this.WarningKeyword || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.WarningDirectiveTrivia(hashToken, warningKeyword, endOfDirectiveToken, isActive); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new WarningDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.WarningKeyword, this.EndOfDirectiveToken, this.IsActive); public WarningDirectiveTriviaSyntax WithWarningKeyword(SyntaxToken warningKeyword) => Update(this.HashToken, warningKeyword, this.EndOfDirectiveToken, this.IsActive); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new WarningDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.WarningKeyword, endOfDirectiveToken, this.IsActive); public WarningDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.WarningKeyword, this.EndOfDirectiveToken, isActive); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.BadDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class BadDirectiveTriviaSyntax : DirectiveTriviaSyntax { internal BadDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.BadDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public SyntaxToken Identifier => new SyntaxToken(this, ((Syntax.InternalSyntax.BadDirectiveTriviaSyntax)this.Green).identifier, GetChildPosition(1), GetChildIndex(1)); public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.BadDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(2), GetChildIndex(2)); public override bool IsActive => ((Syntax.InternalSyntax.BadDirectiveTriviaSyntax)this.Green).IsActive; internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitBadDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitBadDirectiveTrivia(this); public BadDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken identifier, SyntaxToken endOfDirectiveToken, bool isActive) { if (hashToken != this.HashToken || identifier != this.Identifier || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.BadDirectiveTrivia(hashToken, identifier, endOfDirectiveToken, isActive); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new BadDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.Identifier, this.EndOfDirectiveToken, this.IsActive); public BadDirectiveTriviaSyntax WithIdentifier(SyntaxToken identifier) => Update(this.HashToken, identifier, this.EndOfDirectiveToken, this.IsActive); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new BadDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.Identifier, endOfDirectiveToken, this.IsActive); public BadDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.Identifier, this.EndOfDirectiveToken, isActive); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.DefineDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class DefineDirectiveTriviaSyntax : DirectiveTriviaSyntax { internal DefineDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.DefineDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public SyntaxToken DefineKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.DefineDirectiveTriviaSyntax)this.Green).defineKeyword, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken Name => new SyntaxToken(this, ((Syntax.InternalSyntax.DefineDirectiveTriviaSyntax)this.Green).name, GetChildPosition(2), GetChildIndex(2)); public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.DefineDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(3), GetChildIndex(3)); public override bool IsActive => ((Syntax.InternalSyntax.DefineDirectiveTriviaSyntax)this.Green).IsActive; internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitDefineDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitDefineDirectiveTrivia(this); public DefineDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken defineKeyword, SyntaxToken name, SyntaxToken endOfDirectiveToken, bool isActive) { if (hashToken != this.HashToken || defineKeyword != this.DefineKeyword || name != this.Name || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.DefineDirectiveTrivia(hashToken, defineKeyword, name, endOfDirectiveToken, isActive); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new DefineDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.DefineKeyword, this.Name, this.EndOfDirectiveToken, this.IsActive); public DefineDirectiveTriviaSyntax WithDefineKeyword(SyntaxToken defineKeyword) => Update(this.HashToken, defineKeyword, this.Name, this.EndOfDirectiveToken, this.IsActive); public DefineDirectiveTriviaSyntax WithName(SyntaxToken name) => Update(this.HashToken, this.DefineKeyword, name, this.EndOfDirectiveToken, this.IsActive); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new DefineDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.DefineKeyword, this.Name, endOfDirectiveToken, this.IsActive); public DefineDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.DefineKeyword, this.Name, this.EndOfDirectiveToken, isActive); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.UndefDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class UndefDirectiveTriviaSyntax : DirectiveTriviaSyntax { internal UndefDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.UndefDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public SyntaxToken UndefKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.UndefDirectiveTriviaSyntax)this.Green).undefKeyword, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken Name => new SyntaxToken(this, ((Syntax.InternalSyntax.UndefDirectiveTriviaSyntax)this.Green).name, GetChildPosition(2), GetChildIndex(2)); public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.UndefDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(3), GetChildIndex(3)); public override bool IsActive => ((Syntax.InternalSyntax.UndefDirectiveTriviaSyntax)this.Green).IsActive; internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitUndefDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitUndefDirectiveTrivia(this); public UndefDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken undefKeyword, SyntaxToken name, SyntaxToken endOfDirectiveToken, bool isActive) { if (hashToken != this.HashToken || undefKeyword != this.UndefKeyword || name != this.Name || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.UndefDirectiveTrivia(hashToken, undefKeyword, name, endOfDirectiveToken, isActive); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new UndefDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.UndefKeyword, this.Name, this.EndOfDirectiveToken, this.IsActive); public UndefDirectiveTriviaSyntax WithUndefKeyword(SyntaxToken undefKeyword) => Update(this.HashToken, undefKeyword, this.Name, this.EndOfDirectiveToken, this.IsActive); public UndefDirectiveTriviaSyntax WithName(SyntaxToken name) => Update(this.HashToken, this.UndefKeyword, name, this.EndOfDirectiveToken, this.IsActive); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new UndefDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.UndefKeyword, this.Name, endOfDirectiveToken, this.IsActive); public UndefDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.UndefKeyword, this.Name, this.EndOfDirectiveToken, isActive); } public abstract partial class LineOrSpanDirectiveTriviaSyntax : DirectiveTriviaSyntax { internal LineOrSpanDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public abstract SyntaxToken LineKeyword { get; } public LineOrSpanDirectiveTriviaSyntax WithLineKeyword(SyntaxToken lineKeyword) => WithLineKeywordCore(lineKeyword); internal abstract LineOrSpanDirectiveTriviaSyntax WithLineKeywordCore(SyntaxToken lineKeyword); public abstract SyntaxToken File { get; } public LineOrSpanDirectiveTriviaSyntax WithFile(SyntaxToken file) => WithFileCore(file); internal abstract LineOrSpanDirectiveTriviaSyntax WithFileCore(SyntaxToken file); public new LineOrSpanDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => (LineOrSpanDirectiveTriviaSyntax)WithHashTokenCore(hashToken); public new LineOrSpanDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => (LineOrSpanDirectiveTriviaSyntax)WithEndOfDirectiveTokenCore(endOfDirectiveToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.LineDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class LineDirectiveTriviaSyntax : LineOrSpanDirectiveTriviaSyntax { internal LineDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.LineDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public override SyntaxToken LineKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.LineDirectiveTriviaSyntax)this.Green).lineKeyword, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken Line => new SyntaxToken(this, ((Syntax.InternalSyntax.LineDirectiveTriviaSyntax)this.Green).line, GetChildPosition(2), GetChildIndex(2)); public override SyntaxToken File { get { var slot = ((Syntax.InternalSyntax.LineDirectiveTriviaSyntax)this.Green).file; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(3), GetChildIndex(3)) : default; } } public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.LineDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(4), GetChildIndex(4)); public override bool IsActive => ((Syntax.InternalSyntax.LineDirectiveTriviaSyntax)this.Green).IsActive; internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitLineDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitLineDirectiveTrivia(this); public LineDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken lineKeyword, SyntaxToken line, SyntaxToken file, SyntaxToken endOfDirectiveToken, bool isActive) { if (hashToken != this.HashToken || lineKeyword != this.LineKeyword || line != this.Line || file != this.File || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.LineDirectiveTrivia(hashToken, lineKeyword, line, file, endOfDirectiveToken, isActive); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new LineDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.LineKeyword, this.Line, this.File, this.EndOfDirectiveToken, this.IsActive); internal override LineOrSpanDirectiveTriviaSyntax WithLineKeywordCore(SyntaxToken lineKeyword) => WithLineKeyword(lineKeyword); public new LineDirectiveTriviaSyntax WithLineKeyword(SyntaxToken lineKeyword) => Update(this.HashToken, lineKeyword, this.Line, this.File, this.EndOfDirectiveToken, this.IsActive); public LineDirectiveTriviaSyntax WithLine(SyntaxToken line) => Update(this.HashToken, this.LineKeyword, line, this.File, this.EndOfDirectiveToken, this.IsActive); internal override LineOrSpanDirectiveTriviaSyntax WithFileCore(SyntaxToken file) => WithFile(file); public new LineDirectiveTriviaSyntax WithFile(SyntaxToken file) => Update(this.HashToken, this.LineKeyword, this.Line, file, this.EndOfDirectiveToken, this.IsActive); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new LineDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.LineKeyword, this.Line, this.File, endOfDirectiveToken, this.IsActive); public LineDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.LineKeyword, this.Line, this.File, this.EndOfDirectiveToken, isActive); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.LineDirectivePosition"/></description></item> /// </list> /// </remarks> public sealed partial class LineDirectivePositionSyntax : CSharpSyntaxNode { internal LineDirectivePositionSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public SyntaxToken OpenParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.LineDirectivePositionSyntax)this.Green).openParenToken, Position, 0); public SyntaxToken Line => new SyntaxToken(this, ((Syntax.InternalSyntax.LineDirectivePositionSyntax)this.Green).line, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken CommaToken => new SyntaxToken(this, ((Syntax.InternalSyntax.LineDirectivePositionSyntax)this.Green).commaToken, GetChildPosition(2), GetChildIndex(2)); public SyntaxToken Character => new SyntaxToken(this, ((Syntax.InternalSyntax.LineDirectivePositionSyntax)this.Green).character, GetChildPosition(3), GetChildIndex(3)); public SyntaxToken CloseParenToken => new SyntaxToken(this, ((Syntax.InternalSyntax.LineDirectivePositionSyntax)this.Green).closeParenToken, GetChildPosition(4), GetChildIndex(4)); internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitLineDirectivePosition(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitLineDirectivePosition(this); public LineDirectivePositionSyntax Update(SyntaxToken openParenToken, SyntaxToken line, SyntaxToken commaToken, SyntaxToken character, SyntaxToken closeParenToken) { if (openParenToken != this.OpenParenToken || line != this.Line || commaToken != this.CommaToken || character != this.Character || closeParenToken != this.CloseParenToken) { var newNode = SyntaxFactory.LineDirectivePosition(openParenToken, line, commaToken, character, closeParenToken); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } public LineDirectivePositionSyntax WithOpenParenToken(SyntaxToken openParenToken) => Update(openParenToken, this.Line, this.CommaToken, this.Character, this.CloseParenToken); public LineDirectivePositionSyntax WithLine(SyntaxToken line) => Update(this.OpenParenToken, line, this.CommaToken, this.Character, this.CloseParenToken); public LineDirectivePositionSyntax WithCommaToken(SyntaxToken commaToken) => Update(this.OpenParenToken, this.Line, commaToken, this.Character, this.CloseParenToken); public LineDirectivePositionSyntax WithCharacter(SyntaxToken character) => Update(this.OpenParenToken, this.Line, this.CommaToken, character, this.CloseParenToken); public LineDirectivePositionSyntax WithCloseParenToken(SyntaxToken closeParenToken) => Update(this.OpenParenToken, this.Line, this.CommaToken, this.Character, closeParenToken); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.LineSpanDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class LineSpanDirectiveTriviaSyntax : LineOrSpanDirectiveTriviaSyntax { private LineDirectivePositionSyntax? start; private LineDirectivePositionSyntax? end; internal LineSpanDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.LineSpanDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public override SyntaxToken LineKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.LineSpanDirectiveTriviaSyntax)this.Green).lineKeyword, GetChildPosition(1), GetChildIndex(1)); public LineDirectivePositionSyntax Start => GetRed(ref this.start, 2)!; public SyntaxToken MinusToken => new SyntaxToken(this, ((Syntax.InternalSyntax.LineSpanDirectiveTriviaSyntax)this.Green).minusToken, GetChildPosition(3), GetChildIndex(3)); public LineDirectivePositionSyntax End => GetRed(ref this.end, 4)!; public SyntaxToken CharacterOffset { get { var slot = ((Syntax.InternalSyntax.LineSpanDirectiveTriviaSyntax)this.Green).characterOffset; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(5), GetChildIndex(5)) : default; } } public override SyntaxToken File => new SyntaxToken(this, ((Syntax.InternalSyntax.LineSpanDirectiveTriviaSyntax)this.Green).file, GetChildPosition(6), GetChildIndex(6)); public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.LineSpanDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(7), GetChildIndex(7)); public override bool IsActive => ((Syntax.InternalSyntax.LineSpanDirectiveTriviaSyntax)this.Green).IsActive; internal override SyntaxNode? GetNodeSlot(int index) => index switch { 2 => GetRed(ref this.start, 2)!, 4 => GetRed(ref this.end, 4)!, _ => null, }; internal override SyntaxNode? GetCachedSlot(int index) => index switch { 2 => this.start, 4 => this.end, _ => null, }; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitLineSpanDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitLineSpanDirectiveTrivia(this); public LineSpanDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken lineKeyword, LineDirectivePositionSyntax start, SyntaxToken minusToken, LineDirectivePositionSyntax end, SyntaxToken characterOffset, SyntaxToken file, SyntaxToken endOfDirectiveToken, bool isActive) { if (hashToken != this.HashToken || lineKeyword != this.LineKeyword || start != this.Start || minusToken != this.MinusToken || end != this.End || characterOffset != this.CharacterOffset || file != this.File || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.LineSpanDirectiveTrivia(hashToken, lineKeyword, start, minusToken, end, characterOffset, file, endOfDirectiveToken, isActive); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new LineSpanDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.LineKeyword, this.Start, this.MinusToken, this.End, this.CharacterOffset, this.File, this.EndOfDirectiveToken, this.IsActive); internal override LineOrSpanDirectiveTriviaSyntax WithLineKeywordCore(SyntaxToken lineKeyword) => WithLineKeyword(lineKeyword); public new LineSpanDirectiveTriviaSyntax WithLineKeyword(SyntaxToken lineKeyword) => Update(this.HashToken, lineKeyword, this.Start, this.MinusToken, this.End, this.CharacterOffset, this.File, this.EndOfDirectiveToken, this.IsActive); public LineSpanDirectiveTriviaSyntax WithStart(LineDirectivePositionSyntax start) => Update(this.HashToken, this.LineKeyword, start, this.MinusToken, this.End, this.CharacterOffset, this.File, this.EndOfDirectiveToken, this.IsActive); public LineSpanDirectiveTriviaSyntax WithMinusToken(SyntaxToken minusToken) => Update(this.HashToken, this.LineKeyword, this.Start, minusToken, this.End, this.CharacterOffset, this.File, this.EndOfDirectiveToken, this.IsActive); public LineSpanDirectiveTriviaSyntax WithEnd(LineDirectivePositionSyntax end) => Update(this.HashToken, this.LineKeyword, this.Start, this.MinusToken, end, this.CharacterOffset, this.File, this.EndOfDirectiveToken, this.IsActive); public LineSpanDirectiveTriviaSyntax WithCharacterOffset(SyntaxToken characterOffset) => Update(this.HashToken, this.LineKeyword, this.Start, this.MinusToken, this.End, characterOffset, this.File, this.EndOfDirectiveToken, this.IsActive); internal override LineOrSpanDirectiveTriviaSyntax WithFileCore(SyntaxToken file) => WithFile(file); public new LineSpanDirectiveTriviaSyntax WithFile(SyntaxToken file) => Update(this.HashToken, this.LineKeyword, this.Start, this.MinusToken, this.End, this.CharacterOffset, file, this.EndOfDirectiveToken, this.IsActive); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new LineSpanDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.LineKeyword, this.Start, this.MinusToken, this.End, this.CharacterOffset, this.File, endOfDirectiveToken, this.IsActive); public LineSpanDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.LineKeyword, this.Start, this.MinusToken, this.End, this.CharacterOffset, this.File, this.EndOfDirectiveToken, isActive); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.PragmaWarningDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class PragmaWarningDirectiveTriviaSyntax : DirectiveTriviaSyntax { private SyntaxNode? errorCodes; internal PragmaWarningDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.PragmaWarningDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public SyntaxToken PragmaKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.PragmaWarningDirectiveTriviaSyntax)this.Green).pragmaKeyword, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken WarningKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.PragmaWarningDirectiveTriviaSyntax)this.Green).warningKeyword, GetChildPosition(2), GetChildIndex(2)); public SyntaxToken DisableOrRestoreKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.PragmaWarningDirectiveTriviaSyntax)this.Green).disableOrRestoreKeyword, GetChildPosition(3), GetChildIndex(3)); public SeparatedSyntaxList<ExpressionSyntax> ErrorCodes { get { var red = GetRed(ref this.errorCodes, 4); return red != null ? new SeparatedSyntaxList<ExpressionSyntax>(red, GetChildIndex(4)) : default; } } public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.PragmaWarningDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(5), GetChildIndex(5)); public override bool IsActive => ((Syntax.InternalSyntax.PragmaWarningDirectiveTriviaSyntax)this.Green).IsActive; internal override SyntaxNode? GetNodeSlot(int index) => index == 4 ? GetRed(ref this.errorCodes, 4)! : null; internal override SyntaxNode? GetCachedSlot(int index) => index == 4 ? this.errorCodes : null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitPragmaWarningDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitPragmaWarningDirectiveTrivia(this); public PragmaWarningDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken pragmaKeyword, SyntaxToken warningKeyword, SyntaxToken disableOrRestoreKeyword, SeparatedSyntaxList<ExpressionSyntax> errorCodes, SyntaxToken endOfDirectiveToken, bool isActive) { if (hashToken != this.HashToken || pragmaKeyword != this.PragmaKeyword || warningKeyword != this.WarningKeyword || disableOrRestoreKeyword != this.DisableOrRestoreKeyword || errorCodes != this.ErrorCodes || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.PragmaWarningDirectiveTrivia(hashToken, pragmaKeyword, warningKeyword, disableOrRestoreKeyword, errorCodes, endOfDirectiveToken, isActive); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new PragmaWarningDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.PragmaKeyword, this.WarningKeyword, this.DisableOrRestoreKeyword, this.ErrorCodes, this.EndOfDirectiveToken, this.IsActive); public PragmaWarningDirectiveTriviaSyntax WithPragmaKeyword(SyntaxToken pragmaKeyword) => Update(this.HashToken, pragmaKeyword, this.WarningKeyword, this.DisableOrRestoreKeyword, this.ErrorCodes, this.EndOfDirectiveToken, this.IsActive); public PragmaWarningDirectiveTriviaSyntax WithWarningKeyword(SyntaxToken warningKeyword) => Update(this.HashToken, this.PragmaKeyword, warningKeyword, this.DisableOrRestoreKeyword, this.ErrorCodes, this.EndOfDirectiveToken, this.IsActive); public PragmaWarningDirectiveTriviaSyntax WithDisableOrRestoreKeyword(SyntaxToken disableOrRestoreKeyword) => Update(this.HashToken, this.PragmaKeyword, this.WarningKeyword, disableOrRestoreKeyword, this.ErrorCodes, this.EndOfDirectiveToken, this.IsActive); public PragmaWarningDirectiveTriviaSyntax WithErrorCodes(SeparatedSyntaxList<ExpressionSyntax> errorCodes) => Update(this.HashToken, this.PragmaKeyword, this.WarningKeyword, this.DisableOrRestoreKeyword, errorCodes, this.EndOfDirectiveToken, this.IsActive); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new PragmaWarningDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.PragmaKeyword, this.WarningKeyword, this.DisableOrRestoreKeyword, this.ErrorCodes, endOfDirectiveToken, this.IsActive); public PragmaWarningDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.PragmaKeyword, this.WarningKeyword, this.DisableOrRestoreKeyword, this.ErrorCodes, this.EndOfDirectiveToken, isActive); public PragmaWarningDirectiveTriviaSyntax AddErrorCodes(params ExpressionSyntax[] items) => WithErrorCodes(this.ErrorCodes.AddRange(items)); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.PragmaChecksumDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class PragmaChecksumDirectiveTriviaSyntax : DirectiveTriviaSyntax { internal PragmaChecksumDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.PragmaChecksumDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public SyntaxToken PragmaKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.PragmaChecksumDirectiveTriviaSyntax)this.Green).pragmaKeyword, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken ChecksumKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.PragmaChecksumDirectiveTriviaSyntax)this.Green).checksumKeyword, GetChildPosition(2), GetChildIndex(2)); public SyntaxToken File => new SyntaxToken(this, ((Syntax.InternalSyntax.PragmaChecksumDirectiveTriviaSyntax)this.Green).file, GetChildPosition(3), GetChildIndex(3)); public SyntaxToken Guid => new SyntaxToken(this, ((Syntax.InternalSyntax.PragmaChecksumDirectiveTriviaSyntax)this.Green).guid, GetChildPosition(4), GetChildIndex(4)); public SyntaxToken Bytes => new SyntaxToken(this, ((Syntax.InternalSyntax.PragmaChecksumDirectiveTriviaSyntax)this.Green).bytes, GetChildPosition(5), GetChildIndex(5)); public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.PragmaChecksumDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(6), GetChildIndex(6)); public override bool IsActive => ((Syntax.InternalSyntax.PragmaChecksumDirectiveTriviaSyntax)this.Green).IsActive; internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitPragmaChecksumDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitPragmaChecksumDirectiveTrivia(this); public PragmaChecksumDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken pragmaKeyword, SyntaxToken checksumKeyword, SyntaxToken file, SyntaxToken guid, SyntaxToken bytes, SyntaxToken endOfDirectiveToken, bool isActive) { if (hashToken != this.HashToken || pragmaKeyword != this.PragmaKeyword || checksumKeyword != this.ChecksumKeyword || file != this.File || guid != this.Guid || bytes != this.Bytes || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.PragmaChecksumDirectiveTrivia(hashToken, pragmaKeyword, checksumKeyword, file, guid, bytes, endOfDirectiveToken, isActive); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new PragmaChecksumDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.PragmaKeyword, this.ChecksumKeyword, this.File, this.Guid, this.Bytes, this.EndOfDirectiveToken, this.IsActive); public PragmaChecksumDirectiveTriviaSyntax WithPragmaKeyword(SyntaxToken pragmaKeyword) => Update(this.HashToken, pragmaKeyword, this.ChecksumKeyword, this.File, this.Guid, this.Bytes, this.EndOfDirectiveToken, this.IsActive); public PragmaChecksumDirectiveTriviaSyntax WithChecksumKeyword(SyntaxToken checksumKeyword) => Update(this.HashToken, this.PragmaKeyword, checksumKeyword, this.File, this.Guid, this.Bytes, this.EndOfDirectiveToken, this.IsActive); public PragmaChecksumDirectiveTriviaSyntax WithFile(SyntaxToken file) => Update(this.HashToken, this.PragmaKeyword, this.ChecksumKeyword, file, this.Guid, this.Bytes, this.EndOfDirectiveToken, this.IsActive); public PragmaChecksumDirectiveTriviaSyntax WithGuid(SyntaxToken guid) => Update(this.HashToken, this.PragmaKeyword, this.ChecksumKeyword, this.File, guid, this.Bytes, this.EndOfDirectiveToken, this.IsActive); public PragmaChecksumDirectiveTriviaSyntax WithBytes(SyntaxToken bytes) => Update(this.HashToken, this.PragmaKeyword, this.ChecksumKeyword, this.File, this.Guid, bytes, this.EndOfDirectiveToken, this.IsActive); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new PragmaChecksumDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.PragmaKeyword, this.ChecksumKeyword, this.File, this.Guid, this.Bytes, endOfDirectiveToken, this.IsActive); public PragmaChecksumDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.PragmaKeyword, this.ChecksumKeyword, this.File, this.Guid, this.Bytes, this.EndOfDirectiveToken, isActive); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ReferenceDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class ReferenceDirectiveTriviaSyntax : DirectiveTriviaSyntax { internal ReferenceDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ReferenceDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public SyntaxToken ReferenceKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.ReferenceDirectiveTriviaSyntax)this.Green).referenceKeyword, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken File => new SyntaxToken(this, ((Syntax.InternalSyntax.ReferenceDirectiveTriviaSyntax)this.Green).file, GetChildPosition(2), GetChildIndex(2)); public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ReferenceDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(3), GetChildIndex(3)); public override bool IsActive => ((Syntax.InternalSyntax.ReferenceDirectiveTriviaSyntax)this.Green).IsActive; internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitReferenceDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitReferenceDirectiveTrivia(this); public ReferenceDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken referenceKeyword, SyntaxToken file, SyntaxToken endOfDirectiveToken, bool isActive) { if (hashToken != this.HashToken || referenceKeyword != this.ReferenceKeyword || file != this.File || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.ReferenceDirectiveTrivia(hashToken, referenceKeyword, file, endOfDirectiveToken, isActive); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new ReferenceDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.ReferenceKeyword, this.File, this.EndOfDirectiveToken, this.IsActive); public ReferenceDirectiveTriviaSyntax WithReferenceKeyword(SyntaxToken referenceKeyword) => Update(this.HashToken, referenceKeyword, this.File, this.EndOfDirectiveToken, this.IsActive); public ReferenceDirectiveTriviaSyntax WithFile(SyntaxToken file) => Update(this.HashToken, this.ReferenceKeyword, file, this.EndOfDirectiveToken, this.IsActive); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new ReferenceDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.ReferenceKeyword, this.File, endOfDirectiveToken, this.IsActive); public ReferenceDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.ReferenceKeyword, this.File, this.EndOfDirectiveToken, isActive); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.LoadDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class LoadDirectiveTriviaSyntax : DirectiveTriviaSyntax { internal LoadDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.LoadDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public SyntaxToken LoadKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.LoadDirectiveTriviaSyntax)this.Green).loadKeyword, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken File => new SyntaxToken(this, ((Syntax.InternalSyntax.LoadDirectiveTriviaSyntax)this.Green).file, GetChildPosition(2), GetChildIndex(2)); public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.LoadDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(3), GetChildIndex(3)); public override bool IsActive => ((Syntax.InternalSyntax.LoadDirectiveTriviaSyntax)this.Green).IsActive; internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitLoadDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitLoadDirectiveTrivia(this); public LoadDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken loadKeyword, SyntaxToken file, SyntaxToken endOfDirectiveToken, bool isActive) { if (hashToken != this.HashToken || loadKeyword != this.LoadKeyword || file != this.File || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.LoadDirectiveTrivia(hashToken, loadKeyword, file, endOfDirectiveToken, isActive); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new LoadDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.LoadKeyword, this.File, this.EndOfDirectiveToken, this.IsActive); public LoadDirectiveTriviaSyntax WithLoadKeyword(SyntaxToken loadKeyword) => Update(this.HashToken, loadKeyword, this.File, this.EndOfDirectiveToken, this.IsActive); public LoadDirectiveTriviaSyntax WithFile(SyntaxToken file) => Update(this.HashToken, this.LoadKeyword, file, this.EndOfDirectiveToken, this.IsActive); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new LoadDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.LoadKeyword, this.File, endOfDirectiveToken, this.IsActive); public LoadDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.LoadKeyword, this.File, this.EndOfDirectiveToken, isActive); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.ShebangDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class ShebangDirectiveTriviaSyntax : DirectiveTriviaSyntax { internal ShebangDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ShebangDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public SyntaxToken ExclamationToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ShebangDirectiveTriviaSyntax)this.Green).exclamationToken, GetChildPosition(1), GetChildIndex(1)); public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.ShebangDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(2), GetChildIndex(2)); public override bool IsActive => ((Syntax.InternalSyntax.ShebangDirectiveTriviaSyntax)this.Green).IsActive; internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitShebangDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitShebangDirectiveTrivia(this); public ShebangDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken exclamationToken, SyntaxToken endOfDirectiveToken, bool isActive) { if (hashToken != this.HashToken || exclamationToken != this.ExclamationToken || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.ShebangDirectiveTrivia(hashToken, exclamationToken, endOfDirectiveToken, isActive); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new ShebangDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.ExclamationToken, this.EndOfDirectiveToken, this.IsActive); public ShebangDirectiveTriviaSyntax WithExclamationToken(SyntaxToken exclamationToken) => Update(this.HashToken, exclamationToken, this.EndOfDirectiveToken, this.IsActive); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new ShebangDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.ExclamationToken, endOfDirectiveToken, this.IsActive); public ShebangDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.ExclamationToken, this.EndOfDirectiveToken, isActive); } /// <remarks> /// <para>This node is associated with the following syntax kinds:</para> /// <list type="bullet"> /// <item><description><see cref="SyntaxKind.NullableDirectiveTrivia"/></description></item> /// </list> /// </remarks> public sealed partial class NullableDirectiveTriviaSyntax : DirectiveTriviaSyntax { internal NullableDirectiveTriviaSyntax(InternalSyntax.CSharpSyntaxNode green, SyntaxNode? parent, int position) : base(green, parent, position) { } public override SyntaxToken HashToken => new SyntaxToken(this, ((Syntax.InternalSyntax.NullableDirectiveTriviaSyntax)this.Green).hashToken, Position, 0); public SyntaxToken NullableKeyword => new SyntaxToken(this, ((Syntax.InternalSyntax.NullableDirectiveTriviaSyntax)this.Green).nullableKeyword, GetChildPosition(1), GetChildIndex(1)); public SyntaxToken SettingToken => new SyntaxToken(this, ((Syntax.InternalSyntax.NullableDirectiveTriviaSyntax)this.Green).settingToken, GetChildPosition(2), GetChildIndex(2)); public SyntaxToken TargetToken { get { var slot = ((Syntax.InternalSyntax.NullableDirectiveTriviaSyntax)this.Green).targetToken; return slot != null ? new SyntaxToken(this, slot, GetChildPosition(3), GetChildIndex(3)) : default; } } public override SyntaxToken EndOfDirectiveToken => new SyntaxToken(this, ((Syntax.InternalSyntax.NullableDirectiveTriviaSyntax)this.Green).endOfDirectiveToken, GetChildPosition(4), GetChildIndex(4)); public override bool IsActive => ((Syntax.InternalSyntax.NullableDirectiveTriviaSyntax)this.Green).IsActive; internal override SyntaxNode? GetNodeSlot(int index) => null; internal override SyntaxNode? GetCachedSlot(int index) => null; public override void Accept(CSharpSyntaxVisitor visitor) => visitor.VisitNullableDirectiveTrivia(this); public override TResult? Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor) where TResult : default => visitor.VisitNullableDirectiveTrivia(this); public NullableDirectiveTriviaSyntax Update(SyntaxToken hashToken, SyntaxToken nullableKeyword, SyntaxToken settingToken, SyntaxToken targetToken, SyntaxToken endOfDirectiveToken, bool isActive) { if (hashToken != this.HashToken || nullableKeyword != this.NullableKeyword || settingToken != this.SettingToken || targetToken != this.TargetToken || endOfDirectiveToken != this.EndOfDirectiveToken) { var newNode = SyntaxFactory.NullableDirectiveTrivia(hashToken, nullableKeyword, settingToken, targetToken, endOfDirectiveToken, isActive); var annotations = GetAnnotations(); return annotations?.Length > 0 ? newNode.WithAnnotations(annotations) : newNode; } return this; } internal override DirectiveTriviaSyntax WithHashTokenCore(SyntaxToken hashToken) => WithHashToken(hashToken); public new NullableDirectiveTriviaSyntax WithHashToken(SyntaxToken hashToken) => Update(hashToken, this.NullableKeyword, this.SettingToken, this.TargetToken, this.EndOfDirectiveToken, this.IsActive); public NullableDirectiveTriviaSyntax WithNullableKeyword(SyntaxToken nullableKeyword) => Update(this.HashToken, nullableKeyword, this.SettingToken, this.TargetToken, this.EndOfDirectiveToken, this.IsActive); public NullableDirectiveTriviaSyntax WithSettingToken(SyntaxToken settingToken) => Update(this.HashToken, this.NullableKeyword, settingToken, this.TargetToken, this.EndOfDirectiveToken, this.IsActive); public NullableDirectiveTriviaSyntax WithTargetToken(SyntaxToken targetToken) => Update(this.HashToken, this.NullableKeyword, this.SettingToken, targetToken, this.EndOfDirectiveToken, this.IsActive); internal override DirectiveTriviaSyntax WithEndOfDirectiveTokenCore(SyntaxToken endOfDirectiveToken) => WithEndOfDirectiveToken(endOfDirectiveToken); public new NullableDirectiveTriviaSyntax WithEndOfDirectiveToken(SyntaxToken endOfDirectiveToken) => Update(this.HashToken, this.NullableKeyword, this.SettingToken, this.TargetToken, endOfDirectiveToken, this.IsActive); public NullableDirectiveTriviaSyntax WithIsActive(bool isActive) => Update(this.HashToken, this.NullableKeyword, this.SettingToken, this.TargetToken, this.EndOfDirectiveToken, isActive); } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/VisualStudio/CSharp/Test/ProjectSystemShim/CSharpHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.UnitTests; using Microsoft.VisualStudio; using Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim; using Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.CPS; using Microsoft.VisualStudio.LanguageServices.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework; using Microsoft.VisualStudio.Shell.Interop; using Xunit; namespace Roslyn.VisualStudio.CSharp.UnitTests.ProjectSystemShim { internal static class CSharpHelpers { public static CSharpProjectShim CreateCSharpProject(TestEnvironment environment, string projectName) { var projectBinPath = Path.GetTempPath(); var hierarchy = environment.CreateHierarchy(projectName, projectBinPath, projectRefPath: null, projectCapabilities: "CSharp"); return CreateCSharpProject(environment, projectName, hierarchy); } public static CSharpProjectShim CreateCSharpProject(TestEnvironment environment, string projectName, IVsHierarchy hierarchy) { return new CSharpProjectShim( new MockCSharpProjectRoot(hierarchy), projectSystemName: projectName, hierarchy: hierarchy, serviceProvider: environment.ServiceProvider, threadingContext: environment.ThreadingContext); } public static Task<CPSProject> CreateCSharpCPSProjectAsync(TestEnvironment environment, string projectName, params string[] commandLineArguments) { return CreateCSharpCPSProjectAsync(environment, projectName, projectGuid: Guid.NewGuid(), commandLineArguments: commandLineArguments); } public static Task<CPSProject> CreateCSharpCPSProjectAsync(TestEnvironment environment, string projectName, Guid projectGuid, params string[] commandLineArguments) { var projectFilePath = Path.GetTempPath(); var binOutputPath = GetOutputPathFromArguments(commandLineArguments) ?? Path.Combine(projectFilePath, projectName + ".dll"); return CreateCSharpCPSProjectAsync(environment, projectName, projectFilePath, binOutputPath, projectGuid, commandLineArguments); } public static Task<CPSProject> CreateCSharpCPSProjectAsync(TestEnvironment environment, string projectName, string binOutputPath, params string[] commandLineArguments) { var projectFilePath = Path.GetTempPath(); return CreateCSharpCPSProjectAsync(environment, projectName, projectFilePath, binOutputPath, projectGuid: Guid.NewGuid(), commandLineArguments: commandLineArguments); } public static unsafe void SetOption(this CSharpProjectShim csharpProject, CompilerOptions optionID, object value) { Assert.Equal(sizeof(HACK_VariantStructure), 8 + 2 * IntPtr.Size); Assert.Equal(8, (int)Marshal.OffsetOf<HACK_VariantStructure>("_booleanValue")); HACK_VariantStructure variant = default; Marshal.GetNativeVariantForObject(value, (IntPtr)(&variant)); csharpProject.SetOption(optionID, variant); } public static async Task<CPSProject> CreateCSharpCPSProjectAsync(TestEnvironment environment, string projectName, string projectFilePath, string binOutputPath, Guid projectGuid, params string[] commandLineArguments) { var hierarchy = environment.CreateHierarchy(projectName, binOutputPath, projectRefPath: null, "CSharp"); var cpsProjectFactory = environment.ExportProvider.GetExportedValue<IWorkspaceProjectContextFactory>(); var cpsProject = (CPSProject)await cpsProjectFactory.CreateProjectContextAsync( LanguageNames.CSharp, projectName, projectFilePath, projectGuid, hierarchy, binOutputPath, assemblyName: null, CancellationToken.None); cpsProject.SetOptions(ImmutableArray.Create(commandLineArguments)); return cpsProject; } public static async Task<CPSProject> CreateNonCompilableProjectAsync(TestEnvironment environment, string projectName, string projectFilePath) { var hierarchy = environment.CreateHierarchy(projectName, projectBinPath: null, projectRefPath: null, ""); var cpsProjectFactory = environment.ExportProvider.GetExportedValue<IWorkspaceProjectContextFactory>(); return (CPSProject)await cpsProjectFactory.CreateProjectContextAsync( NoCompilationConstants.LanguageName, projectName, projectFilePath, Guid.NewGuid(), hierarchy, binOutputPath: null, assemblyName: null, CancellationToken.None); } private static string GetOutputPathFromArguments(string[] commandLineArguments) { const string outPrefix = "/out:"; string outputPath = null; foreach (var arg in commandLineArguments) { var index = arg.IndexOf(outPrefix); if (index >= 0) { outputPath = arg.Substring(index + outPrefix.Length); } } return outputPath; } private sealed class TestCSharpCommandLineParserService : ICommandLineParserService { public CommandLineArguments Parse(IEnumerable<string> arguments, string baseDirectory, bool isInteractive, string sdkDirectory) { if (baseDirectory == null || !Directory.Exists(baseDirectory)) { baseDirectory = Path.GetTempPath(); } return CSharpCommandLineParser.Default.Parse(arguments, baseDirectory, sdkDirectory); } } private class MockCSharpProjectRoot : ICSharpProjectRoot { private readonly IVsHierarchy _hierarchy; public MockCSharpProjectRoot(IVsHierarchy hierarchy) { _hierarchy = hierarchy; } int ICSharpProjectRoot.BelongsToProject(string pszFileName) { throw new NotImplementedException(); } string ICSharpProjectRoot.BuildPerConfigCacheFileName() { throw new NotImplementedException(); } bool ICSharpProjectRoot.CanCreateFileCodeModel(string pszFile) { throw new NotImplementedException(); } void ICSharpProjectRoot.ConfigureCompiler(ICSCompiler compiler, ICSInputSet inputSet, bool addSources) { throw new NotImplementedException(); } object ICSharpProjectRoot.CreateFileCodeModel(string pszFile, ref Guid riid) { throw new NotImplementedException(); } string ICSharpProjectRoot.GetActiveConfigurationName() { throw new NotImplementedException(); } string ICSharpProjectRoot.GetFullProjectName() { throw new NotImplementedException(); } int ICSharpProjectRoot.GetHierarchyAndItemID(string pszFile, out IVsHierarchy ppHier, out uint pItemID) { ppHier = _hierarchy; // Each item should have it's own ItemID, but for simplicity we'll just hard-code a value of // no particular significance. pItemID = 42; return VSConstants.S_OK; } void ICSharpProjectRoot.GetHierarchyAndItemIDOptionallyInProject(string pszFile, out IVsHierarchy ppHier, out uint pItemID, bool mustBeInProject) { throw new NotImplementedException(); } string ICSharpProjectRoot.GetProjectLocation() { throw new NotImplementedException(); } object ICSharpProjectRoot.GetProjectSite(ref Guid riid) { throw new NotImplementedException(); } void ICSharpProjectRoot.SetProjectSite(ICSharpProjectSite site) { 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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.UnitTests; using Microsoft.VisualStudio; using Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim; using Microsoft.VisualStudio.LanguageServices.CSharp.ProjectSystemShim.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.CPS; using Microsoft.VisualStudio.LanguageServices.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework; using Microsoft.VisualStudio.Shell.Interop; using Xunit; namespace Roslyn.VisualStudio.CSharp.UnitTests.ProjectSystemShim { internal static class CSharpHelpers { public static CSharpProjectShim CreateCSharpProject(TestEnvironment environment, string projectName) { var projectBinPath = Path.GetTempPath(); var hierarchy = environment.CreateHierarchy(projectName, projectBinPath, projectRefPath: null, projectCapabilities: "CSharp"); return CreateCSharpProject(environment, projectName, hierarchy); } public static CSharpProjectShim CreateCSharpProject(TestEnvironment environment, string projectName, IVsHierarchy hierarchy) { return new CSharpProjectShim( new MockCSharpProjectRoot(hierarchy), projectSystemName: projectName, hierarchy: hierarchy, serviceProvider: environment.ServiceProvider, threadingContext: environment.ThreadingContext); } public static Task<CPSProject> CreateCSharpCPSProjectAsync(TestEnvironment environment, string projectName, params string[] commandLineArguments) { return CreateCSharpCPSProjectAsync(environment, projectName, projectGuid: Guid.NewGuid(), commandLineArguments: commandLineArguments); } public static Task<CPSProject> CreateCSharpCPSProjectAsync(TestEnvironment environment, string projectName, Guid projectGuid, params string[] commandLineArguments) { var projectFilePath = Path.GetTempPath(); var binOutputPath = GetOutputPathFromArguments(commandLineArguments) ?? Path.Combine(projectFilePath, projectName + ".dll"); return CreateCSharpCPSProjectAsync(environment, projectName, projectFilePath, binOutputPath, projectGuid, commandLineArguments); } public static Task<CPSProject> CreateCSharpCPSProjectAsync(TestEnvironment environment, string projectName, string binOutputPath, params string[] commandLineArguments) { var projectFilePath = Path.GetTempPath(); return CreateCSharpCPSProjectAsync(environment, projectName, projectFilePath, binOutputPath, projectGuid: Guid.NewGuid(), commandLineArguments: commandLineArguments); } public static unsafe void SetOption(this CSharpProjectShim csharpProject, CompilerOptions optionID, object value) { Assert.Equal(sizeof(HACK_VariantStructure), 8 + 2 * IntPtr.Size); Assert.Equal(8, (int)Marshal.OffsetOf<HACK_VariantStructure>("_booleanValue")); HACK_VariantStructure variant = default; Marshal.GetNativeVariantForObject(value, (IntPtr)(&variant)); csharpProject.SetOption(optionID, variant); } public static async Task<CPSProject> CreateCSharpCPSProjectAsync(TestEnvironment environment, string projectName, string projectFilePath, string binOutputPath, Guid projectGuid, params string[] commandLineArguments) { var hierarchy = environment.CreateHierarchy(projectName, binOutputPath, projectRefPath: null, "CSharp"); var cpsProjectFactory = environment.ExportProvider.GetExportedValue<IWorkspaceProjectContextFactory>(); var cpsProject = (CPSProject)await cpsProjectFactory.CreateProjectContextAsync( LanguageNames.CSharp, projectName, projectFilePath, projectGuid, hierarchy, binOutputPath, assemblyName: null, CancellationToken.None); cpsProject.SetOptions(ImmutableArray.Create(commandLineArguments)); return cpsProject; } public static async Task<CPSProject> CreateNonCompilableProjectAsync(TestEnvironment environment, string projectName, string projectFilePath) { var hierarchy = environment.CreateHierarchy(projectName, projectBinPath: null, projectRefPath: null, ""); var cpsProjectFactory = environment.ExportProvider.GetExportedValue<IWorkspaceProjectContextFactory>(); return (CPSProject)await cpsProjectFactory.CreateProjectContextAsync( NoCompilationConstants.LanguageName, projectName, projectFilePath, Guid.NewGuid(), hierarchy, binOutputPath: null, assemblyName: null, CancellationToken.None); } private static string GetOutputPathFromArguments(string[] commandLineArguments) { const string outPrefix = "/out:"; string outputPath = null; foreach (var arg in commandLineArguments) { var index = arg.IndexOf(outPrefix); if (index >= 0) { outputPath = arg.Substring(index + outPrefix.Length); } } return outputPath; } private sealed class TestCSharpCommandLineParserService : ICommandLineParserService { public CommandLineArguments Parse(IEnumerable<string> arguments, string baseDirectory, bool isInteractive, string sdkDirectory) { if (baseDirectory == null || !Directory.Exists(baseDirectory)) { baseDirectory = Path.GetTempPath(); } return CSharpCommandLineParser.Default.Parse(arguments, baseDirectory, sdkDirectory); } } private class MockCSharpProjectRoot : ICSharpProjectRoot { private readonly IVsHierarchy _hierarchy; public MockCSharpProjectRoot(IVsHierarchy hierarchy) { _hierarchy = hierarchy; } int ICSharpProjectRoot.BelongsToProject(string pszFileName) { throw new NotImplementedException(); } string ICSharpProjectRoot.BuildPerConfigCacheFileName() { throw new NotImplementedException(); } bool ICSharpProjectRoot.CanCreateFileCodeModel(string pszFile) { throw new NotImplementedException(); } void ICSharpProjectRoot.ConfigureCompiler(ICSCompiler compiler, ICSInputSet inputSet, bool addSources) { throw new NotImplementedException(); } object ICSharpProjectRoot.CreateFileCodeModel(string pszFile, ref Guid riid) { throw new NotImplementedException(); } string ICSharpProjectRoot.GetActiveConfigurationName() { throw new NotImplementedException(); } string ICSharpProjectRoot.GetFullProjectName() { throw new NotImplementedException(); } int ICSharpProjectRoot.GetHierarchyAndItemID(string pszFile, out IVsHierarchy ppHier, out uint pItemID) { ppHier = _hierarchy; // Each item should have it's own ItemID, but for simplicity we'll just hard-code a value of // no particular significance. pItemID = 42; return VSConstants.S_OK; } void ICSharpProjectRoot.GetHierarchyAndItemIDOptionallyInProject(string pszFile, out IVsHierarchy ppHier, out uint pItemID, bool mustBeInProject) { throw new NotImplementedException(); } string ICSharpProjectRoot.GetProjectLocation() { throw new NotImplementedException(); } object ICSharpProjectRoot.GetProjectSite(ref Guid riid) { throw new NotImplementedException(); } void ICSharpProjectRoot.SetProjectSite(ICSharpProjectSite site) { throw new NotImplementedException(); } } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/Core/MSBuild/MSBuild/ProjectFile/ProjectFileLoaderRegistry.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.CodeAnalysis; using System.IO; using Microsoft.CodeAnalysis.Host; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.MSBuild { internal class ProjectFileLoaderRegistry { private readonly HostWorkspaceServices _workspaceServices; private readonly DiagnosticReporter _diagnosticReporter; private readonly Dictionary<string, string> _extensionToLanguageMap; private readonly NonReentrantLock _dataGuard; public ProjectFileLoaderRegistry(HostWorkspaceServices workspaceServices, DiagnosticReporter diagnosticReporter) { _workspaceServices = workspaceServices; _diagnosticReporter = diagnosticReporter; _extensionToLanguageMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); _dataGuard = new NonReentrantLock(); } /// <summary> /// Associates a project file extension with a language name. /// </summary> public void AssociateFileExtensionWithLanguage(string fileExtension, string language) { using (_dataGuard.DisposableWait()) { _extensionToLanguageMap[fileExtension] = language; } } public bool TryGetLoaderFromProjectPath(string? projectFilePath, [NotNullWhen(true)] out IProjectFileLoader? loader) { return TryGetLoaderFromProjectPath(projectFilePath, DiagnosticReportingMode.Ignore, out loader); } public bool TryGetLoaderFromProjectPath(string? projectFilePath, DiagnosticReportingMode mode, [NotNullWhen(true)] out IProjectFileLoader? loader) { using (_dataGuard.DisposableWait()) { var extension = Path.GetExtension(projectFilePath); if (extension is null) { loader = null; _diagnosticReporter.Report(mode, $"Project file path was 'null'"); return false; } if (extension.Length > 0 && extension[0] == '.') { extension = extension[1..]; } if (_extensionToLanguageMap.TryGetValue(extension, out var language)) { if (_workspaceServices.SupportedLanguages.Contains(language)) { loader = _workspaceServices.GetLanguageServices(language).GetService<IProjectFileLoader>(); } else { loader = null; _diagnosticReporter.Report(mode, string.Format(WorkspacesResources.Cannot_open_project_0_because_the_language_1_is_not_supported, projectFilePath, language)); return false; } } else { loader = ProjectFileLoader.GetLoaderForProjectFileExtension(_workspaceServices, extension); if (loader == null) { _diagnosticReporter.Report(mode, string.Format(WorkspacesResources.Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language, projectFilePath, Path.GetExtension(projectFilePath))); return false; } } // since we have both C# and VB loaders in this same library, it no longer indicates whether we have full language support available. if (loader != null) { language = loader.Language; // check for command line parser existing... if not then error. var commandLineParser = _workspaceServices .GetLanguageServices(language) .GetService<ICommandLineParserService>(); if (commandLineParser == null) { loader = null; _diagnosticReporter.Report(mode, string.Format(WorkspacesResources.Cannot_open_project_0_because_the_language_1_is_not_supported, projectFilePath, language)); return false; } } return loader != null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using Microsoft.CodeAnalysis.Host; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.MSBuild { internal class ProjectFileLoaderRegistry { private readonly HostWorkspaceServices _workspaceServices; private readonly DiagnosticReporter _diagnosticReporter; private readonly Dictionary<string, string> _extensionToLanguageMap; private readonly NonReentrantLock _dataGuard; public ProjectFileLoaderRegistry(HostWorkspaceServices workspaceServices, DiagnosticReporter diagnosticReporter) { _workspaceServices = workspaceServices; _diagnosticReporter = diagnosticReporter; _extensionToLanguageMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); _dataGuard = new NonReentrantLock(); } /// <summary> /// Associates a project file extension with a language name. /// </summary> public void AssociateFileExtensionWithLanguage(string fileExtension, string language) { using (_dataGuard.DisposableWait()) { _extensionToLanguageMap[fileExtension] = language; } } public bool TryGetLoaderFromProjectPath(string? projectFilePath, [NotNullWhen(true)] out IProjectFileLoader? loader) { return TryGetLoaderFromProjectPath(projectFilePath, DiagnosticReportingMode.Ignore, out loader); } public bool TryGetLoaderFromProjectPath(string? projectFilePath, DiagnosticReportingMode mode, [NotNullWhen(true)] out IProjectFileLoader? loader) { using (_dataGuard.DisposableWait()) { var extension = Path.GetExtension(projectFilePath); if (extension is null) { loader = null; _diagnosticReporter.Report(mode, $"Project file path was 'null'"); return false; } if (extension.Length > 0 && extension[0] == '.') { extension = extension[1..]; } if (_extensionToLanguageMap.TryGetValue(extension, out var language)) { if (_workspaceServices.SupportedLanguages.Contains(language)) { loader = _workspaceServices.GetLanguageServices(language).GetService<IProjectFileLoader>(); } else { loader = null; _diagnosticReporter.Report(mode, string.Format(WorkspacesResources.Cannot_open_project_0_because_the_language_1_is_not_supported, projectFilePath, language)); return false; } } else { loader = ProjectFileLoader.GetLoaderForProjectFileExtension(_workspaceServices, extension); if (loader == null) { _diagnosticReporter.Report(mode, string.Format(WorkspacesResources.Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language, projectFilePath, Path.GetExtension(projectFilePath))); return false; } } // since we have both C# and VB loaders in this same library, it no longer indicates whether we have full language support available. if (loader != null) { language = loader.Language; // check for command line parser existing... if not then error. var commandLineParser = _workspaceServices .GetLanguageServices(language) .GetService<ICommandLineParserService>(); if (commandLineParser == null) { loader = null; _diagnosticReporter.Report(mode, string.Format(WorkspacesResources.Cannot_open_project_0_because_the_language_1_is_not_supported, projectFilePath, language)); return false; } } return loader != null; } } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/CSharpTest/Diagnostics/PreferFrameworkType/PreferFrameworkTypeTests_FixAllTests.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.Diagnostics.PreferFrameworkType { public partial class PreferFrameworkTypeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInDocument_DeclarationContext() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static int F(int x, System.Int16 y) { {|FixAllInDocument:int|} i1 = 0; System.Int16 s1 = 0; int i2 = 0; return i1 + s1 + i2; } } </Document> <Document> using System; class Program2 { static System.Int32 F(System.Int32 x, System.Int16 y) { System.Int32 i1 = 0; System.Int16 s1 = 0; System.Int32 i2 = 0; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static System.Int32 F(System.Int32 x, System.Int16 y) { System.Int32 i1 = 0; System.Int16 s1 = 0; System.Int32 i2 = 0; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static Int32 F(Int32 x, System.Int16 y) { Int32 i1 = 0; System.Int16 s1 = 0; Int32 i2 = 0; return i1 + s1 + i2; } } </Document> <Document> using System; class Program2 { static System.Int32 F(System.Int32 x, System.Int16 y) { System.Int32 i1 = 0; System.Int16 s1 = 0; System.Int32 i2 = 0; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static System.Int32 F(System.Int32 x, System.Int16 y) { System.Int32 i1 = 0; System.Int16 s1 = 0; System.Int32 i2 = 0; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, options: FrameworkTypeEverywhere); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInProject_DeclarationContext() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static int F(int x, System.Int16 y) { {|FixAllInProject:int|} i1 = 0; System.Int16 s1 = 0; int i2 = 0; return i1 + s1 + i2; } } </Document> <Document> using System; class Program2 { static int F(int x, System.Int16 y) { int i1 = 0; System.Int16 s1 = 0; int i2 = 0; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static System.Int32 F(System.Int32 x, System.Int16 y) { System.Int32 i1 = 0; System.Int16 s1 = 0; System.Int32 i2 = 0; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static Int32 F(Int32 x, System.Int16 y) { Int32 i1 = 0; System.Int16 s1 = 0; Int32 i2 = 0; return i1 + s1 + i2; } } </Document> <Document> using System; class Program2 { static Int32 F(Int32 x, System.Int16 y) { Int32 i1 = 0; System.Int16 s1 = 0; Int32 i2 = 0; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static System.Int32 F(System.Int32 x, System.Int16 y) { System.Int32 i1 = 0; System.Int16 s1 = 0; System.Int32 i2 = 0; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, options: FrameworkTypeEverywhere); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInSolution_DeclarationContext() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static int F(int x, System.Int16 y) { {|FixAllInSolution:int|} i1 = 0; System.Int16 s1 = 0; int i2 = 0; return i1 + s1 + i2; } } </Document> <Document> using System; class Program2 { static int F(int x, System.Int16 y) { int i1 = 0; System.Int16 s1 = 0; int i2 = 0; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static int F(int x, System.Int16 y) { int i1 = 0; System.Int16 s1 = 0; int i2 = 0; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static Int32 F(Int32 x, System.Int16 y) { Int32 i1 = 0; System.Int16 s1 = 0; Int32 i2 = 0; return i1 + s1 + i2; } } </Document> <Document> using System; class Program2 { static Int32 F(Int32 x, System.Int16 y) { Int32 i1 = 0; System.Int16 s1 = 0; Int32 i2 = 0; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static Int32 F(Int32 x, System.Int16 y) { Int32 i1 = 0; System.Int16 s1 = 0; Int32 i2 = 0; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, options: FrameworkTypeEverywhere); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInSolution_MemberAccessContext() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class ProgramA { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x; System.Int16 s1 = this.y; System.Int32 i2 = this.z; {|FixAllInSolution:int|}.Parse(i1 + s1 + i2); int.Parse(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> <Document> using System; class ProgramA2 { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x; System.Int16 s1 = this.y; System.Int32 i2 = this.z; int.Parse(i1 + s1 + i2); int.Parse(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class ProgramA3 { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x; System.Int16 s1 = this.y; System.Int32 i2 = this.z; int.Parse(i1 + s1 + i2); int.Parse(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class ProgramA { private Int32 x = 0; private Int32 y = 0; private Int32 z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x; System.Int16 s1 = this.y; System.Int32 i2 = this.z; Int32.Parse(i1 + s1 + i2); Int32.Parse(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> <Document> using System; class ProgramA2 { private Int32 x = 0; private Int32 y = 0; private Int32 z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x; System.Int16 s1 = this.y; System.Int32 i2 = this.z; Int32.Parse(i1 + s1 + i2); Int32.Parse(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class ProgramA3 { private Int32 x = 0; private Int32 y = 0; private Int32 z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x; System.Int16 s1 = this.y; System.Int32 i2 = this.z; Int32.Parse(i1 + s1 + i2); Int32.Parse(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, options: FrameworkTypeEverywhere); } } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics.PreferFrameworkType { public partial class PreferFrameworkTypeTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInDocument_DeclarationContext() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static int F(int x, System.Int16 y) { {|FixAllInDocument:int|} i1 = 0; System.Int16 s1 = 0; int i2 = 0; return i1 + s1 + i2; } } </Document> <Document> using System; class Program2 { static System.Int32 F(System.Int32 x, System.Int16 y) { System.Int32 i1 = 0; System.Int16 s1 = 0; System.Int32 i2 = 0; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static System.Int32 F(System.Int32 x, System.Int16 y) { System.Int32 i1 = 0; System.Int16 s1 = 0; System.Int32 i2 = 0; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static Int32 F(Int32 x, System.Int16 y) { Int32 i1 = 0; System.Int16 s1 = 0; Int32 i2 = 0; return i1 + s1 + i2; } } </Document> <Document> using System; class Program2 { static System.Int32 F(System.Int32 x, System.Int16 y) { System.Int32 i1 = 0; System.Int16 s1 = 0; System.Int32 i2 = 0; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static System.Int32 F(System.Int32 x, System.Int16 y) { System.Int32 i1 = 0; System.Int16 s1 = 0; System.Int32 i2 = 0; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, options: FrameworkTypeEverywhere); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInProject_DeclarationContext() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static int F(int x, System.Int16 y) { {|FixAllInProject:int|} i1 = 0; System.Int16 s1 = 0; int i2 = 0; return i1 + s1 + i2; } } </Document> <Document> using System; class Program2 { static int F(int x, System.Int16 y) { int i1 = 0; System.Int16 s1 = 0; int i2 = 0; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static System.Int32 F(System.Int32 x, System.Int16 y) { System.Int32 i1 = 0; System.Int16 s1 = 0; System.Int32 i2 = 0; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static Int32 F(Int32 x, System.Int16 y) { Int32 i1 = 0; System.Int16 s1 = 0; Int32 i2 = 0; return i1 + s1 + i2; } } </Document> <Document> using System; class Program2 { static Int32 F(Int32 x, System.Int16 y) { Int32 i1 = 0; System.Int16 s1 = 0; Int32 i2 = 0; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static System.Int32 F(System.Int32 x, System.Int16 y) { System.Int32 i1 = 0; System.Int16 s1 = 0; System.Int32 i2 = 0; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, options: FrameworkTypeEverywhere); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInSolution_DeclarationContext() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static int F(int x, System.Int16 y) { {|FixAllInSolution:int|} i1 = 0; System.Int16 s1 = 0; int i2 = 0; return i1 + s1 + i2; } } </Document> <Document> using System; class Program2 { static int F(int x, System.Int16 y) { int i1 = 0; System.Int16 s1 = 0; int i2 = 0; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static int F(int x, System.Int16 y) { int i1 = 0; System.Int16 s1 = 0; int i2 = 0; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class Program { static Int32 F(Int32 x, System.Int16 y) { Int32 i1 = 0; System.Int16 s1 = 0; Int32 i2 = 0; return i1 + s1 + i2; } } </Document> <Document> using System; class Program2 { static Int32 F(Int32 x, System.Int16 y) { Int32 i1 = 0; System.Int16 s1 = 0; Int32 i2 = 0; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class Program2 { static Int32 F(Int32 x, System.Int16 y) { Int32 i1 = 0; System.Int16 s1 = 0; Int32 i2 = 0; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, options: FrameworkTypeEverywhere); } [Fact] [Trait(Traits.Feature, Traits.Features.CodeActionsUseFrameworkType)] [Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)] public async Task TestFixAllInSolution_MemberAccessContext() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class ProgramA { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x; System.Int16 s1 = this.y; System.Int32 i2 = this.z; {|FixAllInSolution:int|}.Parse(i1 + s1 + i2); int.Parse(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> <Document> using System; class ProgramA2 { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x; System.Int16 s1 = this.y; System.Int32 i2 = this.z; int.Parse(i1 + s1 + i2); int.Parse(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class ProgramA3 { private int x = 0; private int y = 0; private int z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x; System.Int16 s1 = this.y; System.Int32 i2 = this.z; int.Parse(i1 + s1 + i2); int.Parse(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document> using System; class ProgramA { private Int32 x = 0; private Int32 y = 0; private Int32 z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x; System.Int16 s1 = this.y; System.Int32 i2 = this.z; Int32.Parse(i1 + s1 + i2); Int32.Parse(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> <Document> using System; class ProgramA2 { private Int32 x = 0; private Int32 y = 0; private Int32 z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x; System.Int16 s1 = this.y; System.Int32 i2 = this.z; Int32.Parse(i1 + s1 + i2); Int32.Parse(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> </Project> <Project Language=""C#"" AssemblyName=""Assembly2"" CommonReferences=""true""> <Document> using System; class ProgramA3 { private Int32 x = 0; private Int32 y = 0; private Int32 z = 0; private System.Int32 F(System.Int32 p1, System.Int16 p2) { System.Int32 i1 = this.x; System.Int16 s1 = this.y; System.Int32 i2 = this.z; Int32.Parse(i1 + s1 + i2); Int32.Parse(i1 + s1 + i2); System.Exception ex = null; return i1 + s1 + i2; } } </Document> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, options: FrameworkTypeEverywhere); } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/Core/Portable/Remote/PinnedSolutionInfo.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.Runtime.Serialization; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Information related to pinned solution /// </summary> [DataContract] internal sealed class PinnedSolutionInfo { /// <summary> /// Unique ID for this pinned solution /// /// This later used to find matching solution between VS and remote host /// </summary> [DataMember(Order = 0)] public readonly int ScopeId; /// <summary> /// This indicates whether this scope is for primary branch or not (not forked solution) /// /// Features like OOP will use this flag to see whether caching information related to this solution /// can benefit other requests or not /// </summary> [DataMember(Order = 1)] public readonly bool FromPrimaryBranch; /// <summary> /// This indicates a Solution.WorkspaceVersion of this solution. remote host engine uses this version /// to decide whether caching this solution will benefit other requests or not /// </summary> [DataMember(Order = 2)] public readonly int WorkspaceVersion; [DataMember(Order = 3)] public readonly Checksum SolutionChecksum; public PinnedSolutionInfo(int scopeId, bool fromPrimaryBranch, int workspaceVersion, Checksum solutionChecksum) { ScopeId = scopeId; FromPrimaryBranch = fromPrimaryBranch; WorkspaceVersion = workspaceVersion; SolutionChecksum = solutionChecksum; } } }
// Licensed to the .NET Foundation under one or more 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.Runtime.Serialization; namespace Microsoft.CodeAnalysis.Remote { /// <summary> /// Information related to pinned solution /// </summary> [DataContract] internal sealed class PinnedSolutionInfo { /// <summary> /// Unique ID for this pinned solution /// /// This later used to find matching solution between VS and remote host /// </summary> [DataMember(Order = 0)] public readonly int ScopeId; /// <summary> /// This indicates whether this scope is for primary branch or not (not forked solution) /// /// Features like OOP will use this flag to see whether caching information related to this solution /// can benefit other requests or not /// </summary> [DataMember(Order = 1)] public readonly bool FromPrimaryBranch; /// <summary> /// This indicates a Solution.WorkspaceVersion of this solution. remote host engine uses this version /// to decide whether caching this solution will benefit other requests or not /// </summary> [DataMember(Order = 2)] public readonly int WorkspaceVersion; [DataMember(Order = 3)] public readonly Checksum SolutionChecksum; public PinnedSolutionInfo(int scopeId, bool fromPrimaryBranch, int workspaceVersion, Checksum solutionChecksum) { ScopeId = scopeId; FromPrimaryBranch = fromPrimaryBranch; WorkspaceVersion = workspaceVersion; SolutionChecksum = solutionChecksum; } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Features/CSharp/Portable/SignatureHelp/InitializerExpressionSignatureHelpProvider.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; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp { [ExportSignatureHelpProvider(nameof(InitializerExpressionSignatureHelpProvider), LanguageNames.CSharp), Shared] internal partial class InitializerExpressionSignatureHelpProvider : AbstractOrdinaryMethodSignatureHelpProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public InitializerExpressionSignatureHelpProvider() { } public override bool IsTriggerCharacter(char ch) => ch == '{' || ch == ','; public override bool IsRetriggerCharacter(char ch) => ch == '}'; private bool TryGetInitializerExpression(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, out InitializerExpressionSyntax expression) => CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, IsTriggerToken, IsInitializerExpressionToken, cancellationToken, out expression) && expression != null; private bool IsTriggerToken(SyntaxToken token) => !token.IsKind(SyntaxKind.None) && token.ValueText.Length == 1 && IsTriggerCharacter(token.ValueText[0]) && token.Parent is InitializerExpressionSyntax; private static bool IsInitializerExpressionToken(InitializerExpressionSyntax expression, SyntaxToken token) => expression.Span.Contains(token.SpanStart) && token != expression.CloseBraceToken; protected override async Task<SignatureHelpItems?> GetItemsWorkerAsync(Document document, int position, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); if (!TryGetInitializerExpression(root, position, document.GetRequiredLanguageService<ISyntaxFactsService>(), triggerInfo.TriggerReason, cancellationToken, out var initializerExpression)) { return null; } var addMethods = await CommonSignatureHelpUtilities.GetCollectionInitializerAddMethodsAsync( document, initializerExpression, cancellationToken).ConfigureAwait(false); if (addMethods.IsDefaultOrEmpty) { return null; } var textSpan = SignatureHelpUtilities.GetSignatureHelpSpan(initializerExpression); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); return CreateCollectionInitializerSignatureHelpItems(addMethods.Select(s => ConvertMethodGroupMethod(document, s, initializerExpression.OpenBraceToken.SpanStart, semanticModel)).ToList(), textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken)); } public override SignatureHelpState? GetCurrentArgumentState(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, TextSpan currentSpan, CancellationToken cancellationToken) { if (TryGetInitializerExpression( root, position, syntaxFacts, SignatureHelpTriggerReason.InvokeSignatureHelpCommand, cancellationToken, out var expression) && currentSpan.Start == SignatureHelpUtilities.GetSignatureHelpSpan(expression).Start) { return SignatureHelpUtilities.GetSignatureHelpState(expression, position); } return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp { [ExportSignatureHelpProvider(nameof(InitializerExpressionSignatureHelpProvider), LanguageNames.CSharp), Shared] internal partial class InitializerExpressionSignatureHelpProvider : AbstractOrdinaryMethodSignatureHelpProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public InitializerExpressionSignatureHelpProvider() { } public override bool IsTriggerCharacter(char ch) => ch == '{' || ch == ','; public override bool IsRetriggerCharacter(char ch) => ch == '}'; private bool TryGetInitializerExpression(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, out InitializerExpressionSyntax expression) => CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, IsTriggerToken, IsInitializerExpressionToken, cancellationToken, out expression) && expression != null; private bool IsTriggerToken(SyntaxToken token) => !token.IsKind(SyntaxKind.None) && token.ValueText.Length == 1 && IsTriggerCharacter(token.ValueText[0]) && token.Parent is InitializerExpressionSyntax; private static bool IsInitializerExpressionToken(InitializerExpressionSyntax expression, SyntaxToken token) => expression.Span.Contains(token.SpanStart) && token != expression.CloseBraceToken; protected override async Task<SignatureHelpItems?> GetItemsWorkerAsync(Document document, int position, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); if (!TryGetInitializerExpression(root, position, document.GetRequiredLanguageService<ISyntaxFactsService>(), triggerInfo.TriggerReason, cancellationToken, out var initializerExpression)) { return null; } var addMethods = await CommonSignatureHelpUtilities.GetCollectionInitializerAddMethodsAsync( document, initializerExpression, cancellationToken).ConfigureAwait(false); if (addMethods.IsDefaultOrEmpty) { return null; } var textSpan = SignatureHelpUtilities.GetSignatureHelpSpan(initializerExpression); var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>(); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); return CreateCollectionInitializerSignatureHelpItems(addMethods.Select(s => ConvertMethodGroupMethod(document, s, initializerExpression.OpenBraceToken.SpanStart, semanticModel)).ToList(), textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken)); } public override SignatureHelpState? GetCurrentArgumentState(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, TextSpan currentSpan, CancellationToken cancellationToken) { if (TryGetInitializerExpression( root, position, syntaxFacts, SignatureHelpTriggerReason.InvokeSignatureHelpCommand, cancellationToken, out var expression) && currentSpan.Start == SignatureHelpUtilities.GetSignatureHelpSpan(expression).Start) { return SignatureHelpUtilities.GetSignatureHelpState(expression, position); } return null; } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/Test/Structure/BlockSpanTests.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.Structure; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Structure { public class BlockSpanTests { [Fact] public void TestProperties() { var span = TextSpan.FromBounds(0, 1); var hintSpan = TextSpan.FromBounds(2, 3); var bannerText = "Goo"; var autoCollapse = true; var outliningRegion = new BlockSpan( isCollapsible: true, textSpan: span, hintSpan: hintSpan, type: BlockTypes.Nonstructural, bannerText: bannerText, autoCollapse: autoCollapse); Assert.Equal(span, outliningRegion.TextSpan); Assert.Equal(hintSpan, outliningRegion.HintSpan); Assert.Equal(bannerText, outliningRegion.BannerText); Assert.Equal(autoCollapse, outliningRegion.AutoCollapse); } [Fact] public void TestToStringWithHintSpan() { var span = TextSpan.FromBounds(0, 1); var hintSpan = TextSpan.FromBounds(2, 3); var bannerText = "Goo"; var autoCollapse = true; var outliningRegion = new BlockSpan( isCollapsible: true, textSpan: span, hintSpan: hintSpan, type: BlockTypes.Nonstructural, bannerText: bannerText, autoCollapse: autoCollapse); Assert.Equal("{Span=[0..1), HintSpan=[2..3), BannerText=\"Goo\", AutoCollapse=True, IsDefaultCollapsed=False}", outliningRegion.ToString()); } [Fact] public void TestToStringWithoutHintSpan() { var span = TextSpan.FromBounds(0, 1); var bannerText = "Goo"; var autoCollapse = true; var outliningRegion = new BlockSpan( isCollapsible: true, textSpan: span, type: BlockTypes.Nonstructural, bannerText: bannerText, autoCollapse: autoCollapse); Assert.Equal("{Span=[0..1), BannerText=\"Goo\", AutoCollapse=True, IsDefaultCollapsed=False}", outliningRegion.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. #nullable disable using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Text; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.Structure { public class BlockSpanTests { [Fact] public void TestProperties() { var span = TextSpan.FromBounds(0, 1); var hintSpan = TextSpan.FromBounds(2, 3); var bannerText = "Goo"; var autoCollapse = true; var outliningRegion = new BlockSpan( isCollapsible: true, textSpan: span, hintSpan: hintSpan, type: BlockTypes.Nonstructural, bannerText: bannerText, autoCollapse: autoCollapse); Assert.Equal(span, outliningRegion.TextSpan); Assert.Equal(hintSpan, outliningRegion.HintSpan); Assert.Equal(bannerText, outliningRegion.BannerText); Assert.Equal(autoCollapse, outliningRegion.AutoCollapse); } [Fact] public void TestToStringWithHintSpan() { var span = TextSpan.FromBounds(0, 1); var hintSpan = TextSpan.FromBounds(2, 3); var bannerText = "Goo"; var autoCollapse = true; var outliningRegion = new BlockSpan( isCollapsible: true, textSpan: span, hintSpan: hintSpan, type: BlockTypes.Nonstructural, bannerText: bannerText, autoCollapse: autoCollapse); Assert.Equal("{Span=[0..1), HintSpan=[2..3), BannerText=\"Goo\", AutoCollapse=True, IsDefaultCollapsed=False}", outliningRegion.ToString()); } [Fact] public void TestToStringWithoutHintSpan() { var span = TextSpan.FromBounds(0, 1); var bannerText = "Goo"; var autoCollapse = true; var outliningRegion = new BlockSpan( isCollapsible: true, textSpan: span, type: BlockTypes.Nonstructural, bannerText: bannerText, autoCollapse: autoCollapse); Assert.Equal("{Span=[0..1), BannerText=\"Goo\", AutoCollapse=True, IsDefaultCollapsed=False}", outliningRegion.ToString()); } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Dependencies/Collections/Internal/IListCalls.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; namespace Microsoft.CodeAnalysis.Collections.Internal { /// <summary> /// Provides static methods to invoke <see cref="IList"/> members on value types that explicitly implement the /// member. /// </summary> /// <remarks> /// Normally, invocation of explicit interface members requires boxing or copying the value type, which is /// especially problematic for operations that mutate the value. Invocation through these helpers behaves like a /// normal call to an implicitly implemented member. /// </remarks> internal static class IListCalls { public static object? GetItem<TList>(ref TList list, int index) where TList : IList => list[index]; public static void SetItem<TList>(ref TList list, int index, object? value) where TList : IList => list[index] = value; public static bool IsFixedSize<TList>(ref TList list) where TList : IList => list.IsFixedSize; public static bool IsReadOnly<TList>(ref TList list) where TList : IList => list.IsReadOnly; public static int Add<TList>(ref TList list, object? value) where TList : IList { return list.Add(value); } public static bool Contains<TList>(ref TList list, object? value) where TList : IList { return list.Contains(value); } public static int IndexOf<TList>(ref TList list, object? value) where TList : IList { return list.IndexOf(value); } public static void Insert<TList>(ref TList list, int index, object? value) where TList : IList { list.Insert(index, value); } public static void Remove<TList>(ref TList list, object? value) where TList : IList { list.Remove(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.Collections; namespace Microsoft.CodeAnalysis.Collections.Internal { /// <summary> /// Provides static methods to invoke <see cref="IList"/> members on value types that explicitly implement the /// member. /// </summary> /// <remarks> /// Normally, invocation of explicit interface members requires boxing or copying the value type, which is /// especially problematic for operations that mutate the value. Invocation through these helpers behaves like a /// normal call to an implicitly implemented member. /// </remarks> internal static class IListCalls { public static object? GetItem<TList>(ref TList list, int index) where TList : IList => list[index]; public static void SetItem<TList>(ref TList list, int index, object? value) where TList : IList => list[index] = value; public static bool IsFixedSize<TList>(ref TList list) where TList : IList => list.IsFixedSize; public static bool IsReadOnly<TList>(ref TList list) where TList : IList => list.IsReadOnly; public static int Add<TList>(ref TList list, object? value) where TList : IList { return list.Add(value); } public static bool Contains<TList>(ref TList list, object? value) where TList : IList { return list.Contains(value); } public static int IndexOf<TList>(ref TList list, object? value) where TList : IList { return list.IndexOf(value); } public static void Insert<TList>(ref TList list, int index, object? value) where TList : IList { list.Insert(index, value); } public static void Remove<TList>(ref TList list, object? value) where TList : IList { list.Remove(value); } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/CastExpressionSyntaxExtensions.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.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static partial class CastExpressionSyntaxExtensions { public static ExpressionSyntax Uncast(this CastExpressionSyntax node) { var leadingTrivia = node.OpenParenToken.LeadingTrivia .Concat(node.OpenParenToken.TrailingTrivia) .Concat(node.Type.GetLeadingTrivia()) .Concat(node.Type.GetTrailingTrivia()) .Concat(node.CloseParenToken.LeadingTrivia) .Concat(node.CloseParenToken.TrailingTrivia) .Concat(node.Expression.GetLeadingTrivia()) .Where(t => !t.IsElastic()); var trailingTrivia = node.GetTrailingTrivia().Where(t => !t.IsElastic()); var resultNode = node.Expression .WithLeadingTrivia(leadingTrivia) .WithTrailingTrivia(trailingTrivia) .WithAdditionalAnnotations(Simplifier.Annotation); resultNode = SimplificationHelpers.CopyAnnotations(from: node, to: resultNode); return resultNode; } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static partial class CastExpressionSyntaxExtensions { public static ExpressionSyntax Uncast(this CastExpressionSyntax node) { var leadingTrivia = node.OpenParenToken.LeadingTrivia .Concat(node.OpenParenToken.TrailingTrivia) .Concat(node.Type.GetLeadingTrivia()) .Concat(node.Type.GetTrailingTrivia()) .Concat(node.CloseParenToken.LeadingTrivia) .Concat(node.CloseParenToken.TrailingTrivia) .Concat(node.Expression.GetLeadingTrivia()) .Where(t => !t.IsElastic()); var trailingTrivia = node.GetTrailingTrivia().Where(t => !t.IsElastic()); var resultNode = node.Expression .WithLeadingTrivia(leadingTrivia) .WithTrailingTrivia(trailingTrivia) .WithAdditionalAnnotations(Simplifier.Annotation); resultNode = SimplificationHelpers.CopyAnnotations(from: node, to: resultNode); return resultNode; } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/Core/Shared/Tagging/EventSources/TaggerEventSources.ReadOnlyRegionsChangedEventSource.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.Editor.Tagging; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging { internal partial class TaggerEventSources { private class ReadOnlyRegionsChangedEventSource : AbstractTaggerEventSource { private readonly ITextBuffer _subjectBuffer; public ReadOnlyRegionsChangedEventSource(ITextBuffer subjectBuffer) { Contract.ThrowIfNull(subjectBuffer); _subjectBuffer = subjectBuffer; } public override void Connect() => _subjectBuffer.ReadOnlyRegionsChanged += OnReadOnlyRegionsChanged; public override void Disconnect() => _subjectBuffer.ReadOnlyRegionsChanged -= OnReadOnlyRegionsChanged; private void OnReadOnlyRegionsChanged(object? sender, SnapshotSpanEventArgs e) => this.RaiseChanged(); } } }
// Licensed to the .NET Foundation under one or more 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.Editor.Tagging; using Microsoft.VisualStudio.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging { internal partial class TaggerEventSources { private class ReadOnlyRegionsChangedEventSource : AbstractTaggerEventSource { private readonly ITextBuffer _subjectBuffer; public ReadOnlyRegionsChangedEventSource(ITextBuffer subjectBuffer) { Contract.ThrowIfNull(subjectBuffer); _subjectBuffer = subjectBuffer; } public override void Connect() => _subjectBuffer.ReadOnlyRegionsChanged += OnReadOnlyRegionsChanged; public override void Disconnect() => _subjectBuffer.ReadOnlyRegionsChanged -= OnReadOnlyRegionsChanged; private void OnReadOnlyRegionsChanged(object? sender, SnapshotSpanEventArgs e) => this.RaiseChanged(); } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/VisualStudio/CSharp/Test/PersistentStorage/Mocks/AuthorizationServiceMock.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. // Copy of https://devdiv.visualstudio.com/DevDiv/_git/VS.CloudCache?path=%2Ftest%2FMicrosoft.VisualStudio.Cache.Tests%2FMocks&_a=contents&version=GBmain // Try to keep in sync and avoid unnecessary changes here. using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.ServiceHub.Framework.Services; #pragma warning disable CS0067 // events that are never used namespace Microsoft.CodeAnalysis.UnitTests.WorkspaceServices.Mocks { internal class AuthorizationServiceMock : IAuthorizationService { public event EventHandler? CredentialsChanged; public event EventHandler? AuthorizationChanged; internal bool Allow { get; set; } = true; public ValueTask<bool> CheckAuthorizationAsync(ProtectedOperation operation, CancellationToken cancellationToken = default) { return new ValueTask<bool>(this.Allow); } public ValueTask<IReadOnlyDictionary<string, string>> GetCredentialsAsync(CancellationToken cancellationToken = default) { 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. // Copy of https://devdiv.visualstudio.com/DevDiv/_git/VS.CloudCache?path=%2Ftest%2FMicrosoft.VisualStudio.Cache.Tests%2FMocks&_a=contents&version=GBmain // Try to keep in sync and avoid unnecessary changes here. using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.ServiceHub.Framework.Services; #pragma warning disable CS0067 // events that are never used namespace Microsoft.CodeAnalysis.UnitTests.WorkspaceServices.Mocks { internal class AuthorizationServiceMock : IAuthorizationService { public event EventHandler? CredentialsChanged; public event EventHandler? AuthorizationChanged; internal bool Allow { get; set; } = true; public ValueTask<bool> CheckAuthorizationAsync(ProtectedOperation operation, CancellationToken cancellationToken = default) { return new ValueTask<bool>(this.Allow); } public ValueTask<IReadOnlyDictionary<string, string>> GetCredentialsAsync(CancellationToken cancellationToken = default) { throw new NotImplementedException(); } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Features/Core/Portable/QuickInfo/CommonSemanticQuickInfoProvider.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.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.QuickInfo { internal abstract partial class CommonSemanticQuickInfoProvider : CommonQuickInfoProvider { protected override async Task<QuickInfoItem?> BuildQuickInfoAsync( QuickInfoContext context, SyntaxToken token) { var (tokenInformation, supportedPlatforms) = await ComputeQuickInfoDataAsync(context, token).ConfigureAwait(false); if (tokenInformation.Symbols.IsDefaultOrEmpty) return null; var cancellationToken = context.CancellationToken; var semanticModel = await context.Document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); return await CreateContentAsync( context.Document.Project.Solution.Workspace, semanticModel, token, tokenInformation, supportedPlatforms, cancellationToken).ConfigureAwait(false); } protected override async Task<QuickInfoItem?> BuildQuickInfoAsync( CommonQuickInfoContext context, SyntaxToken token) { var tokenInformation = BindToken(context.Workspace, context.SemanticModel, token, context.CancellationToken); if (tokenInformation.Symbols.IsDefaultOrEmpty) return null; return await CreateContentAsync( context.Workspace, context.SemanticModel, token, tokenInformation, supportedPlatforms: null, context.CancellationToken).ConfigureAwait(false); } private async Task<(TokenInformation tokenInformation, SupportedPlatformData? supportedPlatforms)> ComputeQuickInfoDataAsync( QuickInfoContext context, SyntaxToken token) { var cancellationToken = context.CancellationToken; var document = context.Document; var linkedDocumentIds = document.GetLinkedDocumentIds(); if (linkedDocumentIds.Any()) return await ComputeFromLinkedDocumentsAsync(context, token, linkedDocumentIds).ConfigureAwait(false); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var tokenInformation = BindToken( document.Project.Solution.Workspace, semanticModel, token, cancellationToken); return (tokenInformation, supportedPlatforms: null); } private async Task<(TokenInformation, SupportedPlatformData supportedPlatforms)> ComputeFromLinkedDocumentsAsync( QuickInfoContext context, SyntaxToken token, ImmutableArray<DocumentId> linkedDocumentIds) { // Linked files/shared projects: imagine the following when GOO is false // #if GOO // int x = 3; // #endif // var y = x$$; // // 'x' will bind as an error type, so we'll show incorrect information. // Instead, we need to find the head in which we get the best binding, // which in this case is the one with no errors. var cancellationToken = context.CancellationToken; var document = context.Document; var solution = document.Project.Solution; var workspace = solution.Workspace; var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var mainTokenInformation = BindToken(workspace, semanticModel, token, cancellationToken); var candidateProjects = new List<ProjectId> { document.Project.Id }; var invalidProjects = new List<ProjectId>(); var candidateResults = new List<(DocumentId docId, TokenInformation tokenInformation)> { (document.Id, mainTokenInformation) }; foreach (var linkedDocumentId in linkedDocumentIds) { var linkedDocument = solution.GetRequiredDocument(linkedDocumentId); var linkedModel = await linkedDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var linkedToken = FindTokenInLinkedDocument(token, linkedModel, cancellationToken); if (linkedToken != default) { // Not in an inactive region, so this file is a candidate. candidateProjects.Add(linkedDocumentId.ProjectId); var linkedSymbols = BindToken(workspace, linkedModel, linkedToken, cancellationToken); candidateResults.Add((linkedDocumentId, linkedSymbols)); } } // Take the first result with no errors. // If every file binds with errors, take the first candidate, which is from the current file. var bestBinding = candidateResults.FirstOrNull(c => HasNoErrors(c.tokenInformation.Symbols)) ?? candidateResults.First(); if (bestBinding.tokenInformation.Symbols.IsDefaultOrEmpty) return default; // We calculate the set of supported projects candidateResults.Remove(bestBinding); foreach (var (docId, tokenInformation) in candidateResults) { // Does the candidate have anything remotely equivalent? if (!tokenInformation.Symbols.Intersect(bestBinding.tokenInformation.Symbols, LinkedFilesSymbolEquivalenceComparer.Instance).Any()) invalidProjects.Add(docId.ProjectId); } var supportedPlatforms = new SupportedPlatformData(invalidProjects, candidateProjects, workspace); return (bestBinding.tokenInformation, supportedPlatforms); } private static bool HasNoErrors(ImmutableArray<ISymbol> symbols) => symbols.Length > 0 && !ErrorVisitor.ContainsError(symbols.FirstOrDefault()); private static SyntaxToken FindTokenInLinkedDocument( SyntaxToken token, SemanticModel linkedModel, CancellationToken cancellationToken) { var root = linkedModel.SyntaxTree.GetRoot(cancellationToken); if (root == null) return default; // Don't search trivia because we want to ignore inactive regions var linkedToken = root.FindToken(token.SpanStart); // The new and old tokens should have the same span? return token.Span == linkedToken.Span ? linkedToken : default; } protected static Task<QuickInfoItem> CreateContentAsync( Workspace workspace, SemanticModel semanticModel, SyntaxToken token, TokenInformation tokenInformation, SupportedPlatformData? supportedPlatforms, CancellationToken cancellationToken) { var syntaxFactsService = workspace.Services.GetLanguageServices(semanticModel.Language).GetRequiredService<ISyntaxFactsService>(); var symbols = tokenInformation.Symbols; // if generating quick info for an attribute, prefer bind to the class instead of the constructor if (syntaxFactsService.IsAttributeName(token.Parent!)) { symbols = symbols.OrderBy((s1, s2) => s1.Kind == s2.Kind ? 0 : s1.Kind == SymbolKind.NamedType ? -1 : s2.Kind == SymbolKind.NamedType ? 1 : 0).ToImmutableArray(); } return QuickInfoUtilities.CreateQuickInfoItemAsync( workspace, semanticModel, token.Span, symbols, supportedPlatforms, tokenInformation.ShowAwaitReturn, tokenInformation.NullableFlowState, cancellationToken); } protected abstract bool GetBindableNodeForTokenIndicatingLambda(SyntaxToken token, [NotNullWhen(returnValue: true)] out SyntaxNode? found); protected abstract bool GetBindableNodeForTokenIndicatingPossibleIndexerAccess(SyntaxToken token, [NotNullWhen(returnValue: true)] out SyntaxNode? found); protected virtual NullableFlowState GetNullabilityAnalysis(Workspace workspace, SemanticModel semanticModel, ISymbol symbol, SyntaxNode node, CancellationToken cancellationToken) => NullableFlowState.None; private TokenInformation BindToken( Workspace workspace, SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken) { var hostServices = workspace.Services; var languageServices = hostServices.GetLanguageServices(semanticModel.Language); var syntaxFacts = languageServices.GetRequiredService<ISyntaxFactsService>(); var enclosingType = semanticModel.GetEnclosingNamedType(token.SpanStart, cancellationToken); var symbols = GetSymbolsFromToken(token, workspace, semanticModel, cancellationToken); var bindableParent = syntaxFacts.TryGetBindableParent(token); var overloads = bindableParent != null ? semanticModel.GetMemberGroup(bindableParent, cancellationToken) : ImmutableArray<ISymbol>.Empty; symbols = symbols.Where(IsOk) .Where(s => IsAccessible(s, enclosingType)) .Concat(overloads) .Distinct(SymbolEquivalenceComparer.Instance) .ToImmutableArray(); if (symbols.Any()) { var firstSymbol = symbols.First(); var isAwait = syntaxFacts.IsAwaitKeyword(token); var nullableFlowState = NullableFlowState.None; if (bindableParent != null) { nullableFlowState = GetNullabilityAnalysis(workspace, semanticModel, firstSymbol, bindableParent, cancellationToken); } return new TokenInformation(symbols, isAwait, nullableFlowState); } // Couldn't bind the token to specific symbols. If it's an operator, see if we can at // least bind it to a type. if (syntaxFacts.IsOperator(token)) { var typeInfo = semanticModel.GetTypeInfo(token.Parent!, cancellationToken); if (IsOk(typeInfo.Type)) { return new TokenInformation(ImmutableArray.Create<ISymbol>(typeInfo.Type)); } } return new TokenInformation(ImmutableArray<ISymbol>.Empty); } private ImmutableArray<ISymbol> GetSymbolsFromToken(SyntaxToken token, Workspace workspace, SemanticModel semanticModel, CancellationToken cancellationToken) { if (GetBindableNodeForTokenIndicatingLambda(token, out var lambdaSyntax)) { var symbol = semanticModel.GetSymbolInfo(lambdaSyntax, cancellationToken).Symbol; return symbol != null ? ImmutableArray.Create(symbol) : ImmutableArray<ISymbol>.Empty; } if (GetBindableNodeForTokenIndicatingPossibleIndexerAccess(token, out var elementAccessExpression)) { var symbol = semanticModel.GetSymbolInfo(elementAccessExpression, cancellationToken).Symbol; if (symbol?.IsIndexer() == true) { return ImmutableArray.Create(symbol); } } return semanticModel.GetSemanticInfo(token, workspace, cancellationToken) .GetSymbols(includeType: true); } private static bool IsOk([NotNullWhen(returnValue: true)] ISymbol? symbol) { if (symbol == null) return false; if (symbol.IsErrorType()) return false; if (symbol is ITypeParameterSymbol { TypeParameterKind: TypeParameterKind.Cref }) return false; return true; } private static bool IsAccessible(ISymbol symbol, INamedTypeSymbol? within) => within == null || symbol.IsAccessibleWithin(within); } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.QuickInfo { internal abstract partial class CommonSemanticQuickInfoProvider : CommonQuickInfoProvider { protected override async Task<QuickInfoItem?> BuildQuickInfoAsync( QuickInfoContext context, SyntaxToken token) { var (tokenInformation, supportedPlatforms) = await ComputeQuickInfoDataAsync(context, token).ConfigureAwait(false); if (tokenInformation.Symbols.IsDefaultOrEmpty) return null; var cancellationToken = context.CancellationToken; var semanticModel = await context.Document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); return await CreateContentAsync( context.Document.Project.Solution.Workspace, semanticModel, token, tokenInformation, supportedPlatforms, cancellationToken).ConfigureAwait(false); } protected override async Task<QuickInfoItem?> BuildQuickInfoAsync( CommonQuickInfoContext context, SyntaxToken token) { var tokenInformation = BindToken(context.Workspace, context.SemanticModel, token, context.CancellationToken); if (tokenInformation.Symbols.IsDefaultOrEmpty) return null; return await CreateContentAsync( context.Workspace, context.SemanticModel, token, tokenInformation, supportedPlatforms: null, context.CancellationToken).ConfigureAwait(false); } private async Task<(TokenInformation tokenInformation, SupportedPlatformData? supportedPlatforms)> ComputeQuickInfoDataAsync( QuickInfoContext context, SyntaxToken token) { var cancellationToken = context.CancellationToken; var document = context.Document; var linkedDocumentIds = document.GetLinkedDocumentIds(); if (linkedDocumentIds.Any()) return await ComputeFromLinkedDocumentsAsync(context, token, linkedDocumentIds).ConfigureAwait(false); var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var tokenInformation = BindToken( document.Project.Solution.Workspace, semanticModel, token, cancellationToken); return (tokenInformation, supportedPlatforms: null); } private async Task<(TokenInformation, SupportedPlatformData supportedPlatforms)> ComputeFromLinkedDocumentsAsync( QuickInfoContext context, SyntaxToken token, ImmutableArray<DocumentId> linkedDocumentIds) { // Linked files/shared projects: imagine the following when GOO is false // #if GOO // int x = 3; // #endif // var y = x$$; // // 'x' will bind as an error type, so we'll show incorrect information. // Instead, we need to find the head in which we get the best binding, // which in this case is the one with no errors. var cancellationToken = context.CancellationToken; var document = context.Document; var solution = document.Project.Solution; var workspace = solution.Workspace; var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var mainTokenInformation = BindToken(workspace, semanticModel, token, cancellationToken); var candidateProjects = new List<ProjectId> { document.Project.Id }; var invalidProjects = new List<ProjectId>(); var candidateResults = new List<(DocumentId docId, TokenInformation tokenInformation)> { (document.Id, mainTokenInformation) }; foreach (var linkedDocumentId in linkedDocumentIds) { var linkedDocument = solution.GetRequiredDocument(linkedDocumentId); var linkedModel = await linkedDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var linkedToken = FindTokenInLinkedDocument(token, linkedModel, cancellationToken); if (linkedToken != default) { // Not in an inactive region, so this file is a candidate. candidateProjects.Add(linkedDocumentId.ProjectId); var linkedSymbols = BindToken(workspace, linkedModel, linkedToken, cancellationToken); candidateResults.Add((linkedDocumentId, linkedSymbols)); } } // Take the first result with no errors. // If every file binds with errors, take the first candidate, which is from the current file. var bestBinding = candidateResults.FirstOrNull(c => HasNoErrors(c.tokenInformation.Symbols)) ?? candidateResults.First(); if (bestBinding.tokenInformation.Symbols.IsDefaultOrEmpty) return default; // We calculate the set of supported projects candidateResults.Remove(bestBinding); foreach (var (docId, tokenInformation) in candidateResults) { // Does the candidate have anything remotely equivalent? if (!tokenInformation.Symbols.Intersect(bestBinding.tokenInformation.Symbols, LinkedFilesSymbolEquivalenceComparer.Instance).Any()) invalidProjects.Add(docId.ProjectId); } var supportedPlatforms = new SupportedPlatformData(invalidProjects, candidateProjects, workspace); return (bestBinding.tokenInformation, supportedPlatforms); } private static bool HasNoErrors(ImmutableArray<ISymbol> symbols) => symbols.Length > 0 && !ErrorVisitor.ContainsError(symbols.FirstOrDefault()); private static SyntaxToken FindTokenInLinkedDocument( SyntaxToken token, SemanticModel linkedModel, CancellationToken cancellationToken) { var root = linkedModel.SyntaxTree.GetRoot(cancellationToken); if (root == null) return default; // Don't search trivia because we want to ignore inactive regions var linkedToken = root.FindToken(token.SpanStart); // The new and old tokens should have the same span? return token.Span == linkedToken.Span ? linkedToken : default; } protected static Task<QuickInfoItem> CreateContentAsync( Workspace workspace, SemanticModel semanticModel, SyntaxToken token, TokenInformation tokenInformation, SupportedPlatformData? supportedPlatforms, CancellationToken cancellationToken) { var syntaxFactsService = workspace.Services.GetLanguageServices(semanticModel.Language).GetRequiredService<ISyntaxFactsService>(); var symbols = tokenInformation.Symbols; // if generating quick info for an attribute, prefer bind to the class instead of the constructor if (syntaxFactsService.IsAttributeName(token.Parent!)) { symbols = symbols.OrderBy((s1, s2) => s1.Kind == s2.Kind ? 0 : s1.Kind == SymbolKind.NamedType ? -1 : s2.Kind == SymbolKind.NamedType ? 1 : 0).ToImmutableArray(); } return QuickInfoUtilities.CreateQuickInfoItemAsync( workspace, semanticModel, token.Span, symbols, supportedPlatforms, tokenInformation.ShowAwaitReturn, tokenInformation.NullableFlowState, cancellationToken); } protected abstract bool GetBindableNodeForTokenIndicatingLambda(SyntaxToken token, [NotNullWhen(returnValue: true)] out SyntaxNode? found); protected abstract bool GetBindableNodeForTokenIndicatingPossibleIndexerAccess(SyntaxToken token, [NotNullWhen(returnValue: true)] out SyntaxNode? found); protected virtual NullableFlowState GetNullabilityAnalysis(Workspace workspace, SemanticModel semanticModel, ISymbol symbol, SyntaxNode node, CancellationToken cancellationToken) => NullableFlowState.None; private TokenInformation BindToken( Workspace workspace, SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken) { var hostServices = workspace.Services; var languageServices = hostServices.GetLanguageServices(semanticModel.Language); var syntaxFacts = languageServices.GetRequiredService<ISyntaxFactsService>(); var enclosingType = semanticModel.GetEnclosingNamedType(token.SpanStart, cancellationToken); var symbols = GetSymbolsFromToken(token, workspace, semanticModel, cancellationToken); var bindableParent = syntaxFacts.TryGetBindableParent(token); var overloads = bindableParent != null ? semanticModel.GetMemberGroup(bindableParent, cancellationToken) : ImmutableArray<ISymbol>.Empty; symbols = symbols.Where(IsOk) .Where(s => IsAccessible(s, enclosingType)) .Concat(overloads) .Distinct(SymbolEquivalenceComparer.Instance) .ToImmutableArray(); if (symbols.Any()) { var firstSymbol = symbols.First(); var isAwait = syntaxFacts.IsAwaitKeyword(token); var nullableFlowState = NullableFlowState.None; if (bindableParent != null) { nullableFlowState = GetNullabilityAnalysis(workspace, semanticModel, firstSymbol, bindableParent, cancellationToken); } return new TokenInformation(symbols, isAwait, nullableFlowState); } // Couldn't bind the token to specific symbols. If it's an operator, see if we can at // least bind it to a type. if (syntaxFacts.IsOperator(token)) { var typeInfo = semanticModel.GetTypeInfo(token.Parent!, cancellationToken); if (IsOk(typeInfo.Type)) { return new TokenInformation(ImmutableArray.Create<ISymbol>(typeInfo.Type)); } } return new TokenInformation(ImmutableArray<ISymbol>.Empty); } private ImmutableArray<ISymbol> GetSymbolsFromToken(SyntaxToken token, Workspace workspace, SemanticModel semanticModel, CancellationToken cancellationToken) { if (GetBindableNodeForTokenIndicatingLambda(token, out var lambdaSyntax)) { var symbol = semanticModel.GetSymbolInfo(lambdaSyntax, cancellationToken).Symbol; return symbol != null ? ImmutableArray.Create(symbol) : ImmutableArray<ISymbol>.Empty; } if (GetBindableNodeForTokenIndicatingPossibleIndexerAccess(token, out var elementAccessExpression)) { var symbol = semanticModel.GetSymbolInfo(elementAccessExpression, cancellationToken).Symbol; if (symbol?.IsIndexer() == true) { return ImmutableArray.Create(symbol); } } return semanticModel.GetSemanticInfo(token, workspace, cancellationToken) .GetSymbols(includeType: true); } private static bool IsOk([NotNullWhen(returnValue: true)] ISymbol? symbol) { if (symbol == null) return false; if (symbol.IsErrorType()) return false; if (symbol is ITypeParameterSymbol { TypeParameterKind: TypeParameterKind.Cref }) return false; return true; } private static bool IsAccessible(ISymbol symbol, INamedTypeSymbol? within) => within == null || symbol.IsAccessibleWithin(within); } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Tools/ExternalAccess/Razor/RazorDocumentExcerptServiceWrapper.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; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.Razor { internal sealed class RazorDocumentExcerptServiceWrapper : IDocumentExcerptService { private readonly IRazorDocumentExcerptService _razorDocumentExcerptService; public RazorDocumentExcerptServiceWrapper(IRazorDocumentExcerptService razorDocumentExcerptService) { _razorDocumentExcerptService = razorDocumentExcerptService ?? throw new ArgumentNullException(nameof(razorDocumentExcerptService)); } public async Task<ExcerptResult?> TryExcerptAsync(Document document, TextSpan span, ExcerptMode mode, CancellationToken cancellationToken) { var razorMode = mode switch { ExcerptMode.SingleLine => RazorExcerptMode.SingleLine, ExcerptMode.Tooltip => RazorExcerptMode.Tooltip, _ => throw new InvalidEnumArgumentException($"Unsupported enum type {mode}."), }; var nullableRazorExcerpt = await _razorDocumentExcerptService.TryExcerptAsync(document, span, razorMode, cancellationToken).ConfigureAwait(false); if (nullableRazorExcerpt == null) { return null; } var razorExcerpt = nullableRazorExcerpt.Value; var roslynExcerpt = new ExcerptResult(razorExcerpt.Content, razorExcerpt.MappedSpan, razorExcerpt.ClassifiedSpans, razorExcerpt.Document, razorExcerpt.Span); return roslynExcerpt; } } }
// Licensed to the .NET Foundation under one or more 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; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.Razor { internal sealed class RazorDocumentExcerptServiceWrapper : IDocumentExcerptService { private readonly IRazorDocumentExcerptService _razorDocumentExcerptService; public RazorDocumentExcerptServiceWrapper(IRazorDocumentExcerptService razorDocumentExcerptService) { _razorDocumentExcerptService = razorDocumentExcerptService ?? throw new ArgumentNullException(nameof(razorDocumentExcerptService)); } public async Task<ExcerptResult?> TryExcerptAsync(Document document, TextSpan span, ExcerptMode mode, CancellationToken cancellationToken) { var razorMode = mode switch { ExcerptMode.SingleLine => RazorExcerptMode.SingleLine, ExcerptMode.Tooltip => RazorExcerptMode.Tooltip, _ => throw new InvalidEnumArgumentException($"Unsupported enum type {mode}."), }; var nullableRazorExcerpt = await _razorDocumentExcerptService.TryExcerptAsync(document, span, razorMode, cancellationToken).ConfigureAwait(false); if (nullableRazorExcerpt == null) { return null; } var razorExcerpt = nullableRazorExcerpt.Value; var roslynExcerpt = new ExcerptResult(razorExcerpt.Content, razorExcerpt.MappedSpan, razorExcerpt.ClassifiedSpans, razorExcerpt.Document, razorExcerpt.Span); return roslynExcerpt; } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Features/Core/Portable/Completion/CompletionServiceWithProviders+ProjectCompletionProvider.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 Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.Completion { public abstract partial class CompletionServiceWithProviders { private class ProjectCompletionProvider : AbstractProjectExtensionProvider<CompletionProvider, ExportCompletionProviderAttribute> { public ProjectCompletionProvider(AnalyzerReference reference) : base(reference) { } protected override bool SupportsLanguage(ExportCompletionProviderAttribute exportAttribute, string language) { return exportAttribute.Language == null || exportAttribute.Language.Length == 0 || exportAttribute.Language.Contains(language); } protected override bool TryGetExtensionsFromReference(AnalyzerReference reference, out ImmutableArray<CompletionProvider> extensions) { // check whether the analyzer reference knows how to return completion providers directly. if (reference is ICompletionProviderFactory completionProviderFactory) { extensions = completionProviderFactory.GetCompletionProviders(); return true; } extensions = 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. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.Completion { public abstract partial class CompletionServiceWithProviders { private class ProjectCompletionProvider : AbstractProjectExtensionProvider<CompletionProvider, ExportCompletionProviderAttribute> { public ProjectCompletionProvider(AnalyzerReference reference) : base(reference) { } protected override bool SupportsLanguage(ExportCompletionProviderAttribute exportAttribute, string language) { return exportAttribute.Language == null || exportAttribute.Language.Length == 0 || exportAttribute.Language.Contains(language); } protected override bool TryGetExtensionsFromReference(AnalyzerReference reference, out ImmutableArray<CompletionProvider> extensions) { // check whether the analyzer reference knows how to return completion providers directly. if (reference is ICompletionProviderFactory completionProviderFactory) { extensions = completionProviderFactory.GetCompletionProviders(); return true; } extensions = default; return false; } } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/Core/Portable/ExternalAccess/UnitTesting/Api/UnitTestingSolutionExtensions.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; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { internal static class UnitTestingSolutionExtensions { public static int GetWorkspaceVersion(this Solution solution) => solution.WorkspaceVersion; public static async Task<UnitTestingChecksumWrapper> GetChecksumAsync(this Solution solution, CancellationToken cancellationToken) => new UnitTestingChecksumWrapper(await solution.State.GetChecksumAsync(cancellationToken).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. using System; using System.Threading; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.ExternalAccess.UnitTesting.Api { internal static class UnitTestingSolutionExtensions { public static int GetWorkspaceVersion(this Solution solution) => solution.WorkspaceVersion; public static async Task<UnitTestingChecksumWrapper> GetChecksumAsync(this Solution solution, CancellationToken cancellationToken) => new UnitTestingChecksumWrapper(await solution.State.GetChecksumAsync(cancellationToken).ConfigureAwait(false)); } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Features/Core/Portable/EditAndContinue/DocumentActiveStatementChanges.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; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { internal readonly struct DocumentActiveStatementChanges { public readonly ImmutableArray<UnmappedActiveStatement> OldStatements; public readonly ImmutableArray<ActiveStatement> NewStatements; public readonly ImmutableArray<ImmutableArray<SourceFileSpan>> NewExceptionRegions; public DocumentActiveStatementChanges( ImmutableArray<UnmappedActiveStatement> oldSpans, ImmutableArray<ActiveStatement> newStatements, ImmutableArray<ImmutableArray<SourceFileSpan>> newExceptionRegions) { Contract.ThrowIfFalse(oldSpans.Length == newStatements.Length); Contract.ThrowIfFalse(oldSpans.Length == newExceptionRegions.Length); #if DEBUG for (var i = 0; i < oldSpans.Length; i++) { // old and new exception region counts must match: Debug.Assert(oldSpans[i].ExceptionRegions.Spans.Length == newExceptionRegions[i].Length); } #endif OldStatements = oldSpans; NewStatements = newStatements; NewExceptionRegions = newExceptionRegions; } public void Deconstruct( out ImmutableArray<UnmappedActiveStatement> oldStatements, out ImmutableArray<ActiveStatement> newStatements, out ImmutableArray<ImmutableArray<SourceFileSpan>> newExceptionRegions) { oldStatements = OldStatements; newStatements = NewStatements; newExceptionRegions = NewExceptionRegions; } } }
// Licensed to the .NET Foundation under one or more 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; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.EditAndContinue { internal readonly struct DocumentActiveStatementChanges { public readonly ImmutableArray<UnmappedActiveStatement> OldStatements; public readonly ImmutableArray<ActiveStatement> NewStatements; public readonly ImmutableArray<ImmutableArray<SourceFileSpan>> NewExceptionRegions; public DocumentActiveStatementChanges( ImmutableArray<UnmappedActiveStatement> oldSpans, ImmutableArray<ActiveStatement> newStatements, ImmutableArray<ImmutableArray<SourceFileSpan>> newExceptionRegions) { Contract.ThrowIfFalse(oldSpans.Length == newStatements.Length); Contract.ThrowIfFalse(oldSpans.Length == newExceptionRegions.Length); #if DEBUG for (var i = 0; i < oldSpans.Length; i++) { // old and new exception region counts must match: Debug.Assert(oldSpans[i].ExceptionRegions.Spans.Length == newExceptionRegions[i].Length); } #endif OldStatements = oldSpans; NewStatements = newStatements; NewExceptionRegions = newExceptionRegions; } public void Deconstruct( out ImmutableArray<UnmappedActiveStatement> oldStatements, out ImmutableArray<ActiveStatement> newStatements, out ImmutableArray<ImmutableArray<SourceFileSpan>> newExceptionRegions) { oldStatements = OldStatements; newStatements = NewStatements; newExceptionRegions = NewExceptionRegions; } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Analyzers/CSharp/Analyzers/UseThrowExpression/CSharpUseThrowExpressionDiagnosticAnalyzer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.UseThrowExpression; namespace Microsoft.CodeAnalysis.CSharp.UseThrowExpression { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class CSharpUseThrowExpressionDiagnosticAnalyzer : AbstractUseThrowExpressionDiagnosticAnalyzer { public CSharpUseThrowExpressionDiagnosticAnalyzer() : base(CSharpCodeStyleOptions.PreferThrowExpression, LanguageNames.CSharp) { } protected override bool IsSupported(Compilation compilation) { return ((CSharpCompilation)compilation).LanguageVersion >= LanguageVersion.CSharp7; } protected override bool IsInExpressionTree(SemanticModel semanticModel, SyntaxNode node, INamedTypeSymbol expressionTypeOpt, CancellationToken cancellationToken) => node.IsInExpressionTree(semanticModel, expressionTypeOpt, cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.UseThrowExpression; namespace Microsoft.CodeAnalysis.CSharp.UseThrowExpression { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class CSharpUseThrowExpressionDiagnosticAnalyzer : AbstractUseThrowExpressionDiagnosticAnalyzer { public CSharpUseThrowExpressionDiagnosticAnalyzer() : base(CSharpCodeStyleOptions.PreferThrowExpression, LanguageNames.CSharp) { } protected override bool IsSupported(Compilation compilation) { return ((CSharpCompilation)compilation).LanguageVersion >= LanguageVersion.CSharp7; } protected override bool IsInExpressionTree(SemanticModel semanticModel, SyntaxNode node, INamedTypeSymbol expressionTypeOpt, CancellationToken cancellationToken) => node.IsInExpressionTree(semanticModel, expressionTypeOpt, cancellationToken); } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Rewriters/CapturedVariableRewriter.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.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Friend NotInheritable Class CapturedVariableRewriter Inherits BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator Friend Shared Function Rewrite( targetMethodMeParameter As ParameterSymbol, displayClassVariables As ImmutableDictionary(Of String, DisplayClassVariable), node As BoundNode, diagnostics As DiagnosticBag) As BoundNode Dim rewriter = New CapturedVariableRewriter(targetMethodMeParameter, displayClassVariables, diagnostics) Return rewriter.Visit(node) End Function Private ReadOnly _targetMethodMeParameter As ParameterSymbol Private ReadOnly _displayClassVariables As ImmutableDictionary(Of String, DisplayClassVariable) Private ReadOnly _diagnostics As DiagnosticBag Private Sub New( targetMethodMeParameter As ParameterSymbol, displayClassVariables As ImmutableDictionary(Of String, DisplayClassVariable), diagnostics As DiagnosticBag) _targetMethodMeParameter = targetMethodMeParameter _displayClassVariables = displayClassVariables _diagnostics = diagnostics End Sub Public Overrides Function Visit(node As BoundNode) As BoundNode ' Ignore nodes that will be rewritten to literals in the LocalRewriter. If TryCast(node, BoundExpression)?.ConstantValueOpt IsNot Nothing Then Return node End If Return MyBase.Visit(node) End Function Public Overrides Function VisitBlock(node As BoundBlock) As BoundNode Dim rewrittenLocals = node.Locals.WhereAsArray(AddressOf IncludeLocal) Dim rewrittenStatements = VisitList(node.Statements) Return node.Update(node.StatementListSyntax, rewrittenLocals, rewrittenStatements) End Function Private Function IncludeLocal(local As LocalSymbol) As Boolean Return Not local.IsStatic AndAlso (local.IsCompilerGenerated OrElse local.Name Is Nothing OrElse GetVariable(local.Name) Is Nothing) End Function Public Overrides Function VisitLocal(node As BoundLocal) As BoundNode Dim local = node.LocalSymbol If Not local.IsCompilerGenerated Then Dim syntax = node.Syntax Dim staticLocal = TryCast(local, EEStaticLocalSymbol) If staticLocal IsNot Nothing Then Dim receiver = If(_targetMethodMeParameter Is Nothing, Nothing, GetRewrittenMeParameter(syntax, New BoundMeReference(syntax, _targetMethodMeParameter.Type))) Dim result = staticLocal.ToBoundExpression(receiver, syntax, node.IsLValue) Debug.Assert(TypeSymbol.Equals(node.Type, result.Type, TypeCompareKind.ConsiderEverything)) Return result End If Dim variable = GetVariable(local.Name) If variable IsNot Nothing Then Dim result = variable.ToBoundExpression(syntax, node.IsLValue, node.SuppressVirtualCalls) Debug.Assert(TypeSymbol.Equals(node.Type, result.Type, TypeCompareKind.ConsiderEverything)) Return result End If End If Return node End Function Public Overrides Function VisitParameter(node As BoundParameter) As BoundNode Return RewriteParameter(node.Syntax, node.ParameterSymbol, node) End Function Public Overrides Function VisitMeReference(node As BoundMeReference) As BoundNode Return Me.GetRewrittenMeParameter(node.Syntax, node) End Function Public Overrides Function VisitMyBaseReference(node As BoundMyBaseReference) As BoundNode ' Rewrite as a "Me" reference with a conversion ' to the base type and with no virtual calls. Debug.Assert(node.SuppressVirtualCalls) Dim syntax = node.Syntax Dim meParameter = Me.GetRewrittenMeParameter(syntax, node) Debug.Assert(meParameter.Type.TypeKind = TypeKind.Class) ' Illegal in structures and modules. Dim baseType = node.Type Debug.Assert(baseType.TypeKind = TypeKind.Class) ' Illegal in structures and modules. Dim result = New BoundDirectCast( syntax:=syntax, operand:=meParameter, conversionKind:=ConversionKind.WideningReference, ' From a class to its base class. suppressVirtualCalls:=node.SuppressVirtualCalls, constantValueOpt:=Nothing, relaxationLambdaOpt:=Nothing, type:=baseType) Debug.Assert(TypeSymbol.Equals(result.Type, node.Type, TypeCompareKind.ConsiderEverything)) Return result End Function Public Overrides Function VisitMyClassReference(node As BoundMyClassReference) As BoundNode ' MyClass is just Me with virtual calls suppressed. Debug.Assert(node.SuppressVirtualCalls) Return Me.GetRewrittenMeParameter(node.Syntax, node) End Function Public Overrides Function VisitValueTypeMeReference(node As BoundValueTypeMeReference) As BoundNode ' ValueTypeMe is just Me with IsLValue true. Debug.Assert(node.IsLValue) Return Me.GetRewrittenMeParameter(node.Syntax, node) End Function Private Function GetRewrittenMeParameter(syntax As SyntaxNode, node As BoundExpression) As BoundExpression If _targetMethodMeParameter Is Nothing Then ReportMissingMe(node.Syntax) Return node End If Dim result = RewriteParameter(syntax, _targetMethodMeParameter, node) Debug.Assert(result IsNot Nothing) Return result End Function Private Function RewriteParameter(syntax As SyntaxNode, symbol As ParameterSymbol, node As BoundExpression) As BoundExpression Dim name As String = symbol.Name Dim variable = Me.GetVariable(name) If variable Is Nothing Then ' The state machine case is for async lambdas. The state machine ' will have a hoisted "me" field if it needs access to the containing ' display class, but the display class may not have a "me" field. If symbol.Type.IsClosureOrStateMachineType() AndAlso GeneratedNames.GetKind(name) <> GeneratedNameKind.TransparentIdentifier Then ReportMissingMe(syntax) End If Return If(TryCast(node, BoundParameter), New BoundParameter(syntax, symbol, node.IsLValue, node.SuppressVirtualCalls, symbol.Type)) End If Dim result = variable.ToBoundExpression(syntax, node.IsLValue, node.SuppressVirtualCalls) Debug.Assert(TypeSymbol.Equals(result.Type, node.Type, TypeCompareKind.ConsiderEverything) OrElse TypeSymbol.Equals(result.Type.BaseTypeNoUseSiteDiagnostics, node.Type, TypeCompareKind.ConsiderEverything)) Return result End Function Private Sub ReportMissingMe(syntax As SyntaxNode) _diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_UseOfKeywordNotInInstanceMethod1, syntax.ToString()), syntax.GetLocation())) End Sub Private Function GetVariable(name As String) As DisplayClassVariable Dim variable As DisplayClassVariable = Nothing _displayClassVariables.TryGetValue(name, variable) Return variable 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.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Friend NotInheritable Class CapturedVariableRewriter Inherits BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator Friend Shared Function Rewrite( targetMethodMeParameter As ParameterSymbol, displayClassVariables As ImmutableDictionary(Of String, DisplayClassVariable), node As BoundNode, diagnostics As DiagnosticBag) As BoundNode Dim rewriter = New CapturedVariableRewriter(targetMethodMeParameter, displayClassVariables, diagnostics) Return rewriter.Visit(node) End Function Private ReadOnly _targetMethodMeParameter As ParameterSymbol Private ReadOnly _displayClassVariables As ImmutableDictionary(Of String, DisplayClassVariable) Private ReadOnly _diagnostics As DiagnosticBag Private Sub New( targetMethodMeParameter As ParameterSymbol, displayClassVariables As ImmutableDictionary(Of String, DisplayClassVariable), diagnostics As DiagnosticBag) _targetMethodMeParameter = targetMethodMeParameter _displayClassVariables = displayClassVariables _diagnostics = diagnostics End Sub Public Overrides Function Visit(node As BoundNode) As BoundNode ' Ignore nodes that will be rewritten to literals in the LocalRewriter. If TryCast(node, BoundExpression)?.ConstantValueOpt IsNot Nothing Then Return node End If Return MyBase.Visit(node) End Function Public Overrides Function VisitBlock(node As BoundBlock) As BoundNode Dim rewrittenLocals = node.Locals.WhereAsArray(AddressOf IncludeLocal) Dim rewrittenStatements = VisitList(node.Statements) Return node.Update(node.StatementListSyntax, rewrittenLocals, rewrittenStatements) End Function Private Function IncludeLocal(local As LocalSymbol) As Boolean Return Not local.IsStatic AndAlso (local.IsCompilerGenerated OrElse local.Name Is Nothing OrElse GetVariable(local.Name) Is Nothing) End Function Public Overrides Function VisitLocal(node As BoundLocal) As BoundNode Dim local = node.LocalSymbol If Not local.IsCompilerGenerated Then Dim syntax = node.Syntax Dim staticLocal = TryCast(local, EEStaticLocalSymbol) If staticLocal IsNot Nothing Then Dim receiver = If(_targetMethodMeParameter Is Nothing, Nothing, GetRewrittenMeParameter(syntax, New BoundMeReference(syntax, _targetMethodMeParameter.Type))) Dim result = staticLocal.ToBoundExpression(receiver, syntax, node.IsLValue) Debug.Assert(TypeSymbol.Equals(node.Type, result.Type, TypeCompareKind.ConsiderEverything)) Return result End If Dim variable = GetVariable(local.Name) If variable IsNot Nothing Then Dim result = variable.ToBoundExpression(syntax, node.IsLValue, node.SuppressVirtualCalls) Debug.Assert(TypeSymbol.Equals(node.Type, result.Type, TypeCompareKind.ConsiderEverything)) Return result End If End If Return node End Function Public Overrides Function VisitParameter(node As BoundParameter) As BoundNode Return RewriteParameter(node.Syntax, node.ParameterSymbol, node) End Function Public Overrides Function VisitMeReference(node As BoundMeReference) As BoundNode Return Me.GetRewrittenMeParameter(node.Syntax, node) End Function Public Overrides Function VisitMyBaseReference(node As BoundMyBaseReference) As BoundNode ' Rewrite as a "Me" reference with a conversion ' to the base type and with no virtual calls. Debug.Assert(node.SuppressVirtualCalls) Dim syntax = node.Syntax Dim meParameter = Me.GetRewrittenMeParameter(syntax, node) Debug.Assert(meParameter.Type.TypeKind = TypeKind.Class) ' Illegal in structures and modules. Dim baseType = node.Type Debug.Assert(baseType.TypeKind = TypeKind.Class) ' Illegal in structures and modules. Dim result = New BoundDirectCast( syntax:=syntax, operand:=meParameter, conversionKind:=ConversionKind.WideningReference, ' From a class to its base class. suppressVirtualCalls:=node.SuppressVirtualCalls, constantValueOpt:=Nothing, relaxationLambdaOpt:=Nothing, type:=baseType) Debug.Assert(TypeSymbol.Equals(result.Type, node.Type, TypeCompareKind.ConsiderEverything)) Return result End Function Public Overrides Function VisitMyClassReference(node As BoundMyClassReference) As BoundNode ' MyClass is just Me with virtual calls suppressed. Debug.Assert(node.SuppressVirtualCalls) Return Me.GetRewrittenMeParameter(node.Syntax, node) End Function Public Overrides Function VisitValueTypeMeReference(node As BoundValueTypeMeReference) As BoundNode ' ValueTypeMe is just Me with IsLValue true. Debug.Assert(node.IsLValue) Return Me.GetRewrittenMeParameter(node.Syntax, node) End Function Private Function GetRewrittenMeParameter(syntax As SyntaxNode, node As BoundExpression) As BoundExpression If _targetMethodMeParameter Is Nothing Then ReportMissingMe(node.Syntax) Return node End If Dim result = RewriteParameter(syntax, _targetMethodMeParameter, node) Debug.Assert(result IsNot Nothing) Return result End Function Private Function RewriteParameter(syntax As SyntaxNode, symbol As ParameterSymbol, node As BoundExpression) As BoundExpression Dim name As String = symbol.Name Dim variable = Me.GetVariable(name) If variable Is Nothing Then ' The state machine case is for async lambdas. The state machine ' will have a hoisted "me" field if it needs access to the containing ' display class, but the display class may not have a "me" field. If symbol.Type.IsClosureOrStateMachineType() AndAlso GeneratedNames.GetKind(name) <> GeneratedNameKind.TransparentIdentifier Then ReportMissingMe(syntax) End If Return If(TryCast(node, BoundParameter), New BoundParameter(syntax, symbol, node.IsLValue, node.SuppressVirtualCalls, symbol.Type)) End If Dim result = variable.ToBoundExpression(syntax, node.IsLValue, node.SuppressVirtualCalls) Debug.Assert(TypeSymbol.Equals(result.Type, node.Type, TypeCompareKind.ConsiderEverything) OrElse TypeSymbol.Equals(result.Type.BaseTypeNoUseSiteDiagnostics, node.Type, TypeCompareKind.ConsiderEverything)) Return result End Function Private Sub ReportMissingMe(syntax As SyntaxNode) _diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_UseOfKeywordNotInInstanceMethod1, syntax.ToString()), syntax.GetLocation())) End Sub Private Function GetVariable(name As String) As DisplayClassVariable Dim variable As DisplayClassVariable = Nothing _displayClassVariables.TryGetValue(name, variable) Return variable End Function End Class End Namespace
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/Core/Portable/Text/CompositeText.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.IO; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Text { /// <summary> /// A composite of a sequence of <see cref="SourceText"/>s. /// </summary> internal sealed class CompositeText : SourceText { private readonly ImmutableArray<SourceText> _segments; private readonly int _length; private readonly int _storageSize; private readonly int[] _segmentOffsets; private readonly Encoding? _encoding; private CompositeText(ImmutableArray<SourceText> segments, Encoding? encoding, SourceHashAlgorithm checksumAlgorithm) : base(checksumAlgorithm: checksumAlgorithm) { Debug.Assert(!segments.IsDefaultOrEmpty); _segments = segments; _encoding = encoding; ComputeLengthAndStorageSize(segments, out _length, out _storageSize); _segmentOffsets = new int[segments.Length]; int offset = 0; for (int i = 0; i < _segmentOffsets.Length; i++) { _segmentOffsets[i] = offset; offset += _segments[i].Length; } } public override Encoding? Encoding { get { return _encoding; } } public override int Length { get { return _length; } } internal override int StorageSize { get { return _storageSize; } } internal override ImmutableArray<SourceText> Segments { get { return _segments; } } public override char this[int position] { get { int index; int offset; GetIndexAndOffset(position, out index, out offset); return _segments[index][offset]; } } public override SourceText GetSubText(TextSpan span) { CheckSubSpan(span); var sourceIndex = span.Start; var count = span.Length; int segIndex; int segOffset; GetIndexAndOffset(sourceIndex, out segIndex, out segOffset); var newSegments = ArrayBuilder<SourceText>.GetInstance(); try { while (segIndex < _segments.Length && count > 0) { var segment = _segments[segIndex]; var copyLength = Math.Min(count, segment.Length - segOffset); AddSegments(newSegments, segment.GetSubText(new TextSpan(segOffset, copyLength))); count -= copyLength; segIndex++; segOffset = 0; } return ToSourceText(newSegments, this, adjustSegments: false); } finally { newSegments.Free(); } } private void GetIndexAndOffset(int position, out int index, out int offset) { // Binary search to find the chunk that contains the given position. int idx = _segmentOffsets.BinarySearch(position); index = idx >= 0 ? idx : (~idx - 1); offset = position - _segmentOffsets[index]; } /// <summary> /// Validates the arguments passed to <see cref="CopyTo"/> against the published contract. /// </summary> /// <returns>True if should bother to proceed with copying.</returns> private bool CheckCopyToArguments(int sourceIndex, char[] destination, int destinationIndex, int count) { if (destination == null) throw new ArgumentNullException(nameof(destination)); if (sourceIndex < 0) throw new ArgumentOutOfRangeException(nameof(sourceIndex)); if (destinationIndex < 0) throw new ArgumentOutOfRangeException(nameof(destinationIndex)); if (count < 0 || count > this.Length - sourceIndex || count > destination.Length - destinationIndex) throw new ArgumentOutOfRangeException(nameof(count)); return count > 0; } public override void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) { if (!CheckCopyToArguments(sourceIndex, destination, destinationIndex, count)) return; int segIndex; int segOffset; GetIndexAndOffset(sourceIndex, out segIndex, out segOffset); while (segIndex < _segments.Length && count > 0) { var segment = _segments[segIndex]; var copyLength = Math.Min(count, segment.Length - segOffset); segment.CopyTo(segOffset, destination, destinationIndex, copyLength); count -= copyLength; destinationIndex += copyLength; segIndex++; segOffset = 0; } } internal static void AddSegments(ArrayBuilder<SourceText> segments, SourceText text) { CompositeText? composite = text as CompositeText; if (composite == null) { segments.Add(text); } else { segments.AddRange(composite._segments); } } internal static SourceText ToSourceText(ArrayBuilder<SourceText> segments, SourceText original, bool adjustSegments) { if (adjustSegments) { TrimInaccessibleText(segments); ReduceSegmentCountIfNecessary(segments); } if (segments.Count == 0) { return SourceText.From(string.Empty, original.Encoding, original.ChecksumAlgorithm); } else if (segments.Count == 1) { return segments[0]; } else { return new CompositeText(segments.ToImmutable(), original.Encoding, original.ChecksumAlgorithm); } } // both of these numbers are currently arbitrary. internal const int TARGET_SEGMENT_COUNT_AFTER_REDUCTION = 32; internal const int MAXIMUM_SEGMENT_COUNT_BEFORE_REDUCTION = 64; /// <summary> /// Reduces the number of segments toward the target number of segments, /// if the number of segments is deemed to be too large (beyond the maximum). /// </summary> private static void ReduceSegmentCountIfNecessary(ArrayBuilder<SourceText> segments) { if (segments.Count > MAXIMUM_SEGMENT_COUNT_BEFORE_REDUCTION) { var segmentSize = GetMinimalSegmentSizeToUseForCombining(segments); CombineSegments(segments, segmentSize); } } // Allow combining segments if each has a size less than or equal to this amount. // This is some arbitrary number deemed to be small private const int INITIAL_SEGMENT_SIZE_FOR_COMBINING = 32; // Segments must be less than (or equal) to this size to be combined with other segments. // This is some arbitrary number that is a fraction of max int. private const int MAXIMUM_SEGMENT_SIZE_FOR_COMBINING = int.MaxValue / 16; /// <summary> /// Determines the segment size to use for call to CombineSegments, that will result in the segment count /// being reduced to less than or equal to the target segment count. /// </summary> private static int GetMinimalSegmentSizeToUseForCombining(ArrayBuilder<SourceText> segments) { // find the minimal segment size that reduces enough segments to less that or equal to the ideal segment count for (var segmentSize = INITIAL_SEGMENT_SIZE_FOR_COMBINING; segmentSize <= MAXIMUM_SEGMENT_SIZE_FOR_COMBINING; segmentSize *= 2) { if (GetSegmentCountIfCombined(segments, segmentSize) <= TARGET_SEGMENT_COUNT_AFTER_REDUCTION) { return segmentSize; } } return MAXIMUM_SEGMENT_SIZE_FOR_COMBINING; } /// <summary> /// Determines the segment count that would result if the segments of size less than or equal to /// the specified segment size were to be combined. /// </summary> private static int GetSegmentCountIfCombined(ArrayBuilder<SourceText> segments, int segmentSize) { int numberOfSegmentsReduced = 0; for (int i = 0; i < segments.Count - 1; i++) { if (segments[i].Length <= segmentSize) { // count how many contiguous segments can be combined int count = 1; for (int j = i + 1; j < segments.Count; j++) { if (segments[j].Length <= segmentSize) { count++; } } if (count > 1) { var removed = count - 1; numberOfSegmentsReduced += removed; i += removed; } } } return segments.Count - numberOfSegmentsReduced; } /// <summary> /// Combines contiguous segments with lengths that are each less than or equal to the specified segment size. /// </summary> private static void CombineSegments(ArrayBuilder<SourceText> segments, int segmentSize) { for (int i = 0; i < segments.Count - 1; i++) { if (segments[i].Length <= segmentSize) { int combinedLength = segments[i].Length; // count how many contiguous segments are reducible int count = 1; for (int j = i + 1; j < segments.Count; j++) { if (segments[j].Length <= segmentSize) { count++; combinedLength += segments[j].Length; } } // if we've got at least two, then combine them into a single text if (count > 1) { var encoding = segments[i].Encoding; var algorithm = segments[i].ChecksumAlgorithm; var writer = SourceTextWriter.Create(encoding, algorithm, combinedLength); while (count > 0) { segments[i].Write(writer); segments.RemoveAt(i); count--; } var newText = writer.ToSourceText(); segments.Insert(i, newText); } } } } private static readonly ObjectPool<HashSet<SourceText>> s_uniqueSourcesPool = new ObjectPool<HashSet<SourceText>>(() => new HashSet<SourceText>(), 5); /// <summary> /// Compute total text length and total size of storage buffers held /// </summary> private static void ComputeLengthAndStorageSize(IReadOnlyList<SourceText> segments, out int length, out int size) { var uniqueSources = s_uniqueSourcesPool.Allocate(); length = 0; for (int i = 0; i < segments.Count; i++) { var segment = segments[i]; length += segment.Length; uniqueSources.Add(segment.StorageKey); } size = 0; foreach (var segment in uniqueSources) { size += segment.StorageSize; } uniqueSources.Clear(); s_uniqueSourcesPool.Free(uniqueSources); } /// <summary> /// Trim excessive inaccessible text. /// </summary> private static void TrimInaccessibleText(ArrayBuilder<SourceText> segments) { int length, size; ComputeLengthAndStorageSize(segments, out length, out size); // if more than half of the storage is unused, compress into a single new segment if (length < size / 2) { var encoding = segments[0].Encoding; var algorithm = segments[0].ChecksumAlgorithm; var writer = SourceTextWriter.Create(encoding, algorithm, length); foreach (var segment in segments) { segment.Write(writer); } segments.Clear(); segments.Add(writer.ToSourceText()); } } } }
// Licensed to the .NET Foundation under one or more 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.IO; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Text { /// <summary> /// A composite of a sequence of <see cref="SourceText"/>s. /// </summary> internal sealed class CompositeText : SourceText { private readonly ImmutableArray<SourceText> _segments; private readonly int _length; private readonly int _storageSize; private readonly int[] _segmentOffsets; private readonly Encoding? _encoding; private CompositeText(ImmutableArray<SourceText> segments, Encoding? encoding, SourceHashAlgorithm checksumAlgorithm) : base(checksumAlgorithm: checksumAlgorithm) { Debug.Assert(!segments.IsDefaultOrEmpty); _segments = segments; _encoding = encoding; ComputeLengthAndStorageSize(segments, out _length, out _storageSize); _segmentOffsets = new int[segments.Length]; int offset = 0; for (int i = 0; i < _segmentOffsets.Length; i++) { _segmentOffsets[i] = offset; offset += _segments[i].Length; } } public override Encoding? Encoding { get { return _encoding; } } public override int Length { get { return _length; } } internal override int StorageSize { get { return _storageSize; } } internal override ImmutableArray<SourceText> Segments { get { return _segments; } } public override char this[int position] { get { int index; int offset; GetIndexAndOffset(position, out index, out offset); return _segments[index][offset]; } } public override SourceText GetSubText(TextSpan span) { CheckSubSpan(span); var sourceIndex = span.Start; var count = span.Length; int segIndex; int segOffset; GetIndexAndOffset(sourceIndex, out segIndex, out segOffset); var newSegments = ArrayBuilder<SourceText>.GetInstance(); try { while (segIndex < _segments.Length && count > 0) { var segment = _segments[segIndex]; var copyLength = Math.Min(count, segment.Length - segOffset); AddSegments(newSegments, segment.GetSubText(new TextSpan(segOffset, copyLength))); count -= copyLength; segIndex++; segOffset = 0; } return ToSourceText(newSegments, this, adjustSegments: false); } finally { newSegments.Free(); } } private void GetIndexAndOffset(int position, out int index, out int offset) { // Binary search to find the chunk that contains the given position. int idx = _segmentOffsets.BinarySearch(position); index = idx >= 0 ? idx : (~idx - 1); offset = position - _segmentOffsets[index]; } /// <summary> /// Validates the arguments passed to <see cref="CopyTo"/> against the published contract. /// </summary> /// <returns>True if should bother to proceed with copying.</returns> private bool CheckCopyToArguments(int sourceIndex, char[] destination, int destinationIndex, int count) { if (destination == null) throw new ArgumentNullException(nameof(destination)); if (sourceIndex < 0) throw new ArgumentOutOfRangeException(nameof(sourceIndex)); if (destinationIndex < 0) throw new ArgumentOutOfRangeException(nameof(destinationIndex)); if (count < 0 || count > this.Length - sourceIndex || count > destination.Length - destinationIndex) throw new ArgumentOutOfRangeException(nameof(count)); return count > 0; } public override void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) { if (!CheckCopyToArguments(sourceIndex, destination, destinationIndex, count)) return; int segIndex; int segOffset; GetIndexAndOffset(sourceIndex, out segIndex, out segOffset); while (segIndex < _segments.Length && count > 0) { var segment = _segments[segIndex]; var copyLength = Math.Min(count, segment.Length - segOffset); segment.CopyTo(segOffset, destination, destinationIndex, copyLength); count -= copyLength; destinationIndex += copyLength; segIndex++; segOffset = 0; } } internal static void AddSegments(ArrayBuilder<SourceText> segments, SourceText text) { CompositeText? composite = text as CompositeText; if (composite == null) { segments.Add(text); } else { segments.AddRange(composite._segments); } } internal static SourceText ToSourceText(ArrayBuilder<SourceText> segments, SourceText original, bool adjustSegments) { if (adjustSegments) { TrimInaccessibleText(segments); ReduceSegmentCountIfNecessary(segments); } if (segments.Count == 0) { return SourceText.From(string.Empty, original.Encoding, original.ChecksumAlgorithm); } else if (segments.Count == 1) { return segments[0]; } else { return new CompositeText(segments.ToImmutable(), original.Encoding, original.ChecksumAlgorithm); } } // both of these numbers are currently arbitrary. internal const int TARGET_SEGMENT_COUNT_AFTER_REDUCTION = 32; internal const int MAXIMUM_SEGMENT_COUNT_BEFORE_REDUCTION = 64; /// <summary> /// Reduces the number of segments toward the target number of segments, /// if the number of segments is deemed to be too large (beyond the maximum). /// </summary> private static void ReduceSegmentCountIfNecessary(ArrayBuilder<SourceText> segments) { if (segments.Count > MAXIMUM_SEGMENT_COUNT_BEFORE_REDUCTION) { var segmentSize = GetMinimalSegmentSizeToUseForCombining(segments); CombineSegments(segments, segmentSize); } } // Allow combining segments if each has a size less than or equal to this amount. // This is some arbitrary number deemed to be small private const int INITIAL_SEGMENT_SIZE_FOR_COMBINING = 32; // Segments must be less than (or equal) to this size to be combined with other segments. // This is some arbitrary number that is a fraction of max int. private const int MAXIMUM_SEGMENT_SIZE_FOR_COMBINING = int.MaxValue / 16; /// <summary> /// Determines the segment size to use for call to CombineSegments, that will result in the segment count /// being reduced to less than or equal to the target segment count. /// </summary> private static int GetMinimalSegmentSizeToUseForCombining(ArrayBuilder<SourceText> segments) { // find the minimal segment size that reduces enough segments to less that or equal to the ideal segment count for (var segmentSize = INITIAL_SEGMENT_SIZE_FOR_COMBINING; segmentSize <= MAXIMUM_SEGMENT_SIZE_FOR_COMBINING; segmentSize *= 2) { if (GetSegmentCountIfCombined(segments, segmentSize) <= TARGET_SEGMENT_COUNT_AFTER_REDUCTION) { return segmentSize; } } return MAXIMUM_SEGMENT_SIZE_FOR_COMBINING; } /// <summary> /// Determines the segment count that would result if the segments of size less than or equal to /// the specified segment size were to be combined. /// </summary> private static int GetSegmentCountIfCombined(ArrayBuilder<SourceText> segments, int segmentSize) { int numberOfSegmentsReduced = 0; for (int i = 0; i < segments.Count - 1; i++) { if (segments[i].Length <= segmentSize) { // count how many contiguous segments can be combined int count = 1; for (int j = i + 1; j < segments.Count; j++) { if (segments[j].Length <= segmentSize) { count++; } } if (count > 1) { var removed = count - 1; numberOfSegmentsReduced += removed; i += removed; } } } return segments.Count - numberOfSegmentsReduced; } /// <summary> /// Combines contiguous segments with lengths that are each less than or equal to the specified segment size. /// </summary> private static void CombineSegments(ArrayBuilder<SourceText> segments, int segmentSize) { for (int i = 0; i < segments.Count - 1; i++) { if (segments[i].Length <= segmentSize) { int combinedLength = segments[i].Length; // count how many contiguous segments are reducible int count = 1; for (int j = i + 1; j < segments.Count; j++) { if (segments[j].Length <= segmentSize) { count++; combinedLength += segments[j].Length; } } // if we've got at least two, then combine them into a single text if (count > 1) { var encoding = segments[i].Encoding; var algorithm = segments[i].ChecksumAlgorithm; var writer = SourceTextWriter.Create(encoding, algorithm, combinedLength); while (count > 0) { segments[i].Write(writer); segments.RemoveAt(i); count--; } var newText = writer.ToSourceText(); segments.Insert(i, newText); } } } } private static readonly ObjectPool<HashSet<SourceText>> s_uniqueSourcesPool = new ObjectPool<HashSet<SourceText>>(() => new HashSet<SourceText>(), 5); /// <summary> /// Compute total text length and total size of storage buffers held /// </summary> private static void ComputeLengthAndStorageSize(IReadOnlyList<SourceText> segments, out int length, out int size) { var uniqueSources = s_uniqueSourcesPool.Allocate(); length = 0; for (int i = 0; i < segments.Count; i++) { var segment = segments[i]; length += segment.Length; uniqueSources.Add(segment.StorageKey); } size = 0; foreach (var segment in uniqueSources) { size += segment.StorageSize; } uniqueSources.Clear(); s_uniqueSourcesPool.Free(uniqueSources); } /// <summary> /// Trim excessive inaccessible text. /// </summary> private static void TrimInaccessibleText(ArrayBuilder<SourceText> segments) { int length, size; ComputeLengthAndStorageSize(segments, out length, out size); // if more than half of the storage is unused, compress into a single new segment if (length < size / 2) { var encoding = segments[0].Encoding; var algorithm = segments[0].ChecksumAlgorithm; var writer = SourceTextWriter.Create(encoding, algorithm, length); foreach (var segment in segments) { segment.Write(writer); } segments.Clear(); segments.Add(writer.ToSourceText()); } } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Features/CSharp/Portable/UseAutoProperty/CSharpUseAutoPropertyCodeFixProvider.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.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.UseAutoProperty; namespace Microsoft.CodeAnalysis.CSharp.UseAutoProperty { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseAutoProperty), Shared] internal class CSharpUseAutoPropertyCodeFixProvider : AbstractUseAutoPropertyCodeFixProvider<TypeDeclarationSyntax, PropertyDeclarationSyntax, VariableDeclaratorSyntax, ConstructorDeclarationSyntax, ExpressionSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpUseAutoPropertyCodeFixProvider() { } protected override PropertyDeclarationSyntax GetPropertyDeclaration(SyntaxNode node) => (PropertyDeclarationSyntax)node; protected override SyntaxNode GetNodeToRemove(VariableDeclaratorSyntax declarator) { var fieldDeclaration = (FieldDeclarationSyntax)declarator.Parent.Parent; var nodeToRemove = fieldDeclaration.Declaration.Variables.Count > 1 ? declarator : (SyntaxNode)fieldDeclaration; return nodeToRemove; } protected override async Task<SyntaxNode> UpdatePropertyAsync( Document propertyDocument, Compilation compilation, IFieldSymbol fieldSymbol, IPropertySymbol propertySymbol, PropertyDeclarationSyntax propertyDeclaration, bool isWrittenOutsideOfConstructor, CancellationToken cancellationToken) { var project = propertyDocument.Project; var trailingTrivia = propertyDeclaration.GetTrailingTrivia(); var updatedProperty = propertyDeclaration.WithAccessorList(UpdateAccessorList(propertyDeclaration.AccessorList)) .WithExpressionBody(null) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None)); // We may need to add a setter if the field is written to outside of the constructor // of it's class. if (NeedsSetter(compilation, propertyDeclaration, isWrittenOutsideOfConstructor)) { var accessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); var generator = SyntaxGenerator.GetGenerator(project); if (fieldSymbol.DeclaredAccessibility != propertySymbol.DeclaredAccessibility) { accessor = (AccessorDeclarationSyntax)generator.WithAccessibility(accessor, fieldSymbol.DeclaredAccessibility); } var modifiers = SyntaxFactory.TokenList( updatedProperty.Modifiers.Where(token => !token.IsKind(SyntaxKind.ReadOnlyKeyword))); updatedProperty = updatedProperty.WithModifiers(modifiers) .AddAccessorListAccessors(accessor); } var fieldInitializer = await GetFieldInitializerAsync(fieldSymbol, cancellationToken).ConfigureAwait(false); if (fieldInitializer != null) { updatedProperty = updatedProperty.WithInitializer(SyntaxFactory.EqualsValueClause(fieldInitializer)) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); } return updatedProperty.WithTrailingTrivia(trailingTrivia).WithAdditionalAnnotations(SpecializedFormattingAnnotation); } protected override IEnumerable<AbstractFormattingRule> GetFormattingRules(Document document) { var rules = new List<AbstractFormattingRule> { new SingleLinePropertyFormattingRule() }; rules.AddRange(Formatter.GetDefaultFormattingRules(document)); return rules; } private class SingleLinePropertyFormattingRule : AbstractFormattingRule { private static bool ForceSingleSpace(SyntaxToken previousToken, SyntaxToken currentToken) { if (currentToken.IsKind(SyntaxKind.OpenBraceToken) && currentToken.Parent.IsKind(SyntaxKind.AccessorList)) { return true; } if (previousToken.IsKind(SyntaxKind.OpenBraceToken) && previousToken.Parent.IsKind(SyntaxKind.AccessorList)) { return true; } if (currentToken.IsKind(SyntaxKind.CloseBraceToken) && currentToken.Parent.IsKind(SyntaxKind.AccessorList)) { return true; } return false; } public override AdjustNewLinesOperation GetAdjustNewLinesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation) { if (ForceSingleSpace(previousToken, currentToken)) { return null; } return base.GetAdjustNewLinesOperation(in previousToken, in currentToken, in nextOperation); } public override AdjustSpacesOperation GetAdjustSpacesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustSpacesOperation nextOperation) { if (ForceSingleSpace(previousToken, currentToken)) { return new AdjustSpacesOperation(1, AdjustSpacesOption.ForceSpaces); } return base.GetAdjustSpacesOperation(in previousToken, in currentToken, in nextOperation); } } private static async Task<ExpressionSyntax> GetFieldInitializerAsync(IFieldSymbol fieldSymbol, CancellationToken cancellationToken) { var variableDeclarator = (VariableDeclaratorSyntax)await fieldSymbol.DeclaringSyntaxReferences[0].GetSyntaxAsync(cancellationToken).ConfigureAwait(false); return variableDeclarator.Initializer?.Value; } private static bool NeedsSetter(Compilation compilation, PropertyDeclarationSyntax propertyDeclaration, bool isWrittenOutsideOfConstructor) { if (propertyDeclaration.AccessorList?.Accessors.Any(SyntaxKind.SetAccessorDeclaration) == true) { // Already has a setter. return false; } if (!SupportsReadOnlyProperties(compilation)) { // If the language doesn't have readonly properties, then we'll need a // setter here. return true; } // If we're written outside a constructor we need a setter. return isWrittenOutsideOfConstructor; } private static bool SupportsReadOnlyProperties(Compilation compilation) => ((CSharpCompilation)compilation).LanguageVersion >= LanguageVersion.CSharp6; private static AccessorListSyntax UpdateAccessorList(AccessorListSyntax accessorList) { if (accessorList == null) { var getter = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); return SyntaxFactory.AccessorList(SyntaxFactory.List(Enumerable.Repeat(getter, 1))); } return accessorList.WithAccessors(SyntaxFactory.List(GetAccessors(accessorList.Accessors))); } private static IEnumerable<AccessorDeclarationSyntax> GetAccessors(SyntaxList<AccessorDeclarationSyntax> accessors) { foreach (var accessor in accessors) { yield return accessor.WithBody(null) .WithExpressionBody(null) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.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. #nullable disable using System.Collections.Generic; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.UseAutoProperty; namespace Microsoft.CodeAnalysis.CSharp.UseAutoProperty { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseAutoProperty), Shared] internal class CSharpUseAutoPropertyCodeFixProvider : AbstractUseAutoPropertyCodeFixProvider<TypeDeclarationSyntax, PropertyDeclarationSyntax, VariableDeclaratorSyntax, ConstructorDeclarationSyntax, ExpressionSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpUseAutoPropertyCodeFixProvider() { } protected override PropertyDeclarationSyntax GetPropertyDeclaration(SyntaxNode node) => (PropertyDeclarationSyntax)node; protected override SyntaxNode GetNodeToRemove(VariableDeclaratorSyntax declarator) { var fieldDeclaration = (FieldDeclarationSyntax)declarator.Parent.Parent; var nodeToRemove = fieldDeclaration.Declaration.Variables.Count > 1 ? declarator : (SyntaxNode)fieldDeclaration; return nodeToRemove; } protected override async Task<SyntaxNode> UpdatePropertyAsync( Document propertyDocument, Compilation compilation, IFieldSymbol fieldSymbol, IPropertySymbol propertySymbol, PropertyDeclarationSyntax propertyDeclaration, bool isWrittenOutsideOfConstructor, CancellationToken cancellationToken) { var project = propertyDocument.Project; var trailingTrivia = propertyDeclaration.GetTrailingTrivia(); var updatedProperty = propertyDeclaration.WithAccessorList(UpdateAccessorList(propertyDeclaration.AccessorList)) .WithExpressionBody(null) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None)); // We may need to add a setter if the field is written to outside of the constructor // of it's class. if (NeedsSetter(compilation, propertyDeclaration, isWrittenOutsideOfConstructor)) { var accessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); var generator = SyntaxGenerator.GetGenerator(project); if (fieldSymbol.DeclaredAccessibility != propertySymbol.DeclaredAccessibility) { accessor = (AccessorDeclarationSyntax)generator.WithAccessibility(accessor, fieldSymbol.DeclaredAccessibility); } var modifiers = SyntaxFactory.TokenList( updatedProperty.Modifiers.Where(token => !token.IsKind(SyntaxKind.ReadOnlyKeyword))); updatedProperty = updatedProperty.WithModifiers(modifiers) .AddAccessorListAccessors(accessor); } var fieldInitializer = await GetFieldInitializerAsync(fieldSymbol, cancellationToken).ConfigureAwait(false); if (fieldInitializer != null) { updatedProperty = updatedProperty.WithInitializer(SyntaxFactory.EqualsValueClause(fieldInitializer)) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); } return updatedProperty.WithTrailingTrivia(trailingTrivia).WithAdditionalAnnotations(SpecializedFormattingAnnotation); } protected override IEnumerable<AbstractFormattingRule> GetFormattingRules(Document document) { var rules = new List<AbstractFormattingRule> { new SingleLinePropertyFormattingRule() }; rules.AddRange(Formatter.GetDefaultFormattingRules(document)); return rules; } private class SingleLinePropertyFormattingRule : AbstractFormattingRule { private static bool ForceSingleSpace(SyntaxToken previousToken, SyntaxToken currentToken) { if (currentToken.IsKind(SyntaxKind.OpenBraceToken) && currentToken.Parent.IsKind(SyntaxKind.AccessorList)) { return true; } if (previousToken.IsKind(SyntaxKind.OpenBraceToken) && previousToken.Parent.IsKind(SyntaxKind.AccessorList)) { return true; } if (currentToken.IsKind(SyntaxKind.CloseBraceToken) && currentToken.Parent.IsKind(SyntaxKind.AccessorList)) { return true; } return false; } public override AdjustNewLinesOperation GetAdjustNewLinesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation) { if (ForceSingleSpace(previousToken, currentToken)) { return null; } return base.GetAdjustNewLinesOperation(in previousToken, in currentToken, in nextOperation); } public override AdjustSpacesOperation GetAdjustSpacesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustSpacesOperation nextOperation) { if (ForceSingleSpace(previousToken, currentToken)) { return new AdjustSpacesOperation(1, AdjustSpacesOption.ForceSpaces); } return base.GetAdjustSpacesOperation(in previousToken, in currentToken, in nextOperation); } } private static async Task<ExpressionSyntax> GetFieldInitializerAsync(IFieldSymbol fieldSymbol, CancellationToken cancellationToken) { var variableDeclarator = (VariableDeclaratorSyntax)await fieldSymbol.DeclaringSyntaxReferences[0].GetSyntaxAsync(cancellationToken).ConfigureAwait(false); return variableDeclarator.Initializer?.Value; } private static bool NeedsSetter(Compilation compilation, PropertyDeclarationSyntax propertyDeclaration, bool isWrittenOutsideOfConstructor) { if (propertyDeclaration.AccessorList?.Accessors.Any(SyntaxKind.SetAccessorDeclaration) == true) { // Already has a setter. return false; } if (!SupportsReadOnlyProperties(compilation)) { // If the language doesn't have readonly properties, then we'll need a // setter here. return true; } // If we're written outside a constructor we need a setter. return isWrittenOutsideOfConstructor; } private static bool SupportsReadOnlyProperties(Compilation compilation) => ((CSharpCompilation)compilation).LanguageVersion >= LanguageVersion.CSharp6; private static AccessorListSyntax UpdateAccessorList(AccessorListSyntax accessorList) { if (accessorList == null) { var getter = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); return SyntaxFactory.AccessorList(SyntaxFactory.List(Enumerable.Repeat(getter, 1))); } return accessorList.WithAccessors(SyntaxFactory.List(GetAccessors(accessorList.Accessors))); } private static IEnumerable<AccessorDeclarationSyntax> GetAccessors(SyntaxList<AccessorDeclarationSyntax> accessors) { foreach (var accessor in accessors) { yield return accessor.WithBody(null) .WithExpressionBody(null) .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)); } } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Portable/Symbols/PublicModel/NamespaceSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel { internal sealed class NamespaceSymbol : NamespaceOrTypeSymbol, INamespaceSymbol { private readonly Symbols.NamespaceSymbol _underlying; public NamespaceSymbol(Symbols.NamespaceSymbol underlying) { Debug.Assert(underlying is object); _underlying = underlying; } internal override CSharp.Symbol UnderlyingSymbol => _underlying; internal override Symbols.NamespaceOrTypeSymbol UnderlyingNamespaceOrTypeSymbol => _underlying; internal Symbols.NamespaceSymbol UnderlyingNamespaceSymbol => _underlying; bool INamespaceSymbol.IsGlobalNamespace => _underlying.IsGlobalNamespace; NamespaceKind INamespaceSymbol.NamespaceKind => _underlying.NamespaceKind; Compilation INamespaceSymbol.ContainingCompilation => _underlying.ContainingCompilation; ImmutableArray<INamespaceSymbol> INamespaceSymbol.ConstituentNamespaces { get { return _underlying.ConstituentNamespaces.GetPublicSymbols(); } } IEnumerable<INamespaceOrTypeSymbol> INamespaceSymbol.GetMembers() { foreach (var n in _underlying.GetMembers()) { yield return ((Symbols.NamespaceOrTypeSymbol)n).GetPublicSymbol(); } } IEnumerable<INamespaceOrTypeSymbol> INamespaceSymbol.GetMembers(string name) { foreach (var n in _underlying.GetMembers(name)) { yield return ((Symbols.NamespaceOrTypeSymbol)n).GetPublicSymbol(); } } IEnumerable<INamespaceSymbol> INamespaceSymbol.GetNamespaceMembers() { foreach (var n in _underlying.GetNamespaceMembers()) { yield return n.GetPublicSymbol(); } } #region ISymbol Members protected override void Accept(SymbolVisitor visitor) { visitor.VisitNamespace(this); } protected override TResult Accept<TResult>(SymbolVisitor<TResult> visitor) { return visitor.VisitNamespace(this); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel { internal sealed class NamespaceSymbol : NamespaceOrTypeSymbol, INamespaceSymbol { private readonly Symbols.NamespaceSymbol _underlying; public NamespaceSymbol(Symbols.NamespaceSymbol underlying) { Debug.Assert(underlying is object); _underlying = underlying; } internal override CSharp.Symbol UnderlyingSymbol => _underlying; internal override Symbols.NamespaceOrTypeSymbol UnderlyingNamespaceOrTypeSymbol => _underlying; internal Symbols.NamespaceSymbol UnderlyingNamespaceSymbol => _underlying; bool INamespaceSymbol.IsGlobalNamespace => _underlying.IsGlobalNamespace; NamespaceKind INamespaceSymbol.NamespaceKind => _underlying.NamespaceKind; Compilation INamespaceSymbol.ContainingCompilation => _underlying.ContainingCompilation; ImmutableArray<INamespaceSymbol> INamespaceSymbol.ConstituentNamespaces { get { return _underlying.ConstituentNamespaces.GetPublicSymbols(); } } IEnumerable<INamespaceOrTypeSymbol> INamespaceSymbol.GetMembers() { foreach (var n in _underlying.GetMembers()) { yield return ((Symbols.NamespaceOrTypeSymbol)n).GetPublicSymbol(); } } IEnumerable<INamespaceOrTypeSymbol> INamespaceSymbol.GetMembers(string name) { foreach (var n in _underlying.GetMembers(name)) { yield return ((Symbols.NamespaceOrTypeSymbol)n).GetPublicSymbol(); } } IEnumerable<INamespaceSymbol> INamespaceSymbol.GetNamespaceMembers() { foreach (var n in _underlying.GetNamespaceMembers()) { yield return n.GetPublicSymbol(); } } #region ISymbol Members protected override void Accept(SymbolVisitor visitor) { visitor.VisitNamespace(this); } protected override TResult Accept<TResult>(SymbolVisitor<TResult> visitor) { return visitor.VisitNamespace(this); } #endregion } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Features/VisualBasic/Portable/SplitOrMergeIfStatements/VisualBasicIfLikeStatementGenerator.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.SplitOrMergeIfStatements Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.SplitOrMergeIfStatements <ExportLanguageService(GetType(IIfLikeStatementGenerator), LanguageNames.VisualBasic), [Shared]> Friend NotInheritable Class VisualBasicIfLikeStatementGenerator Implements IIfLikeStatementGenerator <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Function IsIfOrElseIf(node As SyntaxNode) As Boolean Implements IIfLikeStatementGenerator.IsIfOrElseIf Return TypeOf node Is MultiLineIfBlockSyntax OrElse TypeOf node Is ElseIfBlockSyntax End Function Public Function IsCondition(expression As SyntaxNode, ByRef ifOrElseIf As SyntaxNode) As Boolean Implements IIfLikeStatementGenerator.IsCondition If TypeOf expression.Parent Is IfStatementSyntax AndAlso DirectCast(expression.Parent, IfStatementSyntax).Condition Is expression AndAlso TypeOf expression.Parent.Parent Is MultiLineIfBlockSyntax Then ifOrElseIf = expression.Parent.Parent Return True End If If TypeOf expression.Parent Is ElseIfStatementSyntax AndAlso DirectCast(expression.Parent, ElseIfStatementSyntax).Condition Is expression AndAlso TypeOf expression.Parent.Parent Is ElseIfBlockSyntax Then ifOrElseIf = expression.Parent.Parent Return True End If ifOrElseIf = Nothing Return False End Function Public Function IsElseIfClause(node As SyntaxNode, ByRef parentIfOrElseIf As SyntaxNode) As Boolean Implements IIfLikeStatementGenerator.IsElseIfClause If TypeOf node Is ElseIfBlockSyntax Then Dim ifBlock = DirectCast(node.Parent, MultiLineIfBlockSyntax) Dim index = ifBlock.ElseIfBlocks.IndexOf(DirectCast(node, ElseIfBlockSyntax)) parentIfOrElseIf = If(index > 0, ifBlock.ElseIfBlocks(index - 1), DirectCast(ifBlock, SyntaxNode)) Return True End If parentIfOrElseIf = Nothing Return False End Function Public Function HasElseIfClause(ifOrElseIf As SyntaxNode, ByRef elseIfClause As SyntaxNode) As Boolean Implements IIfLikeStatementGenerator.HasElseIfClause Dim ifBlock As MultiLineIfBlockSyntax Dim nextElseIfIndex As Integer If TypeOf ifOrElseIf Is MultiLineIfBlockSyntax Then ifBlock = DirectCast(ifOrElseIf, MultiLineIfBlockSyntax) nextElseIfIndex = 0 ElseIf TypeOf ifOrElseIf Is ElseIfBlockSyntax Then ifBlock = DirectCast(ifOrElseIf.Parent, MultiLineIfBlockSyntax) Dim index = ifBlock.ElseIfBlocks.IndexOf(DirectCast(ifOrElseIf, ElseIfBlockSyntax)) nextElseIfIndex = index + 1 Else Throw ExceptionUtilities.UnexpectedValue(ifOrElseIf) End If elseIfClause = ifBlock.ElseIfBlocks.ElementAtOrDefault(nextElseIfIndex) Return elseIfClause IsNot Nothing End Function Public Function GetCondition(ifOrElseIf As SyntaxNode) As SyntaxNode Implements IIfLikeStatementGenerator.GetCondition If TypeOf ifOrElseIf Is MultiLineIfBlockSyntax Then Return DirectCast(ifOrElseIf, MultiLineIfBlockSyntax).IfStatement.Condition ElseIf TypeOf ifOrElseIf Is ElseIfBlockSyntax Then Return DirectCast(ifOrElseIf, ElseIfBlockSyntax).ElseIfStatement.Condition Else Throw ExceptionUtilities.UnexpectedValue(ifOrElseIf) End If End Function Public Function GetRootIfStatement(ifOrElseIf As SyntaxNode) As SyntaxNode Implements IIfLikeStatementGenerator.GetRootIfStatement If TypeOf ifOrElseIf Is MultiLineIfBlockSyntax Then Return ifOrElseIf ElseIf TypeOf ifOrElseIf Is ElseIfBlockSyntax Then Return ifOrElseIf.Parent Else Throw ExceptionUtilities.UnexpectedValue(ifOrElseIf) End If End Function Public Function GetElseIfAndElseClauses(ifOrElseIf As SyntaxNode) As ImmutableArray(Of SyntaxNode) Implements IIfLikeStatementGenerator.GetElseIfAndElseClauses If TypeOf ifOrElseIf Is MultiLineIfBlockSyntax Then Dim ifBlock = DirectCast(ifOrElseIf, MultiLineIfBlockSyntax) Return AddIfNotNull(ifBlock.ElseIfBlocks, ifBlock.ElseBlock).ToImmutableArray() ElseIf TypeOf ifOrElseIf Is ElseIfBlockSyntax Then Dim elseIfBlock = DirectCast(ifOrElseIf, ElseIfBlockSyntax) Dim ifBlock = DirectCast(elseIfBlock.Parent, MultiLineIfBlockSyntax) Dim nextElseIfBlocks = ifBlock.ElseIfBlocks.RemoveRange(0, ifBlock.ElseIfBlocks.IndexOf(elseIfBlock) + 1) Return AddIfNotNull(nextElseIfBlocks, ifBlock.ElseBlock).ToImmutableArray() Else Throw ExceptionUtilities.UnexpectedValue(ifOrElseIf) End If End Function Private Shared Function AddIfNotNull(list As SyntaxList(Of SyntaxNode), node As SyntaxNode) As SyntaxList(Of SyntaxNode) Return If(node IsNot Nothing, list.Add(node), list) End Function Public Function WithCondition(ifOrElseIf As SyntaxNode, condition As SyntaxNode) As SyntaxNode Implements IIfLikeStatementGenerator.WithCondition If TypeOf ifOrElseIf Is MultiLineIfBlockSyntax Then Dim ifBlock = DirectCast(ifOrElseIf, MultiLineIfBlockSyntax) Return ifBlock.WithIfStatement(ifBlock.IfStatement.WithCondition(DirectCast(condition, ExpressionSyntax))) ElseIf TypeOf ifOrElseIf Is ElseIfBlockSyntax Then Dim elseIfBlock = DirectCast(ifOrElseIf, ElseIfBlockSyntax) Return elseIfBlock.WithElseIfStatement(elseIfBlock.ElseIfStatement.WithCondition(DirectCast(condition, ExpressionSyntax))) Else Throw ExceptionUtilities.UnexpectedValue(ifOrElseIf) End If End Function Public Function WithStatementInBlock(ifOrElseIf As SyntaxNode, statement As SyntaxNode) As SyntaxNode Implements IIfLikeStatementGenerator.WithStatementInBlock Return ifOrElseIf.ReplaceStatements(SyntaxFactory.SingletonList(DirectCast(statement, StatementSyntax))) End Function Public Function WithStatementsOf(ifOrElseIf As SyntaxNode, otherIfOrElseIf As SyntaxNode) As SyntaxNode Implements IIfLikeStatementGenerator.WithStatementsOf Return ifOrElseIf.ReplaceStatements(otherIfOrElseIf.GetStatements()) End Function Public Function WithElseIfAndElseClausesOf(ifStatement As SyntaxNode, otherIfStatement As SyntaxNode) As SyntaxNode Implements IIfLikeStatementGenerator.WithElseIfAndElseClausesOf Dim ifBlock = DirectCast(ifStatement, MultiLineIfBlockSyntax) Dim otherIfBlock = DirectCast(otherIfStatement, MultiLineIfBlockSyntax) Return ifBlock.WithElseIfBlocks(otherIfBlock.ElseIfBlocks).WithElseBlock(otherIfBlock.ElseBlock) End Function Public Function ToIfStatement(ifOrElseIf As SyntaxNode) As SyntaxNode Implements IIfLikeStatementGenerator.ToIfStatement If TypeOf ifOrElseIf Is MultiLineIfBlockSyntax Then Return ifOrElseIf ElseIf TypeOf ifOrElseIf Is ElseIfBlockSyntax Then Dim elseIfBlock = DirectCast(ifOrElseIf, ElseIfBlockSyntax) Dim ifBlock = DirectCast(elseIfBlock.Parent, MultiLineIfBlockSyntax) Dim nextElseIfBlocks = ifBlock.ElseIfBlocks.RemoveRange(0, ifBlock.ElseIfBlocks.IndexOf(elseIfBlock) + 1) Dim newIfStatement = SyntaxFactory.IfStatement(ifBlock.IfStatement.IfKeyword, elseIfBlock.ElseIfStatement.Condition, elseIfBlock.ElseIfStatement.ThenKeyword) Dim newIfBlock = SyntaxFactory.MultiLineIfBlock(newIfStatement, elseIfBlock.Statements, nextElseIfBlocks, ifBlock.ElseBlock, ifBlock.EndIfStatement) Return newIfBlock Else Throw ExceptionUtilities.UnexpectedValue(ifOrElseIf) End If End Function Public Function ToElseIfClause(ifOrElseIf As SyntaxNode) As SyntaxNode Implements IIfLikeStatementGenerator.ToElseIfClause If TypeOf ifOrElseIf Is MultiLineIfBlockSyntax Then Dim ifBlock = DirectCast(ifOrElseIf, MultiLineIfBlockSyntax) Dim newElseIfStatement = SyntaxFactory.ElseIfStatement(SyntaxFactory.Token(SyntaxKind.ElseIfKeyword), ifBlock.IfStatement.Condition, ifBlock.IfStatement.ThenKeyword) Dim newElseIfBlock = SyntaxFactory.ElseIfBlock(newElseIfStatement, ifBlock.Statements) Return newElseIfBlock ElseIf TypeOf ifOrElseIf Is ElseIfBlockSyntax Then Return ifOrElseIf Else Throw ExceptionUtilities.UnexpectedValue(ifOrElseIf) End If End Function Public Sub InsertElseIfClause(editor As SyntaxEditor, afterIfOrElseIf As SyntaxNode, elseIfClause As SyntaxNode) Implements IIfLikeStatementGenerator.InsertElseIfClause Dim elseIfBlockToInsert = DirectCast(elseIfClause, ElseIfBlockSyntax) If TypeOf afterIfOrElseIf Is MultiLineIfBlockSyntax Then editor.ReplaceNode(afterIfOrElseIf, Function(currentNode, g) Dim ifBlock = DirectCast(currentNode, MultiLineIfBlockSyntax) Dim newIfBlock = ifBlock.WithElseIfBlocks(ifBlock.ElseIfBlocks.Insert(0, elseIfBlockToInsert)) Return newIfBlock End Function) ElseIf TypeOf afterIfOrElseIf Is ElseIfBlockSyntax Then editor.InsertAfter(afterIfOrElseIf, elseIfBlockToInsert) Else Throw ExceptionUtilities.UnexpectedValue(afterIfOrElseIf) End If End Sub Public Sub RemoveElseIfClause(editor As SyntaxEditor, elseIfClause As SyntaxNode) Implements IIfLikeStatementGenerator.RemoveElseIfClause editor.RemoveNode(elseIfClause) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Composition Imports Microsoft.CodeAnalysis.Editing Imports Microsoft.CodeAnalysis.Host.Mef Imports Microsoft.CodeAnalysis.SplitOrMergeIfStatements Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.SplitOrMergeIfStatements <ExportLanguageService(GetType(IIfLikeStatementGenerator), LanguageNames.VisualBasic), [Shared]> Friend NotInheritable Class VisualBasicIfLikeStatementGenerator Implements IIfLikeStatementGenerator <ImportingConstructor> <Obsolete(MefConstruction.ImportingConstructorMessage, True)> Public Sub New() End Sub Public Function IsIfOrElseIf(node As SyntaxNode) As Boolean Implements IIfLikeStatementGenerator.IsIfOrElseIf Return TypeOf node Is MultiLineIfBlockSyntax OrElse TypeOf node Is ElseIfBlockSyntax End Function Public Function IsCondition(expression As SyntaxNode, ByRef ifOrElseIf As SyntaxNode) As Boolean Implements IIfLikeStatementGenerator.IsCondition If TypeOf expression.Parent Is IfStatementSyntax AndAlso DirectCast(expression.Parent, IfStatementSyntax).Condition Is expression AndAlso TypeOf expression.Parent.Parent Is MultiLineIfBlockSyntax Then ifOrElseIf = expression.Parent.Parent Return True End If If TypeOf expression.Parent Is ElseIfStatementSyntax AndAlso DirectCast(expression.Parent, ElseIfStatementSyntax).Condition Is expression AndAlso TypeOf expression.Parent.Parent Is ElseIfBlockSyntax Then ifOrElseIf = expression.Parent.Parent Return True End If ifOrElseIf = Nothing Return False End Function Public Function IsElseIfClause(node As SyntaxNode, ByRef parentIfOrElseIf As SyntaxNode) As Boolean Implements IIfLikeStatementGenerator.IsElseIfClause If TypeOf node Is ElseIfBlockSyntax Then Dim ifBlock = DirectCast(node.Parent, MultiLineIfBlockSyntax) Dim index = ifBlock.ElseIfBlocks.IndexOf(DirectCast(node, ElseIfBlockSyntax)) parentIfOrElseIf = If(index > 0, ifBlock.ElseIfBlocks(index - 1), DirectCast(ifBlock, SyntaxNode)) Return True End If parentIfOrElseIf = Nothing Return False End Function Public Function HasElseIfClause(ifOrElseIf As SyntaxNode, ByRef elseIfClause As SyntaxNode) As Boolean Implements IIfLikeStatementGenerator.HasElseIfClause Dim ifBlock As MultiLineIfBlockSyntax Dim nextElseIfIndex As Integer If TypeOf ifOrElseIf Is MultiLineIfBlockSyntax Then ifBlock = DirectCast(ifOrElseIf, MultiLineIfBlockSyntax) nextElseIfIndex = 0 ElseIf TypeOf ifOrElseIf Is ElseIfBlockSyntax Then ifBlock = DirectCast(ifOrElseIf.Parent, MultiLineIfBlockSyntax) Dim index = ifBlock.ElseIfBlocks.IndexOf(DirectCast(ifOrElseIf, ElseIfBlockSyntax)) nextElseIfIndex = index + 1 Else Throw ExceptionUtilities.UnexpectedValue(ifOrElseIf) End If elseIfClause = ifBlock.ElseIfBlocks.ElementAtOrDefault(nextElseIfIndex) Return elseIfClause IsNot Nothing End Function Public Function GetCondition(ifOrElseIf As SyntaxNode) As SyntaxNode Implements IIfLikeStatementGenerator.GetCondition If TypeOf ifOrElseIf Is MultiLineIfBlockSyntax Then Return DirectCast(ifOrElseIf, MultiLineIfBlockSyntax).IfStatement.Condition ElseIf TypeOf ifOrElseIf Is ElseIfBlockSyntax Then Return DirectCast(ifOrElseIf, ElseIfBlockSyntax).ElseIfStatement.Condition Else Throw ExceptionUtilities.UnexpectedValue(ifOrElseIf) End If End Function Public Function GetRootIfStatement(ifOrElseIf As SyntaxNode) As SyntaxNode Implements IIfLikeStatementGenerator.GetRootIfStatement If TypeOf ifOrElseIf Is MultiLineIfBlockSyntax Then Return ifOrElseIf ElseIf TypeOf ifOrElseIf Is ElseIfBlockSyntax Then Return ifOrElseIf.Parent Else Throw ExceptionUtilities.UnexpectedValue(ifOrElseIf) End If End Function Public Function GetElseIfAndElseClauses(ifOrElseIf As SyntaxNode) As ImmutableArray(Of SyntaxNode) Implements IIfLikeStatementGenerator.GetElseIfAndElseClauses If TypeOf ifOrElseIf Is MultiLineIfBlockSyntax Then Dim ifBlock = DirectCast(ifOrElseIf, MultiLineIfBlockSyntax) Return AddIfNotNull(ifBlock.ElseIfBlocks, ifBlock.ElseBlock).ToImmutableArray() ElseIf TypeOf ifOrElseIf Is ElseIfBlockSyntax Then Dim elseIfBlock = DirectCast(ifOrElseIf, ElseIfBlockSyntax) Dim ifBlock = DirectCast(elseIfBlock.Parent, MultiLineIfBlockSyntax) Dim nextElseIfBlocks = ifBlock.ElseIfBlocks.RemoveRange(0, ifBlock.ElseIfBlocks.IndexOf(elseIfBlock) + 1) Return AddIfNotNull(nextElseIfBlocks, ifBlock.ElseBlock).ToImmutableArray() Else Throw ExceptionUtilities.UnexpectedValue(ifOrElseIf) End If End Function Private Shared Function AddIfNotNull(list As SyntaxList(Of SyntaxNode), node As SyntaxNode) As SyntaxList(Of SyntaxNode) Return If(node IsNot Nothing, list.Add(node), list) End Function Public Function WithCondition(ifOrElseIf As SyntaxNode, condition As SyntaxNode) As SyntaxNode Implements IIfLikeStatementGenerator.WithCondition If TypeOf ifOrElseIf Is MultiLineIfBlockSyntax Then Dim ifBlock = DirectCast(ifOrElseIf, MultiLineIfBlockSyntax) Return ifBlock.WithIfStatement(ifBlock.IfStatement.WithCondition(DirectCast(condition, ExpressionSyntax))) ElseIf TypeOf ifOrElseIf Is ElseIfBlockSyntax Then Dim elseIfBlock = DirectCast(ifOrElseIf, ElseIfBlockSyntax) Return elseIfBlock.WithElseIfStatement(elseIfBlock.ElseIfStatement.WithCondition(DirectCast(condition, ExpressionSyntax))) Else Throw ExceptionUtilities.UnexpectedValue(ifOrElseIf) End If End Function Public Function WithStatementInBlock(ifOrElseIf As SyntaxNode, statement As SyntaxNode) As SyntaxNode Implements IIfLikeStatementGenerator.WithStatementInBlock Return ifOrElseIf.ReplaceStatements(SyntaxFactory.SingletonList(DirectCast(statement, StatementSyntax))) End Function Public Function WithStatementsOf(ifOrElseIf As SyntaxNode, otherIfOrElseIf As SyntaxNode) As SyntaxNode Implements IIfLikeStatementGenerator.WithStatementsOf Return ifOrElseIf.ReplaceStatements(otherIfOrElseIf.GetStatements()) End Function Public Function WithElseIfAndElseClausesOf(ifStatement As SyntaxNode, otherIfStatement As SyntaxNode) As SyntaxNode Implements IIfLikeStatementGenerator.WithElseIfAndElseClausesOf Dim ifBlock = DirectCast(ifStatement, MultiLineIfBlockSyntax) Dim otherIfBlock = DirectCast(otherIfStatement, MultiLineIfBlockSyntax) Return ifBlock.WithElseIfBlocks(otherIfBlock.ElseIfBlocks).WithElseBlock(otherIfBlock.ElseBlock) End Function Public Function ToIfStatement(ifOrElseIf As SyntaxNode) As SyntaxNode Implements IIfLikeStatementGenerator.ToIfStatement If TypeOf ifOrElseIf Is MultiLineIfBlockSyntax Then Return ifOrElseIf ElseIf TypeOf ifOrElseIf Is ElseIfBlockSyntax Then Dim elseIfBlock = DirectCast(ifOrElseIf, ElseIfBlockSyntax) Dim ifBlock = DirectCast(elseIfBlock.Parent, MultiLineIfBlockSyntax) Dim nextElseIfBlocks = ifBlock.ElseIfBlocks.RemoveRange(0, ifBlock.ElseIfBlocks.IndexOf(elseIfBlock) + 1) Dim newIfStatement = SyntaxFactory.IfStatement(ifBlock.IfStatement.IfKeyword, elseIfBlock.ElseIfStatement.Condition, elseIfBlock.ElseIfStatement.ThenKeyword) Dim newIfBlock = SyntaxFactory.MultiLineIfBlock(newIfStatement, elseIfBlock.Statements, nextElseIfBlocks, ifBlock.ElseBlock, ifBlock.EndIfStatement) Return newIfBlock Else Throw ExceptionUtilities.UnexpectedValue(ifOrElseIf) End If End Function Public Function ToElseIfClause(ifOrElseIf As SyntaxNode) As SyntaxNode Implements IIfLikeStatementGenerator.ToElseIfClause If TypeOf ifOrElseIf Is MultiLineIfBlockSyntax Then Dim ifBlock = DirectCast(ifOrElseIf, MultiLineIfBlockSyntax) Dim newElseIfStatement = SyntaxFactory.ElseIfStatement(SyntaxFactory.Token(SyntaxKind.ElseIfKeyword), ifBlock.IfStatement.Condition, ifBlock.IfStatement.ThenKeyword) Dim newElseIfBlock = SyntaxFactory.ElseIfBlock(newElseIfStatement, ifBlock.Statements) Return newElseIfBlock ElseIf TypeOf ifOrElseIf Is ElseIfBlockSyntax Then Return ifOrElseIf Else Throw ExceptionUtilities.UnexpectedValue(ifOrElseIf) End If End Function Public Sub InsertElseIfClause(editor As SyntaxEditor, afterIfOrElseIf As SyntaxNode, elseIfClause As SyntaxNode) Implements IIfLikeStatementGenerator.InsertElseIfClause Dim elseIfBlockToInsert = DirectCast(elseIfClause, ElseIfBlockSyntax) If TypeOf afterIfOrElseIf Is MultiLineIfBlockSyntax Then editor.ReplaceNode(afterIfOrElseIf, Function(currentNode, g) Dim ifBlock = DirectCast(currentNode, MultiLineIfBlockSyntax) Dim newIfBlock = ifBlock.WithElseIfBlocks(ifBlock.ElseIfBlocks.Insert(0, elseIfBlockToInsert)) Return newIfBlock End Function) ElseIf TypeOf afterIfOrElseIf Is ElseIfBlockSyntax Then editor.InsertAfter(afterIfOrElseIf, elseIfBlockToInsert) Else Throw ExceptionUtilities.UnexpectedValue(afterIfOrElseIf) End If End Sub Public Sub RemoveElseIfClause(editor As SyntaxEditor, elseIfClause As SyntaxNode) Implements IIfLikeStatementGenerator.RemoveElseIfClause editor.RemoveNode(elseIfClause) End Sub End Class End Namespace
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/CSharpTest/SignatureHelp/GenericNameSignatureHelpProviderTests.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.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.SignatureHelp; using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp { public class GenericNameSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests { internal override Type GetSignatureHelpProviderType() => typeof(GenericNameSignatureHelpProvider); #region "Declaring generic type objects" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task NestedGenericTerminated() { var markup = @" class G<T> { }; class C { void Goo() { G<G<int>$$> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<T>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWith1ParameterTerminated() { var markup = @" class G<T> { }; class C { void Goo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<T>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWith2ParametersOn1() { var markup = @" class G<S, T> { }; class C { void Goo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWith2ParametersOn2() { var markup = @" class G<S, T> { }; class C { void Goo() { [|G<int, $$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", string.Empty, string.Empty, currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWith2ParametersOn1XmlDoc() { var markup = @" /// <summary> /// Summary for G /// </summary> /// <typeparam name=""S"">TypeParamS. Also see <see cref=""T""/></typeparam> /// <typeparam name=""T"">TypeParamT</typeparam> class G<S, T> { }; class C { void Goo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", "Summary for G", "TypeParamS. Also see T", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWith2ParametersOn2XmlDoc() { var markup = @" /// <summary> /// Summary for G /// </summary> /// <typeparam name=""S"">TypeParamS</typeparam> /// <typeparam name=""T"">TypeParamT. Also see <see cref=""S""/></typeparam> class G<S, T> { }; class C { void Goo() { [|G<int, $$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", "Summary for G", "TypeParamT. Also see S", currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } #endregion #region "Constraints on generic types" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsStruct() { var markup = @" class G<S> where S : struct { }; class C { void Goo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S> where S : struct", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsClass() { var markup = @" class G<S> where S : class { }; class C { void Goo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S> where S : class", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsNew() { var markup = @" class G<S> where S : new() { }; class C { void Goo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S> where S : new()", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsBase() { var markup = @" class Base { } class G<S> where S : Base { }; class C { void Goo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S> where S : Base", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsBaseGenericWithGeneric() { var markup = @" class Base<T> { } class G<S> where S : Base<S> { }; class C { void Goo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S> where S : Base<S>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsBaseGenericWithNonGeneric() { var markup = @" class Base<T> { } class G<S> where S : Base<int> { }; class C { void Goo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S> where S : Base<int>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsBaseGenericNested() { var markup = @" class Base<T> { } class G<S> where S : Base<Base<int>> { }; class C { void Goo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S> where S : Base<Base<int>>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsDeriveFromAnotherGenericParameter() { var markup = @" class G<S, T> where S : T { }; class C { void Goo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T> where S : T", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsMixed1() { var markup = @" /// <summary> /// Summary1 /// </summary> /// <typeparam name=""S"">SummaryS</typeparam> /// <typeparam name=""T"">SummaryT</typeparam> class G<S, T> where S : Base, new() where T : class, S, IGoo, new() { }; internal interface IGoo { } internal class Base { } class C { void Goo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T> where S : Base, new()", "Summary1", "SummaryS", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsMixed2() { var markup = @" /// <summary> /// Summary1 /// </summary> /// <typeparam name=""S"">SummaryS</typeparam> /// <typeparam name=""T"">SummaryT</typeparam> class G<S, T> where S : Base, new() where T : class, S, IGoo, new() { }; internal interface IGoo { } internal class Base { } class C { void Goo() { [|G<bar, $$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T> where T : class, S, IGoo, new()", "Summary1", "SummaryT", currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } #endregion #region "Generic member invocation" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWith1ParameterTerminated() { var markup = @" class C { void Goo<T>() { } void Bar() { [|Goo<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Goo<T>()", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(544091, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544091")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWith2ParametersOn1() { var markup = @" class C { /// <summary> /// Method summary /// </summary> /// <typeparam name=""S"" > type param S. see <see cref=""T""/> </typeparam> /// <typeparam name=""T"">type param T. </typeparam> /// <param name=""s"">parameter s</param> /// <param name=""t"">parameter t</param> void Goo<S, T>(S s, T t) { } void Bar() { [|Goo<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Goo<S, T>(S s, T t)", "Method summary", "type param S. see T", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(544091, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544091")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWith2ParametersOn2() { var markup = @" class C { void Goo<S, T>(S s, T t) { } void Bar() { [|Goo<int, $$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Goo<S, T>(S s, T t)", string.Empty, string.Empty, currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(544091, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544091")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWith2ParametersOn1XmlDoc() { var markup = @" class C { /// <summary> /// SummaryForGoo /// </summary> /// <typeparam name=""S"">SummaryForS</typeparam> /// <typeparam name=""T"">SummaryForT</typeparam> void Goo<S, T>(S s, T t) { } void Bar() { [|Goo<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Goo<S, T>(S s, T t)", "SummaryForGoo", "SummaryForS", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(544091, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544091")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWith2ParametersOn2XmlDoc() { var markup = @" class C { /// <summary> /// SummaryForGoo /// </summary> /// <typeparam name=""S"">SummaryForS</typeparam> /// <typeparam name=""T"">SummaryForT</typeparam> void Goo<S, T>(S s, T t) { } void Bar() { [|Goo<int, $$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Goo<S, T>(S s, T t)", "SummaryForGoo", "SummaryForT", currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task CallingGenericExtensionMethod() { var markup = @" class G { }; class C { void Bar() { G g = null; g.[|Goo<$$|]> } } static class GooClass { public static void Goo<T>(this G g) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem($"({CSharpFeaturesResources.extension}) void G.Goo<T>()", string.Empty, string.Empty, currentParameterIndex: 0)); // TODO: Enable the script case when we have support for extension methods in scripts await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false, sourceCodeKind: Microsoft.CodeAnalysis.SourceCodeKind.Regular); } #endregion #region "Constraints on generic methods" [WorkItem(544091, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544091")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWithConstraintsMixed1() { var markup = @" class Base { } interface IGoo { } class C { /// <summary> /// GooSummary /// </summary> /// <typeparam name=""S"">ParamS</typeparam> /// <typeparam name=""T"">ParamT</typeparam> S Goo<S, T>(S s, T t) where S : Base, new() where T : class, S, IGoo, new() { return null; } void Bar() { [|Goo<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("S C.Goo<S, T>(S s, T t) where S : Base, new()", "GooSummary", "ParamS", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(544091, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544091")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWithConstraintsMixed2() { var markup = @" class Base { } interface IGoo { } class C { /// <summary> /// GooSummary /// </summary> /// <typeparam name=""S"">ParamS</typeparam> /// <typeparam name=""T"">ParamT</typeparam> S Goo<S, T>(S s, T t) where S : Base, new() where T : class, S, IGoo, new() { return null; } void Bar() { [|Goo<Base, $$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("S C.Goo<S, T>(S s, T t) where T : class, S, IGoo, new()", "GooSummary", "ParamT", currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestUnmanagedConstraint() { var markup = @" class C { /// <summary> /// summary headline /// </summary> /// <typeparam name=""T"">T documentation</typeparam> void M<T>(T arg) where T : unmanaged { } void Bar() { [|M<$$|]> } }"; await TestAsync(markup, new List<SignatureHelpTestItem> { new SignatureHelpTestItem("void C.M<T>(T arg) where T : unmanaged", "summary headline", "T documentation", currentParameterIndex: 0) }); } #endregion #region "Trigger tests" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestTriggerCharacters() { char[] expectedCharacters = { ',', '<' }; char[] unexpectedCharacters = { ' ', '[', '(' }; VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task FieldUnavailableInOneLinkedFile() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if GOO class D<T> { } #endif void goo() { var x = new D<$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"D<T>\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", currentParameterIndex: 0); await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task ExcludeFilesWithInactiveRegions() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO,BAR""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if GOO class D<T> { } #endif #if BAR void goo() { var x = new D<$$ } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" /> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"D<T>\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", currentParameterIndex: 0); await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false); } #endregion #region "EditorBrowsable tests" [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_GenericType_BrowsableAlways() { var markup = @" class Program { void M() { var c = new C<$$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public class C<T> { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C<T>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_GenericType_BrowsableNever() { var markup = @" class Program { void M() { var c = new C<$$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class C<T> { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C<T>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_GenericType_BrowsableAdvanced() { var markup = @" class Program { void M() { var c = new C<$$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public class C<T> { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C<T>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } #endregion [WorkItem(1083601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1083601")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithBadTypeArgumentList() { var markup = @" class G<T> { }; class C { void Goo() { G{$$> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); await TestAsync(markup, expectedOrderedItems); } [WorkItem(50114, "https://github.com/dotnet/roslyn/issues/50114")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithDocCommentList() { var markup = @" /// <summary> /// List: /// <list> /// <item> /// <description> /// Item 1. /// </description> /// </item> /// </list> /// </summary> class G<S, T> { }; class C { void Goo() { [|G<int, $$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", "List:\r\n\r\nItem 1.", classificationTypeNames: ImmutableArray.Create( ClassificationTypeNames.Text, ClassificationTypeNames.WhiteSpace, ClassificationTypeNames.WhiteSpace, ClassificationTypeNames.WhiteSpace, ClassificationTypeNames.Text, ClassificationTypeNames.WhiteSpace))); await TestAsync(markup, expectedOrderedItems); } } }
// Licensed to the .NET Foundation under one or more 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.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.SignatureHelp; using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp { public class GenericNameSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests { internal override Type GetSignatureHelpProviderType() => typeof(GenericNameSignatureHelpProvider); #region "Declaring generic type objects" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task NestedGenericTerminated() { var markup = @" class G<T> { }; class C { void Goo() { G<G<int>$$> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<T>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWith1ParameterTerminated() { var markup = @" class G<T> { }; class C { void Goo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<T>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWith2ParametersOn1() { var markup = @" class G<S, T> { }; class C { void Goo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWith2ParametersOn2() { var markup = @" class G<S, T> { }; class C { void Goo() { [|G<int, $$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", string.Empty, string.Empty, currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWith2ParametersOn1XmlDoc() { var markup = @" /// <summary> /// Summary for G /// </summary> /// <typeparam name=""S"">TypeParamS. Also see <see cref=""T""/></typeparam> /// <typeparam name=""T"">TypeParamT</typeparam> class G<S, T> { }; class C { void Goo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", "Summary for G", "TypeParamS. Also see T", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWith2ParametersOn2XmlDoc() { var markup = @" /// <summary> /// Summary for G /// </summary> /// <typeparam name=""S"">TypeParamS</typeparam> /// <typeparam name=""T"">TypeParamT. Also see <see cref=""S""/></typeparam> class G<S, T> { }; class C { void Goo() { [|G<int, $$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", "Summary for G", "TypeParamT. Also see S", currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } #endregion #region "Constraints on generic types" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsStruct() { var markup = @" class G<S> where S : struct { }; class C { void Goo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S> where S : struct", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsClass() { var markup = @" class G<S> where S : class { }; class C { void Goo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S> where S : class", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsNew() { var markup = @" class G<S> where S : new() { }; class C { void Goo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S> where S : new()", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsBase() { var markup = @" class Base { } class G<S> where S : Base { }; class C { void Goo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S> where S : Base", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsBaseGenericWithGeneric() { var markup = @" class Base<T> { } class G<S> where S : Base<S> { }; class C { void Goo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S> where S : Base<S>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsBaseGenericWithNonGeneric() { var markup = @" class Base<T> { } class G<S> where S : Base<int> { }; class C { void Goo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S> where S : Base<int>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsBaseGenericNested() { var markup = @" class Base<T> { } class G<S> where S : Base<Base<int>> { }; class C { void Goo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S> where S : Base<Base<int>>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsDeriveFromAnotherGenericParameter() { var markup = @" class G<S, T> where S : T { }; class C { void Goo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T> where S : T", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsMixed1() { var markup = @" /// <summary> /// Summary1 /// </summary> /// <typeparam name=""S"">SummaryS</typeparam> /// <typeparam name=""T"">SummaryT</typeparam> class G<S, T> where S : Base, new() where T : class, S, IGoo, new() { }; internal interface IGoo { } internal class Base { } class C { void Goo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T> where S : Base, new()", "Summary1", "SummaryS", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsMixed2() { var markup = @" /// <summary> /// Summary1 /// </summary> /// <typeparam name=""S"">SummaryS</typeparam> /// <typeparam name=""T"">SummaryT</typeparam> class G<S, T> where S : Base, new() where T : class, S, IGoo, new() { }; internal interface IGoo { } internal class Base { } class C { void Goo() { [|G<bar, $$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T> where T : class, S, IGoo, new()", "Summary1", "SummaryT", currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } #endregion #region "Generic member invocation" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWith1ParameterTerminated() { var markup = @" class C { void Goo<T>() { } void Bar() { [|Goo<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Goo<T>()", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(544091, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544091")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWith2ParametersOn1() { var markup = @" class C { /// <summary> /// Method summary /// </summary> /// <typeparam name=""S"" > type param S. see <see cref=""T""/> </typeparam> /// <typeparam name=""T"">type param T. </typeparam> /// <param name=""s"">parameter s</param> /// <param name=""t"">parameter t</param> void Goo<S, T>(S s, T t) { } void Bar() { [|Goo<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Goo<S, T>(S s, T t)", "Method summary", "type param S. see T", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(544091, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544091")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWith2ParametersOn2() { var markup = @" class C { void Goo<S, T>(S s, T t) { } void Bar() { [|Goo<int, $$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Goo<S, T>(S s, T t)", string.Empty, string.Empty, currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(544091, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544091")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWith2ParametersOn1XmlDoc() { var markup = @" class C { /// <summary> /// SummaryForGoo /// </summary> /// <typeparam name=""S"">SummaryForS</typeparam> /// <typeparam name=""T"">SummaryForT</typeparam> void Goo<S, T>(S s, T t) { } void Bar() { [|Goo<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Goo<S, T>(S s, T t)", "SummaryForGoo", "SummaryForS", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(544091, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544091")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWith2ParametersOn2XmlDoc() { var markup = @" class C { /// <summary> /// SummaryForGoo /// </summary> /// <typeparam name=""S"">SummaryForS</typeparam> /// <typeparam name=""T"">SummaryForT</typeparam> void Goo<S, T>(S s, T t) { } void Bar() { [|Goo<int, $$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Goo<S, T>(S s, T t)", "SummaryForGoo", "SummaryForT", currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task CallingGenericExtensionMethod() { var markup = @" class G { }; class C { void Bar() { G g = null; g.[|Goo<$$|]> } } static class GooClass { public static void Goo<T>(this G g) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem($"({CSharpFeaturesResources.extension}) void G.Goo<T>()", string.Empty, string.Empty, currentParameterIndex: 0)); // TODO: Enable the script case when we have support for extension methods in scripts await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false, sourceCodeKind: Microsoft.CodeAnalysis.SourceCodeKind.Regular); } #endregion #region "Constraints on generic methods" [WorkItem(544091, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544091")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWithConstraintsMixed1() { var markup = @" class Base { } interface IGoo { } class C { /// <summary> /// GooSummary /// </summary> /// <typeparam name=""S"">ParamS</typeparam> /// <typeparam name=""T"">ParamT</typeparam> S Goo<S, T>(S s, T t) where S : Base, new() where T : class, S, IGoo, new() { return null; } void Bar() { [|Goo<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("S C.Goo<S, T>(S s, T t) where S : Base, new()", "GooSummary", "ParamS", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(544091, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544091")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWithConstraintsMixed2() { var markup = @" class Base { } interface IGoo { } class C { /// <summary> /// GooSummary /// </summary> /// <typeparam name=""S"">ParamS</typeparam> /// <typeparam name=""T"">ParamT</typeparam> S Goo<S, T>(S s, T t) where S : Base, new() where T : class, S, IGoo, new() { return null; } void Bar() { [|Goo<Base, $$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("S C.Goo<S, T>(S s, T t) where T : class, S, IGoo, new()", "GooSummary", "ParamT", currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task TestUnmanagedConstraint() { var markup = @" class C { /// <summary> /// summary headline /// </summary> /// <typeparam name=""T"">T documentation</typeparam> void M<T>(T arg) where T : unmanaged { } void Bar() { [|M<$$|]> } }"; await TestAsync(markup, new List<SignatureHelpTestItem> { new SignatureHelpTestItem("void C.M<T>(T arg) where T : unmanaged", "summary headline", "T documentation", currentParameterIndex: 0) }); } #endregion #region "Trigger tests" [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestTriggerCharacters() { char[] expectedCharacters = { ',', '<' }; char[] unexpectedCharacters = { ' ', '[', '(' }; VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task FieldUnavailableInOneLinkedFile() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if GOO class D<T> { } #endif void goo() { var x = new D<$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"D<T>\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", currentParameterIndex: 0); await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false); } [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task ExcludeFilesWithInactiveRegions() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO,BAR""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if GOO class D<T> { } #endif #if BAR void goo() { var x = new D<$$ } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" /> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"D<T>\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", currentParameterIndex: 0); await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false); } #endregion #region "EditorBrowsable tests" [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_GenericType_BrowsableAlways() { var markup = @" class Program { void M() { var c = new C<$$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public class C<T> { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C<T>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_GenericType_BrowsableNever() { var markup = @" class Program { void M() { var c = new C<$$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class C<T> { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C<T>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_GenericType_BrowsableAdvanced() { var markup = @" class Program { void M() { var c = new C<$$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public class C<T> { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C<T>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } #endregion [WorkItem(1083601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1083601")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithBadTypeArgumentList() { var markup = @" class G<T> { }; class C { void Goo() { G{$$> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); await TestAsync(markup, expectedOrderedItems); } [WorkItem(50114, "https://github.com/dotnet/roslyn/issues/50114")] [Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithDocCommentList() { var markup = @" /// <summary> /// List: /// <list> /// <item> /// <description> /// Item 1. /// </description> /// </item> /// </list> /// </summary> class G<S, T> { }; class C { void Goo() { [|G<int, $$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", "List:\r\n\r\nItem 1.", classificationTypeNames: ImmutableArray.Create( ClassificationTypeNames.Text, ClassificationTypeNames.WhiteSpace, ClassificationTypeNames.WhiteSpace, ClassificationTypeNames.WhiteSpace, ClassificationTypeNames.Text, ClassificationTypeNames.WhiteSpace))); await TestAsync(markup, expectedOrderedItems); } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/VisualBasicTest/Structure/NamespaceDeclarationStructureTests.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 Public Class NamespaceDeclarationStructureProviderTests Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of NamespaceStatementSyntax) Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider Return New NamespaceDeclarationStructureProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestNamespace() As Task Const code = " {|span:$$Namespace N1 End Namespace|} " Await VerifyBlockSpansAsync(code, Region("span", "Namespace N1 ...", autoCollapse:=False)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestNamespaceWithComments() As Task Const code = " {|span1:'My 'Namespace|} {|span2:$$Namespace N1 End Namespace|} " Await VerifyBlockSpansAsync(code, Region("span1", "' My ...", autoCollapse:=True), Region("span2", "Namespace N1 ...", autoCollapse:=False)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestNamespaceWithNestedComments() As Task Const code = " {|span1:$$Namespace N1 {|span2:'My 'Namespace|} End Namespace|} " Await VerifyBlockSpansAsync(code, Region("span1", "Namespace N1 ...", autoCollapse:=False), Region("span2", "' My ...", 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 Public Class NamespaceDeclarationStructureProviderTests Inherits AbstractVisualBasicSyntaxNodeStructureProviderTests(Of NamespaceStatementSyntax) Friend Overrides Function CreateProvider() As AbstractSyntaxStructureProvider Return New NamespaceDeclarationStructureProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestNamespace() As Task Const code = " {|span:$$Namespace N1 End Namespace|} " Await VerifyBlockSpansAsync(code, Region("span", "Namespace N1 ...", autoCollapse:=False)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestNamespaceWithComments() As Task Const code = " {|span1:'My 'Namespace|} {|span2:$$Namespace N1 End Namespace|} " Await VerifyBlockSpansAsync(code, Region("span1", "' My ...", autoCollapse:=True), Region("span2", "Namespace N1 ...", autoCollapse:=False)) End Function <Fact, Trait(Traits.Feature, Traits.Features.Outlining)> Public Async Function TestNamespaceWithNestedComments() As Task Const code = " {|span1:$$Namespace N1 {|span2:'My 'Namespace|} End Namespace|} " Await VerifyBlockSpansAsync(code, Region("span1", "Namespace N1 ...", autoCollapse:=False), Region("span2", "' My ...", autoCollapse:=True)) End Function End Class End Namespace
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/Test/Utilities/VisualBasic/LocalVariableDeclaratorsCollector.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.PooledObjects Friend NotInheritable Class LocalVariableDeclaratorsCollector Inherits VisualBasicSyntaxWalker Private ReadOnly _builder As ArrayBuilder(Of SyntaxNode) Public Sub New(builder As ArrayBuilder(Of SyntaxNode)) Me._builder = builder End Sub Friend Shared Function GetDeclarators(method As SourceMethodSymbol) As ImmutableArray(Of SyntaxNode) Dim builder = ArrayBuilder(Of SyntaxNode).GetInstance() Dim visitor = New LocalVariableDeclaratorsCollector(builder) visitor.Visit(method.BlockSyntax) Return builder.ToImmutableAndFree() End Function Public Overrides Sub VisitForEachStatement(node As ForEachStatementSyntax) Me._builder.Add(node) MyBase.VisitForEachStatement(node) End Sub Public Overrides Sub VisitForStatement(node As ForStatementSyntax) Me._builder.Add(node) MyBase.VisitForStatement(node) End Sub Public Overrides Sub VisitSyncLockStatement(node As SyncLockStatementSyntax) Me._builder.Add(node) MyBase.VisitSyncLockStatement(node) End Sub Public Overrides Sub VisitWithStatement(node As WithStatementSyntax) Me._builder.Add(node) MyBase.VisitWithStatement(node) End Sub Public Overrides Sub VisitUsingStatement(node As UsingStatementSyntax) Me._builder.Add(node) MyBase.VisitUsingStatement(node) End Sub Public Overrides Sub VisitVariableDeclarator(node As VariableDeclaratorSyntax) For Each name In node.Names Me._builder.Add(name) Next MyBase.VisitVariableDeclarator(node) End Sub Public Overrides Sub VisitIdentifierName(node As IdentifierNameSyntax) End Sub Public Overrides Sub VisitGoToStatement(node As GoToStatementSyntax) ' goto syntax does not declare locals Return End Sub Public Overrides Sub VisitLabelStatement(node As LabelStatementSyntax) ' labels do not declare locals Return End Sub Public Overrides Sub VisitLabel(node As LabelSyntax) ' labels do not declare locals Return End Sub Public Overrides Sub VisitGetXmlNamespaceExpression(node As GetXmlNamespaceExpressionSyntax) ' GetXmlNamespace does not declare locals Return End Sub Public Overrides Sub VisitMemberAccessExpression(node As MemberAccessExpressionSyntax) MyBase.Visit(node.Expression) ' right side of the . does not declare locals Return End Sub Public Overrides Sub VisitQualifiedName(node As QualifiedNameSyntax) MyBase.Visit(node.Left) ' right side of the . does not declare locals Return End Sub Public Overrides Sub VisitSimpleArgument(node As SimpleArgumentSyntax) MyBase.Visit(node.Expression) ' argument name in "goo(argName := expr)" does not declare locals Return End Sub End Class
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.PooledObjects Friend NotInheritable Class LocalVariableDeclaratorsCollector Inherits VisualBasicSyntaxWalker Private ReadOnly _builder As ArrayBuilder(Of SyntaxNode) Public Sub New(builder As ArrayBuilder(Of SyntaxNode)) Me._builder = builder End Sub Friend Shared Function GetDeclarators(method As SourceMethodSymbol) As ImmutableArray(Of SyntaxNode) Dim builder = ArrayBuilder(Of SyntaxNode).GetInstance() Dim visitor = New LocalVariableDeclaratorsCollector(builder) visitor.Visit(method.BlockSyntax) Return builder.ToImmutableAndFree() End Function Public Overrides Sub VisitForEachStatement(node As ForEachStatementSyntax) Me._builder.Add(node) MyBase.VisitForEachStatement(node) End Sub Public Overrides Sub VisitForStatement(node As ForStatementSyntax) Me._builder.Add(node) MyBase.VisitForStatement(node) End Sub Public Overrides Sub VisitSyncLockStatement(node As SyncLockStatementSyntax) Me._builder.Add(node) MyBase.VisitSyncLockStatement(node) End Sub Public Overrides Sub VisitWithStatement(node As WithStatementSyntax) Me._builder.Add(node) MyBase.VisitWithStatement(node) End Sub Public Overrides Sub VisitUsingStatement(node As UsingStatementSyntax) Me._builder.Add(node) MyBase.VisitUsingStatement(node) End Sub Public Overrides Sub VisitVariableDeclarator(node As VariableDeclaratorSyntax) For Each name In node.Names Me._builder.Add(name) Next MyBase.VisitVariableDeclarator(node) End Sub Public Overrides Sub VisitIdentifierName(node As IdentifierNameSyntax) End Sub Public Overrides Sub VisitGoToStatement(node As GoToStatementSyntax) ' goto syntax does not declare locals Return End Sub Public Overrides Sub VisitLabelStatement(node As LabelStatementSyntax) ' labels do not declare locals Return End Sub Public Overrides Sub VisitLabel(node As LabelSyntax) ' labels do not declare locals Return End Sub Public Overrides Sub VisitGetXmlNamespaceExpression(node As GetXmlNamespaceExpressionSyntax) ' GetXmlNamespace does not declare locals Return End Sub Public Overrides Sub VisitMemberAccessExpression(node As MemberAccessExpressionSyntax) MyBase.Visit(node.Expression) ' right side of the . does not declare locals Return End Sub Public Overrides Sub VisitQualifiedName(node As QualifiedNameSyntax) MyBase.Visit(node.Left) ' right side of the . does not declare locals Return End Sub Public Overrides Sub VisitSimpleArgument(node As SimpleArgumentSyntax) MyBase.Visit(node.Expression) ' argument name in "goo(argName := expr)" does not declare locals Return End Sub End Class
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/Core/MSBuildTask/CopyRefAssembly.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; namespace Microsoft.CodeAnalysis.BuildTasks { /// <summary> /// By default, this task copies the source over to the destination. /// But if we're able to check that they are identical, the destination is left untouched. /// </summary> public sealed class CopyRefAssembly : Task { [Required] public string SourcePath { get; set; } [Output] [Required] public string DestinationPath { get; set; } public CopyRefAssembly() { TaskResources = ErrorString.ResourceManager; // These required properties will all be assigned by MSBuild. Suppress warnings about leaving them with // their default values. SourcePath = null!; DestinationPath = null!; } public override bool Execute() { if (!File.Exists(SourcePath)) { Log.LogErrorWithCodeFromResources("General_ExpectedFileMissing", SourcePath); return false; } if (File.Exists(DestinationPath)) { var source = Guid.Empty; try { source = ExtractMvid(SourcePath); } catch (Exception e) { Log.LogMessageFromResources(MessageImportance.High, "CopyRefAssembly_BadSource3", SourcePath, e.Message, e.StackTrace); } if (source.Equals(Guid.Empty)) { Log.LogMessageFromResources(MessageImportance.High, "CopyRefAssembly_SourceNotRef1", SourcePath); } else { try { Guid destination = ExtractMvid(DestinationPath); if (!source.Equals(Guid.Empty) && source.Equals(destination)) { Log.LogMessageFromResources(MessageImportance.Low, "CopyRefAssembly_SkippingCopy1", DestinationPath); return true; } } catch (Exception) { Log.LogMessageFromResources(MessageImportance.High, "CopyRefAssembly_BadDestination1", DestinationPath); } } } return Copy(); } private bool Copy() { try { File.Copy(SourcePath, DestinationPath, overwrite: true); } catch (Exception e) { var util = new TaskLoggingHelper(this); util.LogErrorWithCodeFromResources("Compiler_UnexpectedException"); util.LogErrorFromException(e, showStackTrace: true, showDetail: true, file: null); return false; } return true; } private Guid ExtractMvid(string path) { using (FileStream source = File.OpenRead(path)) { return MvidReader.ReadAssemblyMvidOrEmpty(source); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; namespace Microsoft.CodeAnalysis.BuildTasks { /// <summary> /// By default, this task copies the source over to the destination. /// But if we're able to check that they are identical, the destination is left untouched. /// </summary> public sealed class CopyRefAssembly : Task { [Required] public string SourcePath { get; set; } [Output] [Required] public string DestinationPath { get; set; } public CopyRefAssembly() { TaskResources = ErrorString.ResourceManager; // These required properties will all be assigned by MSBuild. Suppress warnings about leaving them with // their default values. SourcePath = null!; DestinationPath = null!; } public override bool Execute() { if (!File.Exists(SourcePath)) { Log.LogErrorWithCodeFromResources("General_ExpectedFileMissing", SourcePath); return false; } if (File.Exists(DestinationPath)) { var source = Guid.Empty; try { source = ExtractMvid(SourcePath); } catch (Exception e) { Log.LogMessageFromResources(MessageImportance.High, "CopyRefAssembly_BadSource3", SourcePath, e.Message, e.StackTrace); } if (source.Equals(Guid.Empty)) { Log.LogMessageFromResources(MessageImportance.High, "CopyRefAssembly_SourceNotRef1", SourcePath); } else { try { Guid destination = ExtractMvid(DestinationPath); if (!source.Equals(Guid.Empty) && source.Equals(destination)) { Log.LogMessageFromResources(MessageImportance.Low, "CopyRefAssembly_SkippingCopy1", DestinationPath); return true; } } catch (Exception) { Log.LogMessageFromResources(MessageImportance.High, "CopyRefAssembly_BadDestination1", DestinationPath); } } } return Copy(); } private bool Copy() { try { File.Copy(SourcePath, DestinationPath, overwrite: true); } catch (Exception e) { var util = new TaskLoggingHelper(this); util.LogErrorWithCodeFromResources("Compiler_UnexpectedException"); util.LogErrorFromException(e, showStackTrace: true, showDetail: true, file: null); return false; } return true; } private Guid ExtractMvid(string path) { using (FileStream source = File.OpenRead(path)) { return MvidReader.ReadAssemblyMvidOrEmpty(source); } } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/Core/Portable/SymbolDisplay/ObjectDisplayExtensions.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 { internal static class ObjectDisplayExtensions { /// <summary> /// Determines if a flag is set on the <see cref="ObjectDisplayOptions"/> enum. /// </summary> /// <param name="options">The value to check.</param> /// <param name="flag">An enum field that specifies the flag.</param> /// <returns>Whether the <paramref name="flag"/> is set on the <paramref name="options"/>.</returns> internal static bool IncludesOption(this ObjectDisplayOptions options, ObjectDisplayOptions flag) { return (options & 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 namespace Microsoft.CodeAnalysis { internal static class ObjectDisplayExtensions { /// <summary> /// Determines if a flag is set on the <see cref="ObjectDisplayOptions"/> enum. /// </summary> /// <param name="options">The value to check.</param> /// <param name="flag">An enum field that specifies the flag.</param> /// <returns>Whether the <paramref name="flag"/> is set on the <paramref name="options"/>.</returns> internal static bool IncludesOption(this ObjectDisplayOptions options, ObjectDisplayOptions flag) { return (options & flag) == flag; } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/VisualBasic/Test/Semantic/Microsoft.CodeAnalysis.VisualBasic.Semantic.UnitTests.vbproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <TargetFrameworks>net5.0;net472</TargetFrameworks> <RootNamespace></RootNamespace> <!-- Disable running the tests on .NET Core while we investigate the core dump issue https://github.com/dotnet/roslyn/issues/29660 --> <SkipTests Condition="'$(TargetFrameworkIdentifier)' == '.NETCoreApp' and '$(OS)' != 'Windows_NT'">true</SkipTests> <!-- Skipped because we appear to be missing things necessary to compile vb.net. See https://github.com/mono/mono/issues/10679 --> <SkipTests Condition="'$(TestRuntime)' == 'Mono'">true</SkipTests> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" /> <ProjectReference Include="..\..\..\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\..\..\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\..\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" /> <ProjectReference Include="..\..\..\Test\Utilities\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Test.Utilities.vbproj" /> <ProjectReference Include="..\..\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="System.Drawing.Common" Version="$(SystemDrawingCommonVersion)" Condition="$(TargetFramework) == 'net5.0'" /> </ItemGroup> <ItemGroup> <Folder Include="My Project\" /> </ItemGroup> <ItemGroup> <Import Include="IdentifierComparison = Microsoft.CodeAnalysis.CaseInsensitiveComparison" /> <Import Include="Roslyn.Utilities" /> <Import Include="Xunit" /> </ItemGroup> <ItemGroup> <Content Include="Semantics\Async_Overload_Change_3.vb.txt" /> <Content Include="Semantics\BinaryOperatorsTestBaseline1.txt" /> <Content Include="Semantics\BinaryOperatorsTestBaseline2.txt" /> <Content Include="Semantics\BinaryOperatorsTestBaseline3.txt" /> <Content Include="Semantics\BinaryOperatorsTestBaseline4.txt" /> <Content Include="Semantics\BinaryOperatorsTestBaseline5.txt" /> <Compile Remove="Binding\T_68086.vb" /> <EmbeddedResource Include="Semantics\Async_Overload_Change_3.vb.txt" /> <EmbeddedResource Include="Semantics\BinaryOperatorsTestBaseline1.txt" /> <EmbeddedResource Include="Semantics\BinaryOperatorsTestBaseline2.txt" /> <EmbeddedResource Include="Semantics\BinaryOperatorsTestBaseline3.txt" /> <EmbeddedResource Include="Semantics\BinaryOperatorsTestBaseline4.txt" /> <EmbeddedResource Include="Semantics\BinaryOperatorsTestBaseline5.txt" /> <EmbeddedResource Include="Semantics\BinaryOperatorsTestSource1.vb" /> <EmbeddedResource Include="Semantics\BinaryOperatorsTestSource2.vb" /> <EmbeddedResource Include="Semantics\BinaryOperatorsTestSource3.vb" /> <EmbeddedResource Include="Semantics\BinaryOperatorsTestSource4.vb" /> <EmbeddedResource Include="Semantics\BinaryOperatorsTestSource5.vb" /> <EmbeddedResource Include="Semantics\LongTypeNameNative.vb.txt" /> <EmbeddedResource Include="Semantics\LongTypeName.vb.txt" /> <EmbeddedResource Include="Semantics\OverloadResolutionTestSource.vb" /> <EmbeddedResource Include="Semantics\PrintResultTestSource.vb" /> <EmbeddedResource Include="Binding\T_1247520.cs" /> <EmbeddedResource Include="Binding\T_68086.vb" /> </ItemGroup> <ItemGroup> <Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" /> </ItemGroup> <ItemGroup> <Content Include="Semantics\BinaryOperatorsTestSource1.vb" /> <Content Include="Semantics\BinaryOperatorsTestSource2.vb" /> <Content Include="Semantics\BinaryOperatorsTestSource3.vb" /> <Content Include="Semantics\BinaryOperatorsTestSource4.vb" /> <Content Include="Semantics\BinaryOperatorsTestSource5.vb" /> <Content Include="Semantics\OverloadResolutionTestSource.vb" /> <Content Include="Semantics\PrintResultTestSource.vb" /> <Compile Remove="Semantics\BinaryOperatorsTestSource1.vb" /> <Compile Remove="Semantics\BinaryOperatorsTestSource2.vb" /> <Compile Remove="Semantics\BinaryOperatorsTestSource3.vb" /> <Compile Remove="Semantics\BinaryOperatorsTestSource4.vb" /> <Compile Remove="Semantics\BinaryOperatorsTestSource5.vb" /> <Compile Remove="Semantics\OverloadResolutionTestSource.vb" /> <Compile Remove="Semantics\PrintResultTestSource.vb" /> </ItemGroup> <Import Project="$(RepositoryEngineeringDir)targets\ILAsm.targets" /> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Library</OutputType> <TargetFrameworks>net5.0;net472</TargetFrameworks> <RootNamespace></RootNamespace> <!-- Disable running the tests on .NET Core while we investigate the core dump issue https://github.com/dotnet/roslyn/issues/29660 --> <SkipTests Condition="'$(TargetFrameworkIdentifier)' == '.NETCoreApp' and '$(OS)' != 'Windows_NT'">true</SkipTests> <!-- Skipped because we appear to be missing things necessary to compile vb.net. See https://github.com/mono/mono/issues/10679 --> <SkipTests Condition="'$(TestRuntime)' == 'Mono'">true</SkipTests> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\..\..\Test\PdbUtilities\Roslyn.Test.PdbUtilities.csproj" /> <ProjectReference Include="..\..\..\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\..\..\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\..\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" /> <ProjectReference Include="..\..\..\Test\Utilities\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.Test.Utilities.vbproj" /> <ProjectReference Include="..\..\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> </ItemGroup> <ItemGroup> <PackageReference Include="System.Drawing.Common" Version="$(SystemDrawingCommonVersion)" Condition="$(TargetFramework) == 'net5.0'" /> </ItemGroup> <ItemGroup> <Folder Include="My Project\" /> </ItemGroup> <ItemGroup> <Import Include="IdentifierComparison = Microsoft.CodeAnalysis.CaseInsensitiveComparison" /> <Import Include="Roslyn.Utilities" /> <Import Include="Xunit" /> </ItemGroup> <ItemGroup> <Content Include="Semantics\Async_Overload_Change_3.vb.txt" /> <Content Include="Semantics\BinaryOperatorsTestBaseline1.txt" /> <Content Include="Semantics\BinaryOperatorsTestBaseline2.txt" /> <Content Include="Semantics\BinaryOperatorsTestBaseline3.txt" /> <Content Include="Semantics\BinaryOperatorsTestBaseline4.txt" /> <Content Include="Semantics\BinaryOperatorsTestBaseline5.txt" /> <Compile Remove="Binding\T_68086.vb" /> <EmbeddedResource Include="Semantics\Async_Overload_Change_3.vb.txt" /> <EmbeddedResource Include="Semantics\BinaryOperatorsTestBaseline1.txt" /> <EmbeddedResource Include="Semantics\BinaryOperatorsTestBaseline2.txt" /> <EmbeddedResource Include="Semantics\BinaryOperatorsTestBaseline3.txt" /> <EmbeddedResource Include="Semantics\BinaryOperatorsTestBaseline4.txt" /> <EmbeddedResource Include="Semantics\BinaryOperatorsTestBaseline5.txt" /> <EmbeddedResource Include="Semantics\BinaryOperatorsTestSource1.vb" /> <EmbeddedResource Include="Semantics\BinaryOperatorsTestSource2.vb" /> <EmbeddedResource Include="Semantics\BinaryOperatorsTestSource3.vb" /> <EmbeddedResource Include="Semantics\BinaryOperatorsTestSource4.vb" /> <EmbeddedResource Include="Semantics\BinaryOperatorsTestSource5.vb" /> <EmbeddedResource Include="Semantics\LongTypeNameNative.vb.txt" /> <EmbeddedResource Include="Semantics\LongTypeName.vb.txt" /> <EmbeddedResource Include="Semantics\OverloadResolutionTestSource.vb" /> <EmbeddedResource Include="Semantics\PrintResultTestSource.vb" /> <EmbeddedResource Include="Binding\T_1247520.cs" /> <EmbeddedResource Include="Binding\T_68086.vb" /> </ItemGroup> <ItemGroup> <Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" /> </ItemGroup> <ItemGroup> <Content Include="Semantics\BinaryOperatorsTestSource1.vb" /> <Content Include="Semantics\BinaryOperatorsTestSource2.vb" /> <Content Include="Semantics\BinaryOperatorsTestSource3.vb" /> <Content Include="Semantics\BinaryOperatorsTestSource4.vb" /> <Content Include="Semantics\BinaryOperatorsTestSource5.vb" /> <Content Include="Semantics\OverloadResolutionTestSource.vb" /> <Content Include="Semantics\PrintResultTestSource.vb" /> <Compile Remove="Semantics\BinaryOperatorsTestSource1.vb" /> <Compile Remove="Semantics\BinaryOperatorsTestSource2.vb" /> <Compile Remove="Semantics\BinaryOperatorsTestSource3.vb" /> <Compile Remove="Semantics\BinaryOperatorsTestSource4.vb" /> <Compile Remove="Semantics\BinaryOperatorsTestSource5.vb" /> <Compile Remove="Semantics\OverloadResolutionTestSource.vb" /> <Compile Remove="Semantics\PrintResultTestSource.vb" /> </ItemGroup> <Import Project="$(RepositoryEngineeringDir)targets\ILAsm.targets" /> </Project>
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Features/VisualBasic/Portable/ConvertForToForEach/VisualBasicConvertForToForEachCodeRefactoringProvider.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.ConvertForToForEach Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.ConvertForToForEach <ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeRefactoringProviderNames.ConvertForToForEach), [Shared]> Friend Class VisualBasicConvertForToForEachCodeRefactoringProvider Inherits AbstractConvertForToForEachCodeRefactoringProvider(Of StatementSyntax, ForBlockSyntax, ExpressionSyntax, MemberAccessExpressionSyntax, TypeSyntax, VariableDeclaratorSyntax) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Protected Overrides Function GetTitle() As String Return VBFeaturesResources.Convert_to_For_Each End Function Protected Overrides Function GetBodyStatements(forStatement As ForBlockSyntax) As SyntaxList(Of StatementSyntax) Return forStatement.Statements End Function Protected Overrides Function IsValidVariableDeclarator(firstVariable As VariableDeclaratorSyntax) As Boolean ' we only support local declarations in vb that have a single identifier. i.e. ' dim x = list(i) Return firstVariable.Names.Count = 1 End Function Protected Overrides Function TryGetForStatementComponents( forBlock As ForBlockSyntax, ByRef iterationVariable As SyntaxToken, ByRef initializer As ExpressionSyntax, ByRef memberAccess As MemberAccessExpressionSyntax, ByRef stepValueExpressionOpt As ExpressionSyntax, cancellationToken As CancellationToken) As Boolean Dim forStatement As ForStatementSyntax = forBlock.ForStatement Dim identifierName = TryCast(forStatement.ControlVariable, IdentifierNameSyntax) If identifierName IsNot Nothing Then iterationVariable = identifierName.Identifier If forStatement.FromValue IsNot Nothing Then initializer = forStatement.FromValue Dim subtraction = TryCast(forStatement.ToValue, BinaryExpressionSyntax) If subtraction?.Kind() = SyntaxKind.SubtractExpression Then Dim subtractionRight = TryCast(subtraction.Right, LiteralExpressionSyntax) If TypeOf subtractionRight?.Token.Value Is Integer AndAlso DirectCast(subtractionRight.Token.Value, Integer) = 1 Then memberAccess = TryCast(subtraction.Left, MemberAccessExpressionSyntax) If memberAccess IsNot Nothing Then stepValueExpressionOpt = forStatement.StepClause?.StepValue Return True End If End If End If End If End If Return False End Function Protected Overrides Function ConvertForNode( currentFor As ForBlockSyntax, typeNode As TypeSyntax, foreachIdentifier As SyntaxToken, collectionExpression As ExpressionSyntax, iterationVariableType As ITypeSymbol, options As OptionSet) As SyntaxNode Dim forStatement = currentFor.ForStatement Return SyntaxFactory.ForEachBlock( SyntaxFactory.ForEachStatement( forStatement.ForKeyword, SyntaxFactory.Token(SyntaxKind.EachKeyword), SyntaxFactory.VariableDeclarator( SyntaxFactory.SingletonSeparatedList(SyntaxFactory.ModifiedIdentifier(foreachIdentifier)), If(typeNode IsNot Nothing, SyntaxFactory.SimpleAsClause(typeNode), Nothing), Nothing), SyntaxFactory.Token(SyntaxKind.InKeyword), collectionExpression).WithTriviaFrom(forStatement), currentFor.Statements, currentFor.NextStatement) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.ConvertForToForEach Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.ConvertForToForEach <ExportCodeRefactoringProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeRefactoringProviderNames.ConvertForToForEach), [Shared]> Friend Class VisualBasicConvertForToForEachCodeRefactoringProvider Inherits AbstractConvertForToForEachCodeRefactoringProvider(Of StatementSyntax, ForBlockSyntax, ExpressionSyntax, MemberAccessExpressionSyntax, TypeSyntax, VariableDeclaratorSyntax) <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Protected Overrides Function GetTitle() As String Return VBFeaturesResources.Convert_to_For_Each End Function Protected Overrides Function GetBodyStatements(forStatement As ForBlockSyntax) As SyntaxList(Of StatementSyntax) Return forStatement.Statements End Function Protected Overrides Function IsValidVariableDeclarator(firstVariable As VariableDeclaratorSyntax) As Boolean ' we only support local declarations in vb that have a single identifier. i.e. ' dim x = list(i) Return firstVariable.Names.Count = 1 End Function Protected Overrides Function TryGetForStatementComponents( forBlock As ForBlockSyntax, ByRef iterationVariable As SyntaxToken, ByRef initializer As ExpressionSyntax, ByRef memberAccess As MemberAccessExpressionSyntax, ByRef stepValueExpressionOpt As ExpressionSyntax, cancellationToken As CancellationToken) As Boolean Dim forStatement As ForStatementSyntax = forBlock.ForStatement Dim identifierName = TryCast(forStatement.ControlVariable, IdentifierNameSyntax) If identifierName IsNot Nothing Then iterationVariable = identifierName.Identifier If forStatement.FromValue IsNot Nothing Then initializer = forStatement.FromValue Dim subtraction = TryCast(forStatement.ToValue, BinaryExpressionSyntax) If subtraction?.Kind() = SyntaxKind.SubtractExpression Then Dim subtractionRight = TryCast(subtraction.Right, LiteralExpressionSyntax) If TypeOf subtractionRight?.Token.Value Is Integer AndAlso DirectCast(subtractionRight.Token.Value, Integer) = 1 Then memberAccess = TryCast(subtraction.Left, MemberAccessExpressionSyntax) If memberAccess IsNot Nothing Then stepValueExpressionOpt = forStatement.StepClause?.StepValue Return True End If End If End If End If End If Return False End Function Protected Overrides Function ConvertForNode( currentFor As ForBlockSyntax, typeNode As TypeSyntax, foreachIdentifier As SyntaxToken, collectionExpression As ExpressionSyntax, iterationVariableType As ITypeSymbol, options As OptionSet) As SyntaxNode Dim forStatement = currentFor.ForStatement Return SyntaxFactory.ForEachBlock( SyntaxFactory.ForEachStatement( forStatement.ForKeyword, SyntaxFactory.Token(SyntaxKind.EachKeyword), SyntaxFactory.VariableDeclarator( SyntaxFactory.SingletonSeparatedList(SyntaxFactory.ModifiedIdentifier(foreachIdentifier)), If(typeNode IsNot Nothing, SyntaxFactory.SimpleAsClause(typeNode), Nothing), Nothing), SyntaxFactory.Token(SyntaxKind.InKeyword), collectionExpression).WithTriviaFrom(forStatement), currentFor.Statements, currentFor.NextStatement) End Function End Class End Namespace
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Features/Core/Portable/RQName/Nodes/RQMethod.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; namespace Microsoft.CodeAnalysis.Features.RQName.Nodes { internal class RQMethod : RQMethodBase { public RQMethod( RQUnconstructedType containingType, RQMethodPropertyOrEventName memberName, int typeParameterCount, IList<RQParameter> parameters) : base(containingType, memberName, typeParameterCount, parameters) { } } }
// Licensed to the .NET Foundation under one or more 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; namespace Microsoft.CodeAnalysis.Features.RQName.Nodes { internal class RQMethod : RQMethodBase { public RQMethod( RQUnconstructedType containingType, RQMethodPropertyOrEventName memberName, int typeParameterCount, IList<RQParameter> parameters) : base(containingType, memberName, typeParameterCount, parameters) { } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/Test/Resources/Core/SymbolsTests/MultiTargeting/Source7.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 /t:module /out:Source7Module.netmodule /vbruntime- Source7.vb ' vbc /t:library /out:c7.dll /vbruntime- Source7.vb Public Class C7 End Class Public Class C8(Of T) End Class
' Licensed to the .NET Foundation under one or more 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 /t:module /out:Source7Module.netmodule /vbruntime- Source7.vb ' vbc /t:library /out:c7.dll /vbruntime- Source7.vb Public Class C7 End Class Public Class C8(Of T) End Class
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Features/Core/Portable/CodeRefactorings/ICodeRefactoringService.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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CodeRefactorings { internal interface ICodeRefactoringService { Task<bool> HasRefactoringsAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken); Task<ImmutableArray<CodeRefactoring>> GetRefactoringsAsync(Document document, TextSpan textSpan, bool isBlocking, Func<string, IDisposable?> addOperationScope, CancellationToken cancellationToken); } internal static class ICodeRefactoringServiceExtensions { public static Task<ImmutableArray<CodeRefactoring>> GetRefactoringsAsync(this ICodeRefactoringService service, Document document, TextSpan state, CancellationToken cancellationToken) => service.GetRefactoringsAsync(document, state, isBlocking: false, cancellationToken); public static Task<ImmutableArray<CodeRefactoring>> GetRefactoringsAsync(this ICodeRefactoringService service, Document document, TextSpan state, bool isBlocking, CancellationToken cancellationToken) => service.GetRefactoringsAsync(document, state, isBlocking, addOperationScope: _ => null, 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; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CodeRefactorings { internal interface ICodeRefactoringService { Task<bool> HasRefactoringsAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken); Task<ImmutableArray<CodeRefactoring>> GetRefactoringsAsync(Document document, TextSpan textSpan, bool isBlocking, Func<string, IDisposable?> addOperationScope, CancellationToken cancellationToken); } internal static class ICodeRefactoringServiceExtensions { public static Task<ImmutableArray<CodeRefactoring>> GetRefactoringsAsync(this ICodeRefactoringService service, Document document, TextSpan state, CancellationToken cancellationToken) => service.GetRefactoringsAsync(document, state, isBlocking: false, cancellationToken); public static Task<ImmutableArray<CodeRefactoring>> GetRefactoringsAsync(this ICodeRefactoringService service, Document document, TextSpan state, bool isBlocking, CancellationToken cancellationToken) => service.GetRefactoringsAsync(document, state, isBlocking, addOperationScope: _ => null, cancellationToken); } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Workspace/Mef/WorkspaceServiceMetadata.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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host.Mef { /// <summary> /// MEF metadata class used for finding <see cref="IWorkspaceService"/> and <see cref="IWorkspaceServiceFactory"/> exports. /// </summary> internal class WorkspaceServiceMetadata { public string ServiceType { get; } public string Layer { get; } public WorkspaceServiceMetadata(Type serviceType, string layer) : this(serviceType.AssemblyQualifiedName, layer) { } public WorkspaceServiceMetadata(IDictionary<string, object> data) { this.ServiceType = (string)data.GetValueOrDefault("ServiceType"); this.Layer = (string)data.GetValueOrDefault("Layer"); } public WorkspaceServiceMetadata(string serviceType, string layer) { this.ServiceType = serviceType; this.Layer = layer; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Host.Mef { /// <summary> /// MEF metadata class used for finding <see cref="IWorkspaceService"/> and <see cref="IWorkspaceServiceFactory"/> exports. /// </summary> internal class WorkspaceServiceMetadata { public string ServiceType { get; } public string Layer { get; } public WorkspaceServiceMetadata(Type serviceType, string layer) : this(serviceType.AssemblyQualifiedName, layer) { } public WorkspaceServiceMetadata(IDictionary<string, object> data) { this.ServiceType = (string)data.GetValueOrDefault("ServiceType"); this.Layer = (string)data.GetValueOrDefault("Layer"); } public WorkspaceServiceMetadata(string serviceType, string layer) { this.ServiceType = serviceType; this.Layer = layer; } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/Core.Wpf/InlineRename/Taggers/ClassificationFormatDefinitions.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 System.Windows.Media; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal sealed class ClassificationFormatDefinitions { [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeDefinitions.InlineRenameField)] [Name(ClassificationTypeDefinitions.InlineRenameField)] [Order(After = Priority.High)] [UserVisible(true)] private class InlineRenameFieldFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public InlineRenameFieldFormatDefinition() { this.DisplayName = EditorFeaturesResources.Inline_Rename_Field_Text; this.ForegroundColor = Color.FromRgb(0x00, 0x64, 0x00); } } } }
// Licensed to the .NET Foundation under one or more 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 System.Windows.Media; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal sealed class ClassificationFormatDefinitions { [Export(typeof(EditorFormatDefinition))] [ClassificationType(ClassificationTypeNames = ClassificationTypeDefinitions.InlineRenameField)] [Name(ClassificationTypeDefinitions.InlineRenameField)] [Order(After = Priority.High)] [UserVisible(true)] private class InlineRenameFieldFormatDefinition : ClassificationFormatDefinition { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public InlineRenameFieldFormatDefinition() { this.DisplayName = EditorFeaturesResources.Inline_Rename_Field_Text; this.ForegroundColor = Color.FromRgb(0x00, 0x64, 0x00); } } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/Shared/BuildServerConnection.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.ComponentModel; using System.Diagnostics; using System.IO; using System.IO.Pipes; using System.Reflection; using System.Runtime.InteropServices; using System.Security.AccessControl; using System.Security.Cryptography; using System.Security.Principal; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Win32.SafeHandles; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CommandLine.CompilerServerLogger; using static Microsoft.CodeAnalysis.CommandLine.NativeMethods; namespace Microsoft.CodeAnalysis.CommandLine { /// <summary> /// This type is functionally identical to BuildPaths. Unfortunately BuildPaths cannot be used in our MSBuild /// layer as it's defined in Microsoft.CodeAnalysis. Yet we need the same functionality in our build server /// communication layer which is shared between MSBuild and non-MSBuild components. This is the problem that /// BuildPathsAlt fixes as the type lives with the build server communication code. /// </summary> internal sealed class BuildPathsAlt { /// <summary> /// The path which contains the compiler binaries and response files. /// </summary> internal string ClientDirectory { get; } /// <summary> /// The path in which the compilation takes place. /// </summary> internal string WorkingDirectory { get; } /// <summary> /// The path which contains mscorlib. This can be null when specified by the user or running in a /// CoreClr environment. /// </summary> internal string? SdkDirectory { get; } /// <summary> /// The temporary directory a compilation should use instead of <see cref="Path.GetTempPath"/>. The latter /// relies on global state individual compilations should ignore. /// </summary> internal string? TempDirectory { get; } internal BuildPathsAlt(string clientDir, string workingDir, string? sdkDir, string? tempDir) { ClientDirectory = clientDir; WorkingDirectory = workingDir; SdkDirectory = sdkDir; TempDirectory = tempDir; } } internal delegate bool CreateServerFunc(string clientDir, string pipeName, ICompilerServerLogger logger); internal sealed class BuildServerConnection { // Spend up to 1s connecting to existing process (existing processes should be always responsive). internal const int TimeOutMsExistingProcess = 1000; // Spend up to 20s connecting to a new process, to allow time for it to start. internal const int TimeOutMsNewProcess = 20000; /// <summary> /// Determines if the compiler server is supported in this environment. /// </summary> internal static bool IsCompilerServerSupported => GetPipeNameForPath("") is object; public static Task<BuildResponse> RunServerCompilationAsync( Guid requestId, RequestLanguage language, string? sharedCompilationId, List<string> arguments, BuildPathsAlt buildPaths, string? keepAlive, string? libEnvVariable, ICompilerServerLogger logger, CancellationToken cancellationToken) { var pipeNameOpt = sharedCompilationId ?? GetPipeNameForPath(buildPaths.ClientDirectory); return RunServerCompilationCoreAsync( requestId, language, arguments, buildPaths, pipeNameOpt, keepAlive, libEnvVariable, timeoutOverride: null, createServerFunc: TryCreateServerCore, logger: logger, cancellationToken: cancellationToken); } internal static async Task<BuildResponse> RunServerCompilationCoreAsync( Guid requestId, RequestLanguage language, List<string> arguments, BuildPathsAlt buildPaths, string? pipeName, string? keepAlive, string? libDirectory, int? timeoutOverride, CreateServerFunc createServerFunc, ICompilerServerLogger logger, CancellationToken cancellationToken) { if (pipeName is null) { throw new ArgumentException(nameof(pipeName)); } if (buildPaths.TempDirectory == null) { throw new ArgumentException(nameof(buildPaths)); } // early check for the build hash. If we can't find it something is wrong; no point even trying to go to the server if (string.IsNullOrWhiteSpace(BuildProtocolConstants.GetCommitHash())) { return new IncorrectHashBuildResponse(); } var pipeTask = tryConnectToServer(pipeName, buildPaths, timeoutOverride, createServerFunc, logger, cancellationToken); if (pipeTask is null) { return new RejectedBuildResponse("Failed to connect to server"); } else { using var pipe = await pipeTask.ConfigureAwait(false); if (pipe is null) { return new RejectedBuildResponse("Failed to connect to server"); } else { var request = BuildRequest.Create(language, arguments, workingDirectory: buildPaths.WorkingDirectory, tempDirectory: buildPaths.TempDirectory, compilerHash: BuildProtocolConstants.GetCommitHash() ?? "", requestId: requestId, keepAlive: keepAlive, libDirectory: libDirectory); return await TryCompileAsync(pipe, request, logger, cancellationToken).ConfigureAwait(false); } } // This code uses a Mutex.WaitOne / ReleaseMutex pairing. Both of these calls must occur on the same thread // or an exception will be thrown. This code lives in a separate non-async function to help ensure this // invariant doesn't get invalidated in the future by an `await` being inserted. static Task<NamedPipeClientStream?>? tryConnectToServer( string pipeName, BuildPathsAlt buildPaths, int? timeoutOverride, CreateServerFunc createServerFunc, ICompilerServerLogger logger, CancellationToken cancellationToken) { var originalThreadId = Environment.CurrentManagedThreadId; var clientDir = buildPaths.ClientDirectory; var timeoutNewProcess = timeoutOverride ?? TimeOutMsNewProcess; var timeoutExistingProcess = timeoutOverride ?? TimeOutMsExistingProcess; Task<NamedPipeClientStream?>? pipeTask = null; IServerMutex? clientMutex = null; try { var holdsMutex = false; try { var clientMutexName = GetClientMutexName(pipeName); clientMutex = OpenOrCreateMutex(clientMutexName, out holdsMutex); } catch { // The Mutex constructor can throw in certain cases. One specific example is docker containers // where the /tmp directory is restricted. In those cases there is no reliable way to execute // the server and we need to fall back to the command line. // // Example: https://github.com/dotnet/roslyn/issues/24124 #pragma warning disable VSTHRD114 // Avoid returning a null Task (False positive: https://github.com/microsoft/vs-threading/issues/637) return null; #pragma warning restore VSTHRD114 // Avoid returning a null Task } if (!holdsMutex) { try { holdsMutex = clientMutex.TryLock(timeoutNewProcess); if (!holdsMutex) { #pragma warning disable VSTHRD114 // Avoid returning a null Task (False positive: https://github.com/microsoft/vs-threading/issues/637) return null; #pragma warning restore VSTHRD114 // Avoid returning a null Task } } catch (AbandonedMutexException) { holdsMutex = true; } } // Check for an already running server var serverMutexName = GetServerMutexName(pipeName); bool wasServerRunning = WasServerMutexOpen(serverMutexName); var timeout = wasServerRunning ? timeoutExistingProcess : timeoutNewProcess; if (wasServerRunning || createServerFunc(clientDir, pipeName, logger)) { pipeTask = TryConnectToServerAsync(pipeName, timeout, logger, cancellationToken); } return pipeTask; } finally { try { clientMutex?.Dispose(); } catch (ApplicationException e) { var releaseThreadId = Environment.CurrentManagedThreadId; var message = $"ReleaseMutex failed. WaitOne Id: {originalThreadId} Release Id: {releaseThreadId}"; throw new Exception(message, e); } } } } /// <summary> /// Try to compile using the server. Returns a null-containing Task if a response /// from the server cannot be retrieved. /// </summary> private static async Task<BuildResponse> TryCompileAsync( NamedPipeClientStream pipeStream, BuildRequest request, ICompilerServerLogger logger, CancellationToken cancellationToken) { BuildResponse response; using (pipeStream) { // Write the request try { logger.Log($"Begin writing request for {request.RequestId}"); await request.WriteAsync(pipeStream, cancellationToken).ConfigureAwait(false); logger.Log($"End writing request for {request.RequestId}"); } catch (Exception e) { logger.LogException(e, $"Error writing build request for {request.RequestId}"); return new RejectedBuildResponse($"Error writing build request: {e.Message}"); } // Wait for the compilation and a monitor to detect if the server disconnects var serverCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); logger.Log($"Begin reading response for {request.RequestId}"); var responseTask = BuildResponse.ReadAsync(pipeStream, serverCts.Token); var monitorTask = MonitorDisconnectAsync(pipeStream, request.RequestId, logger, serverCts.Token); await Task.WhenAny(responseTask, monitorTask).ConfigureAwait(false); logger.Log($"End reading response for {request.RequestId}"); if (responseTask.IsCompleted) { // await the task to log any exceptions try { response = await responseTask.ConfigureAwait(false); } catch (Exception e) { logger.LogException(e, $"Reading response for {request.RequestId}"); response = new RejectedBuildResponse($"Error reading response: {e.Message}"); } } else { logger.LogError($"Client disconnect for {request.RequestId}"); response = new RejectedBuildResponse($"Client disconnected"); } // Cancel whatever task is still around serverCts.Cancel(); RoslynDebug.Assert(response != null); return response; } } /// <summary> /// The IsConnected property on named pipes does not detect when the client has disconnected /// if we don't attempt any new I/O after the client disconnects. We start an async I/O here /// which serves to check the pipe for disconnection. /// </summary> internal static async Task MonitorDisconnectAsync( PipeStream pipeStream, Guid requestId, ICompilerServerLogger logger, CancellationToken cancellationToken = default) { var buffer = Array.Empty<byte>(); while (!cancellationToken.IsCancellationRequested && pipeStream.IsConnected) { try { // Wait a tenth of a second before trying again await Task.Delay(millisecondsDelay: 100, cancellationToken).ConfigureAwait(false); await pipeStream.ReadAsync(buffer, 0, 0, cancellationToken).ConfigureAwait(false); } catch (OperationCanceledException) { } catch (Exception e) { // It is okay for this call to fail. Errors will be reflected in the // IsConnected property which will be read on the next iteration of the logger.LogException(e, $"Error poking pipe {requestId}."); } } } /// <summary> /// Connect to the pipe for a given directory and return it. /// Throws on cancellation. /// </summary> /// <param name="pipeName">Name of the named pipe to connect to.</param> /// <param name="timeoutMs">Timeout to allow in connecting to process.</param> /// <param name="cancellationToken">Cancellation token to cancel connection to server.</param> /// <returns> /// An open <see cref="NamedPipeClientStream"/> to the server process or null on failure. /// </returns> internal static async Task<NamedPipeClientStream?> TryConnectToServerAsync( string pipeName, int timeoutMs, ICompilerServerLogger logger, CancellationToken cancellationToken) { NamedPipeClientStream? pipeStream = null; try { // Machine-local named pipes are named "\\.\pipe\<pipename>". // We use the SHA1 of the directory the compiler exes live in as the pipe name. // The NamedPipeClientStream class handles the "\\.\pipe\" part for us. logger.Log("Attempt to open named pipe '{0}'", pipeName); pipeStream = NamedPipeUtil.CreateClient(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous); cancellationToken.ThrowIfCancellationRequested(); logger.Log("Attempt to connect named pipe '{0}'", pipeName); try { // NamedPipeClientStream.ConnectAsync on the "full" framework has a bug where it // tries to move potentially expensive work (actually connecting to the pipe) to // a background thread with Task.Factory.StartNew. However, that call will merely // queue the work onto the TaskScheduler associated with the "current" Task which // does not guarantee it will be processed on a background thread and this could // lead to a hang. // To avoid this, we first force ourselves to a background thread using Task.Run. // This ensures that the Task created by ConnectAsync will run on the default // TaskScheduler (i.e., on a threadpool thread) which was the intent all along. await Task.Run(() => pipeStream.ConnectAsync(timeoutMs, cancellationToken), cancellationToken).ConfigureAwait(false); } catch (Exception e) when (e is IOException || e is TimeoutException) { // Note: IOException can also indicate timeout. From docs: // TimeoutException: Could not connect to the server within the // specified timeout period. // IOException: The server is connected to another client and the // time-out period has expired. logger.LogException(e, $"Connecting to server timed out after {timeoutMs} ms"); pipeStream.Dispose(); return null; } logger.Log("Named pipe '{0}' connected", pipeName); cancellationToken.ThrowIfCancellationRequested(); // Verify that we own the pipe. if (!NamedPipeUtil.CheckPipeConnectionOwnership(pipeStream)) { pipeStream.Dispose(); logger.LogError("Owner of named pipe is incorrect"); return null; } return pipeStream; } catch (Exception e) when (!(e is TaskCanceledException || e is OperationCanceledException)) { logger.LogException(e, "Exception while connecting to process"); pipeStream?.Dispose(); return null; } } internal static (string processFilePath, string commandLineArguments, string toolFilePath) GetServerProcessInfo(string clientDir, string pipeName) { var serverPathWithoutExtension = Path.Combine(clientDir, "VBCSCompiler"); var commandLineArgs = $@"""-pipename:{pipeName}"""; return RuntimeHostInfo.GetProcessInfo(serverPathWithoutExtension, commandLineArgs); } internal static bool TryCreateServerCore(string clientDir, string pipeName, ICompilerServerLogger logger) { var serverInfo = GetServerProcessInfo(clientDir, pipeName); if (!File.Exists(serverInfo.toolFilePath)) { return false; } if (PlatformInformation.IsWindows) { // As far as I can tell, there isn't a way to use the Process class to // create a process with no stdin/stdout/stderr, so we use P/Invoke. // This code was taken from MSBuild task starting code. STARTUPINFO startInfo = new STARTUPINFO(); startInfo.cb = Marshal.SizeOf(startInfo); startInfo.hStdError = InvalidIntPtr; startInfo.hStdInput = InvalidIntPtr; startInfo.hStdOutput = InvalidIntPtr; startInfo.dwFlags = STARTF_USESTDHANDLES; uint dwCreationFlags = NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW; PROCESS_INFORMATION processInfo; logger.Log("Attempting to create process '{0}'", serverInfo.processFilePath); var builder = new StringBuilder($@"""{serverInfo.processFilePath}"" {serverInfo.commandLineArguments}"); bool success = CreateProcess( lpApplicationName: null, lpCommandLine: builder, lpProcessAttributes: NullPtr, lpThreadAttributes: NullPtr, bInheritHandles: false, dwCreationFlags: dwCreationFlags, lpEnvironment: NullPtr, // Inherit environment lpCurrentDirectory: clientDir, lpStartupInfo: ref startInfo, lpProcessInformation: out processInfo); if (success) { logger.Log("Successfully created process with process id {0}", processInfo.dwProcessId); CloseHandle(processInfo.hProcess); CloseHandle(processInfo.hThread); } else { logger.LogError("Failed to create process. GetLastError={0}", Marshal.GetLastWin32Error()); } return success; } else { try { var startInfo = new ProcessStartInfo() { FileName = serverInfo.processFilePath, Arguments = serverInfo.commandLineArguments, UseShellExecute = false, WorkingDirectory = clientDir, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true }; Process.Start(startInfo); return true; } catch { return false; } } } /// <returns> /// Null if not enough information was found to create a valid pipe name. /// </returns> internal static string? GetPipeNameForPath(string compilerExeDirectory) { // Prefix with username and elevation bool isAdmin = false; if (PlatformInformation.IsWindows) { var currentIdentity = WindowsIdentity.GetCurrent(); var principal = new WindowsPrincipal(currentIdentity); isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator); } var userName = Environment.UserName; if (userName == null) { return null; } return GetPipeName(userName, isAdmin, compilerExeDirectory); } internal static string GetPipeName( string userName, bool isAdmin, string compilerExeDirectory) { // Normalize away trailing slashes. File APIs include / exclude this with no // discernable pattern. Easiest to normalize it here vs. auditing every caller // of this method. compilerExeDirectory = compilerExeDirectory.TrimEnd(Path.DirectorySeparatorChar); var pipeNameInput = $"{userName}.{isAdmin}.{compilerExeDirectory}"; using (var sha = SHA256.Create()) { var bytes = sha.ComputeHash(Encoding.UTF8.GetBytes(pipeNameInput)); return Convert.ToBase64String(bytes) .Replace("/", "_") .Replace("=", string.Empty); } } internal static bool WasServerMutexOpen(string mutexName) { try { if (PlatformInformation.IsRunningOnMono) { IServerMutex? mutex = null; bool createdNew = false; try { mutex = new ServerFileMutexPair(mutexName, false, out createdNew); return !createdNew; } finally { mutex?.Dispose(); } } else { return ServerNamedMutex.WasOpen(mutexName); } } catch { // In the case an exception occurred trying to open the Mutex then // the assumption is that it's not open. return false; } } internal static IServerMutex OpenOrCreateMutex(string name, out bool createdNew) { if (PlatformInformation.IsRunningOnMono) { return new ServerFileMutexPair(name, initiallyOwned: true, out createdNew); } else { return new ServerNamedMutex(name, out createdNew); } } internal static string GetServerMutexName(string pipeName) { return $"{pipeName}.server"; } internal static string GetClientMutexName(string pipeName) { return $"{pipeName}.client"; } /// <summary> /// Gets the value of the temporary path for the current environment assuming the working directory /// is <paramref name="workingDir"/>. This function must emulate <see cref="Path.GetTempPath"/> as /// closely as possible. /// </summary> public static string? GetTempPath(string? workingDir) { if (PlatformInformation.IsUnix) { // Unix temp path is fine: it does not use the working directory // (it uses ${TMPDIR} if set, otherwise, it returns /tmp) return Path.GetTempPath(); } var tmp = Environment.GetEnvironmentVariable("TMP"); if (Path.IsPathRooted(tmp)) { return tmp; } var temp = Environment.GetEnvironmentVariable("TEMP"); if (Path.IsPathRooted(temp)) { return temp; } if (!string.IsNullOrEmpty(workingDir)) { if (!string.IsNullOrEmpty(tmp)) { return Path.Combine(workingDir, tmp); } if (!string.IsNullOrEmpty(temp)) { return Path.Combine(workingDir, temp); } } var userProfile = Environment.GetEnvironmentVariable("USERPROFILE"); if (Path.IsPathRooted(userProfile)) { return userProfile; } return Environment.GetEnvironmentVariable("SYSTEMROOT"); } } internal interface IServerMutex : IDisposable { bool TryLock(int timeoutMs); bool IsDisposed { get; } } /// <summary> /// An interprocess mutex abstraction based on OS advisory locking (FileStream.Lock/Unlock). /// If multiple processes running as the same user create FileMutex instances with the same name, /// those instances will all point to the same file somewhere in a selected temporary directory. /// The TryLock method can be used to attempt to acquire the mutex, with Unlock or Dispose used to release. /// Unlike Win32 named mutexes, there is no mechanism for detecting an abandoned mutex. The file /// will simply revert to being unlocked but remain where it is. /// </summary> internal sealed class FileMutex : IDisposable { public readonly FileStream Stream; public readonly string FilePath; public bool IsLocked { get; private set; } internal static string GetMutexDirectory() { var tempPath = BuildServerConnection.GetTempPath(null); var result = Path.Combine(tempPath!, ".roslyn"); Directory.CreateDirectory(result); return result; } public FileMutex(string name) { FilePath = Path.Combine(GetMutexDirectory(), name); Stream = new FileStream(FilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); } public bool TryLock(int timeoutMs) { if (IsLocked) throw new InvalidOperationException("Lock already held"); var sw = Stopwatch.StartNew(); do { try { Stream.Lock(0, 0); IsLocked = true; return true; } catch (IOException) { // Lock currently held by someone else. // We want to sleep for a short period of time to ensure that other processes // have an opportunity to finish their work and relinquish the lock. // Spinning here (via Yield) would work but risks creating a priority // inversion if the lock is held by a lower-priority process. Thread.Sleep(1); } catch (Exception) { // Something else went wrong. return false; } } while (sw.ElapsedMilliseconds < timeoutMs); return false; } public void Unlock() { if (!IsLocked) return; Stream.Unlock(0, 0); IsLocked = false; } public void Dispose() { var wasLocked = IsLocked; if (wasLocked) Unlock(); Stream.Dispose(); // We do not delete the lock file here because there is no reliable way to perform a // 'delete if no one has the file open' operation atomically on *nix. This is a leak. } } internal sealed class ServerNamedMutex : IServerMutex { public readonly Mutex Mutex; public bool IsDisposed { get; private set; } public bool IsLocked { get; private set; } public ServerNamedMutex(string mutexName, out bool createdNew) { Mutex = new Mutex( initiallyOwned: true, name: mutexName, createdNew: out createdNew ); if (createdNew) IsLocked = true; } public static bool WasOpen(string mutexName) { Mutex? m = null; try { return Mutex.TryOpenExisting(mutexName, out m); } catch { // In the case an exception occurred trying to open the Mutex then // the assumption is that it's not open. return false; } finally { m?.Dispose(); } } public bool TryLock(int timeoutMs) { if (IsDisposed) throw new ObjectDisposedException("Mutex"); if (IsLocked) throw new InvalidOperationException("Lock already held"); return IsLocked = Mutex.WaitOne(timeoutMs); } public void Dispose() { if (IsDisposed) return; IsDisposed = true; try { if (IsLocked) Mutex.ReleaseMutex(); } finally { Mutex.Dispose(); IsLocked = false; } } } /// <summary> /// Approximates a named mutex with 'locked', 'unlocked' and 'abandoned' states. /// There is no reliable way to detect whether a mutex has been abandoned on some target platforms, /// so we use the AliveMutex to manually track whether the creator of a mutex is still running, /// while the HeldMutex represents the actual lock state of the mutex. /// </summary> internal sealed class ServerFileMutexPair : IServerMutex { public readonly FileMutex AliveMutex; public readonly FileMutex HeldMutex; public bool IsDisposed { get; private set; } public ServerFileMutexPair(string mutexName, bool initiallyOwned, out bool createdNew) { AliveMutex = new FileMutex(mutexName + "-alive"); HeldMutex = new FileMutex(mutexName + "-held"); createdNew = AliveMutex.TryLock(0); if (initiallyOwned && createdNew) { if (!TryLock(0)) throw new Exception("Failed to lock mutex after creating it"); } } public bool TryLock(int timeoutMs) { if (IsDisposed) throw new ObjectDisposedException("Mutex"); return HeldMutex.TryLock(timeoutMs); } public void Dispose() { if (IsDisposed) return; IsDisposed = true; try { HeldMutex.Unlock(); AliveMutex.Unlock(); } finally { AliveMutex.Dispose(); HeldMutex.Dispose(); } } } }
// Licensed to the .NET Foundation under one or more 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.ComponentModel; using System.Diagnostics; using System.IO; using System.IO.Pipes; using System.Reflection; using System.Runtime.InteropServices; using System.Security.AccessControl; using System.Security.Cryptography; using System.Security.Principal; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Win32.SafeHandles; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CommandLine.CompilerServerLogger; using static Microsoft.CodeAnalysis.CommandLine.NativeMethods; namespace Microsoft.CodeAnalysis.CommandLine { /// <summary> /// This type is functionally identical to BuildPaths. Unfortunately BuildPaths cannot be used in our MSBuild /// layer as it's defined in Microsoft.CodeAnalysis. Yet we need the same functionality in our build server /// communication layer which is shared between MSBuild and non-MSBuild components. This is the problem that /// BuildPathsAlt fixes as the type lives with the build server communication code. /// </summary> internal sealed class BuildPathsAlt { /// <summary> /// The path which contains the compiler binaries and response files. /// </summary> internal string ClientDirectory { get; } /// <summary> /// The path in which the compilation takes place. /// </summary> internal string WorkingDirectory { get; } /// <summary> /// The path which contains mscorlib. This can be null when specified by the user or running in a /// CoreClr environment. /// </summary> internal string? SdkDirectory { get; } /// <summary> /// The temporary directory a compilation should use instead of <see cref="Path.GetTempPath"/>. The latter /// relies on global state individual compilations should ignore. /// </summary> internal string? TempDirectory { get; } internal BuildPathsAlt(string clientDir, string workingDir, string? sdkDir, string? tempDir) { ClientDirectory = clientDir; WorkingDirectory = workingDir; SdkDirectory = sdkDir; TempDirectory = tempDir; } } internal delegate bool CreateServerFunc(string clientDir, string pipeName, ICompilerServerLogger logger); internal sealed class BuildServerConnection { // Spend up to 1s connecting to existing process (existing processes should be always responsive). internal const int TimeOutMsExistingProcess = 1000; // Spend up to 20s connecting to a new process, to allow time for it to start. internal const int TimeOutMsNewProcess = 20000; /// <summary> /// Determines if the compiler server is supported in this environment. /// </summary> internal static bool IsCompilerServerSupported => GetPipeNameForPath("") is object; public static Task<BuildResponse> RunServerCompilationAsync( Guid requestId, RequestLanguage language, string? sharedCompilationId, List<string> arguments, BuildPathsAlt buildPaths, string? keepAlive, string? libEnvVariable, ICompilerServerLogger logger, CancellationToken cancellationToken) { var pipeNameOpt = sharedCompilationId ?? GetPipeNameForPath(buildPaths.ClientDirectory); return RunServerCompilationCoreAsync( requestId, language, arguments, buildPaths, pipeNameOpt, keepAlive, libEnvVariable, timeoutOverride: null, createServerFunc: TryCreateServerCore, logger: logger, cancellationToken: cancellationToken); } internal static async Task<BuildResponse> RunServerCompilationCoreAsync( Guid requestId, RequestLanguage language, List<string> arguments, BuildPathsAlt buildPaths, string? pipeName, string? keepAlive, string? libDirectory, int? timeoutOverride, CreateServerFunc createServerFunc, ICompilerServerLogger logger, CancellationToken cancellationToken) { if (pipeName is null) { throw new ArgumentException(nameof(pipeName)); } if (buildPaths.TempDirectory == null) { throw new ArgumentException(nameof(buildPaths)); } // early check for the build hash. If we can't find it something is wrong; no point even trying to go to the server if (string.IsNullOrWhiteSpace(BuildProtocolConstants.GetCommitHash())) { return new IncorrectHashBuildResponse(); } var pipeTask = tryConnectToServer(pipeName, buildPaths, timeoutOverride, createServerFunc, logger, cancellationToken); if (pipeTask is null) { return new RejectedBuildResponse("Failed to connect to server"); } else { using var pipe = await pipeTask.ConfigureAwait(false); if (pipe is null) { return new RejectedBuildResponse("Failed to connect to server"); } else { var request = BuildRequest.Create(language, arguments, workingDirectory: buildPaths.WorkingDirectory, tempDirectory: buildPaths.TempDirectory, compilerHash: BuildProtocolConstants.GetCommitHash() ?? "", requestId: requestId, keepAlive: keepAlive, libDirectory: libDirectory); return await TryCompileAsync(pipe, request, logger, cancellationToken).ConfigureAwait(false); } } // This code uses a Mutex.WaitOne / ReleaseMutex pairing. Both of these calls must occur on the same thread // or an exception will be thrown. This code lives in a separate non-async function to help ensure this // invariant doesn't get invalidated in the future by an `await` being inserted. static Task<NamedPipeClientStream?>? tryConnectToServer( string pipeName, BuildPathsAlt buildPaths, int? timeoutOverride, CreateServerFunc createServerFunc, ICompilerServerLogger logger, CancellationToken cancellationToken) { var originalThreadId = Environment.CurrentManagedThreadId; var clientDir = buildPaths.ClientDirectory; var timeoutNewProcess = timeoutOverride ?? TimeOutMsNewProcess; var timeoutExistingProcess = timeoutOverride ?? TimeOutMsExistingProcess; Task<NamedPipeClientStream?>? pipeTask = null; IServerMutex? clientMutex = null; try { var holdsMutex = false; try { var clientMutexName = GetClientMutexName(pipeName); clientMutex = OpenOrCreateMutex(clientMutexName, out holdsMutex); } catch { // The Mutex constructor can throw in certain cases. One specific example is docker containers // where the /tmp directory is restricted. In those cases there is no reliable way to execute // the server and we need to fall back to the command line. // // Example: https://github.com/dotnet/roslyn/issues/24124 #pragma warning disable VSTHRD114 // Avoid returning a null Task (False positive: https://github.com/microsoft/vs-threading/issues/637) return null; #pragma warning restore VSTHRD114 // Avoid returning a null Task } if (!holdsMutex) { try { holdsMutex = clientMutex.TryLock(timeoutNewProcess); if (!holdsMutex) { #pragma warning disable VSTHRD114 // Avoid returning a null Task (False positive: https://github.com/microsoft/vs-threading/issues/637) return null; #pragma warning restore VSTHRD114 // Avoid returning a null Task } } catch (AbandonedMutexException) { holdsMutex = true; } } // Check for an already running server var serverMutexName = GetServerMutexName(pipeName); bool wasServerRunning = WasServerMutexOpen(serverMutexName); var timeout = wasServerRunning ? timeoutExistingProcess : timeoutNewProcess; if (wasServerRunning || createServerFunc(clientDir, pipeName, logger)) { pipeTask = TryConnectToServerAsync(pipeName, timeout, logger, cancellationToken); } return pipeTask; } finally { try { clientMutex?.Dispose(); } catch (ApplicationException e) { var releaseThreadId = Environment.CurrentManagedThreadId; var message = $"ReleaseMutex failed. WaitOne Id: {originalThreadId} Release Id: {releaseThreadId}"; throw new Exception(message, e); } } } } /// <summary> /// Try to compile using the server. Returns a null-containing Task if a response /// from the server cannot be retrieved. /// </summary> private static async Task<BuildResponse> TryCompileAsync( NamedPipeClientStream pipeStream, BuildRequest request, ICompilerServerLogger logger, CancellationToken cancellationToken) { BuildResponse response; using (pipeStream) { // Write the request try { logger.Log($"Begin writing request for {request.RequestId}"); await request.WriteAsync(pipeStream, cancellationToken).ConfigureAwait(false); logger.Log($"End writing request for {request.RequestId}"); } catch (Exception e) { logger.LogException(e, $"Error writing build request for {request.RequestId}"); return new RejectedBuildResponse($"Error writing build request: {e.Message}"); } // Wait for the compilation and a monitor to detect if the server disconnects var serverCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); logger.Log($"Begin reading response for {request.RequestId}"); var responseTask = BuildResponse.ReadAsync(pipeStream, serverCts.Token); var monitorTask = MonitorDisconnectAsync(pipeStream, request.RequestId, logger, serverCts.Token); await Task.WhenAny(responseTask, monitorTask).ConfigureAwait(false); logger.Log($"End reading response for {request.RequestId}"); if (responseTask.IsCompleted) { // await the task to log any exceptions try { response = await responseTask.ConfigureAwait(false); } catch (Exception e) { logger.LogException(e, $"Reading response for {request.RequestId}"); response = new RejectedBuildResponse($"Error reading response: {e.Message}"); } } else { logger.LogError($"Client disconnect for {request.RequestId}"); response = new RejectedBuildResponse($"Client disconnected"); } // Cancel whatever task is still around serverCts.Cancel(); RoslynDebug.Assert(response != null); return response; } } /// <summary> /// The IsConnected property on named pipes does not detect when the client has disconnected /// if we don't attempt any new I/O after the client disconnects. We start an async I/O here /// which serves to check the pipe for disconnection. /// </summary> internal static async Task MonitorDisconnectAsync( PipeStream pipeStream, Guid requestId, ICompilerServerLogger logger, CancellationToken cancellationToken = default) { var buffer = Array.Empty<byte>(); while (!cancellationToken.IsCancellationRequested && pipeStream.IsConnected) { try { // Wait a tenth of a second before trying again await Task.Delay(millisecondsDelay: 100, cancellationToken).ConfigureAwait(false); await pipeStream.ReadAsync(buffer, 0, 0, cancellationToken).ConfigureAwait(false); } catch (OperationCanceledException) { } catch (Exception e) { // It is okay for this call to fail. Errors will be reflected in the // IsConnected property which will be read on the next iteration of the logger.LogException(e, $"Error poking pipe {requestId}."); } } } /// <summary> /// Connect to the pipe for a given directory and return it. /// Throws on cancellation. /// </summary> /// <param name="pipeName">Name of the named pipe to connect to.</param> /// <param name="timeoutMs">Timeout to allow in connecting to process.</param> /// <param name="cancellationToken">Cancellation token to cancel connection to server.</param> /// <returns> /// An open <see cref="NamedPipeClientStream"/> to the server process or null on failure. /// </returns> internal static async Task<NamedPipeClientStream?> TryConnectToServerAsync( string pipeName, int timeoutMs, ICompilerServerLogger logger, CancellationToken cancellationToken) { NamedPipeClientStream? pipeStream = null; try { // Machine-local named pipes are named "\\.\pipe\<pipename>". // We use the SHA1 of the directory the compiler exes live in as the pipe name. // The NamedPipeClientStream class handles the "\\.\pipe\" part for us. logger.Log("Attempt to open named pipe '{0}'", pipeName); pipeStream = NamedPipeUtil.CreateClient(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous); cancellationToken.ThrowIfCancellationRequested(); logger.Log("Attempt to connect named pipe '{0}'", pipeName); try { // NamedPipeClientStream.ConnectAsync on the "full" framework has a bug where it // tries to move potentially expensive work (actually connecting to the pipe) to // a background thread with Task.Factory.StartNew. However, that call will merely // queue the work onto the TaskScheduler associated with the "current" Task which // does not guarantee it will be processed on a background thread and this could // lead to a hang. // To avoid this, we first force ourselves to a background thread using Task.Run. // This ensures that the Task created by ConnectAsync will run on the default // TaskScheduler (i.e., on a threadpool thread) which was the intent all along. await Task.Run(() => pipeStream.ConnectAsync(timeoutMs, cancellationToken), cancellationToken).ConfigureAwait(false); } catch (Exception e) when (e is IOException || e is TimeoutException) { // Note: IOException can also indicate timeout. From docs: // TimeoutException: Could not connect to the server within the // specified timeout period. // IOException: The server is connected to another client and the // time-out period has expired. logger.LogException(e, $"Connecting to server timed out after {timeoutMs} ms"); pipeStream.Dispose(); return null; } logger.Log("Named pipe '{0}' connected", pipeName); cancellationToken.ThrowIfCancellationRequested(); // Verify that we own the pipe. if (!NamedPipeUtil.CheckPipeConnectionOwnership(pipeStream)) { pipeStream.Dispose(); logger.LogError("Owner of named pipe is incorrect"); return null; } return pipeStream; } catch (Exception e) when (!(e is TaskCanceledException || e is OperationCanceledException)) { logger.LogException(e, "Exception while connecting to process"); pipeStream?.Dispose(); return null; } } internal static (string processFilePath, string commandLineArguments, string toolFilePath) GetServerProcessInfo(string clientDir, string pipeName) { var serverPathWithoutExtension = Path.Combine(clientDir, "VBCSCompiler"); var commandLineArgs = $@"""-pipename:{pipeName}"""; return RuntimeHostInfo.GetProcessInfo(serverPathWithoutExtension, commandLineArgs); } internal static bool TryCreateServerCore(string clientDir, string pipeName, ICompilerServerLogger logger) { var serverInfo = GetServerProcessInfo(clientDir, pipeName); if (!File.Exists(serverInfo.toolFilePath)) { return false; } if (PlatformInformation.IsWindows) { // As far as I can tell, there isn't a way to use the Process class to // create a process with no stdin/stdout/stderr, so we use P/Invoke. // This code was taken from MSBuild task starting code. STARTUPINFO startInfo = new STARTUPINFO(); startInfo.cb = Marshal.SizeOf(startInfo); startInfo.hStdError = InvalidIntPtr; startInfo.hStdInput = InvalidIntPtr; startInfo.hStdOutput = InvalidIntPtr; startInfo.dwFlags = STARTF_USESTDHANDLES; uint dwCreationFlags = NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW; PROCESS_INFORMATION processInfo; logger.Log("Attempting to create process '{0}'", serverInfo.processFilePath); var builder = new StringBuilder($@"""{serverInfo.processFilePath}"" {serverInfo.commandLineArguments}"); bool success = CreateProcess( lpApplicationName: null, lpCommandLine: builder, lpProcessAttributes: NullPtr, lpThreadAttributes: NullPtr, bInheritHandles: false, dwCreationFlags: dwCreationFlags, lpEnvironment: NullPtr, // Inherit environment lpCurrentDirectory: clientDir, lpStartupInfo: ref startInfo, lpProcessInformation: out processInfo); if (success) { logger.Log("Successfully created process with process id {0}", processInfo.dwProcessId); CloseHandle(processInfo.hProcess); CloseHandle(processInfo.hThread); } else { logger.LogError("Failed to create process. GetLastError={0}", Marshal.GetLastWin32Error()); } return success; } else { try { var startInfo = new ProcessStartInfo() { FileName = serverInfo.processFilePath, Arguments = serverInfo.commandLineArguments, UseShellExecute = false, WorkingDirectory = clientDir, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true }; Process.Start(startInfo); return true; } catch { return false; } } } /// <returns> /// Null if not enough information was found to create a valid pipe name. /// </returns> internal static string? GetPipeNameForPath(string compilerExeDirectory) { // Prefix with username and elevation bool isAdmin = false; if (PlatformInformation.IsWindows) { var currentIdentity = WindowsIdentity.GetCurrent(); var principal = new WindowsPrincipal(currentIdentity); isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator); } var userName = Environment.UserName; if (userName == null) { return null; } return GetPipeName(userName, isAdmin, compilerExeDirectory); } internal static string GetPipeName( string userName, bool isAdmin, string compilerExeDirectory) { // Normalize away trailing slashes. File APIs include / exclude this with no // discernable pattern. Easiest to normalize it here vs. auditing every caller // of this method. compilerExeDirectory = compilerExeDirectory.TrimEnd(Path.DirectorySeparatorChar); var pipeNameInput = $"{userName}.{isAdmin}.{compilerExeDirectory}"; using (var sha = SHA256.Create()) { var bytes = sha.ComputeHash(Encoding.UTF8.GetBytes(pipeNameInput)); return Convert.ToBase64String(bytes) .Replace("/", "_") .Replace("=", string.Empty); } } internal static bool WasServerMutexOpen(string mutexName) { try { if (PlatformInformation.IsRunningOnMono) { IServerMutex? mutex = null; bool createdNew = false; try { mutex = new ServerFileMutexPair(mutexName, false, out createdNew); return !createdNew; } finally { mutex?.Dispose(); } } else { return ServerNamedMutex.WasOpen(mutexName); } } catch { // In the case an exception occurred trying to open the Mutex then // the assumption is that it's not open. return false; } } internal static IServerMutex OpenOrCreateMutex(string name, out bool createdNew) { if (PlatformInformation.IsRunningOnMono) { return new ServerFileMutexPair(name, initiallyOwned: true, out createdNew); } else { return new ServerNamedMutex(name, out createdNew); } } internal static string GetServerMutexName(string pipeName) { return $"{pipeName}.server"; } internal static string GetClientMutexName(string pipeName) { return $"{pipeName}.client"; } /// <summary> /// Gets the value of the temporary path for the current environment assuming the working directory /// is <paramref name="workingDir"/>. This function must emulate <see cref="Path.GetTempPath"/> as /// closely as possible. /// </summary> public static string? GetTempPath(string? workingDir) { if (PlatformInformation.IsUnix) { // Unix temp path is fine: it does not use the working directory // (it uses ${TMPDIR} if set, otherwise, it returns /tmp) return Path.GetTempPath(); } var tmp = Environment.GetEnvironmentVariable("TMP"); if (Path.IsPathRooted(tmp)) { return tmp; } var temp = Environment.GetEnvironmentVariable("TEMP"); if (Path.IsPathRooted(temp)) { return temp; } if (!string.IsNullOrEmpty(workingDir)) { if (!string.IsNullOrEmpty(tmp)) { return Path.Combine(workingDir, tmp); } if (!string.IsNullOrEmpty(temp)) { return Path.Combine(workingDir, temp); } } var userProfile = Environment.GetEnvironmentVariable("USERPROFILE"); if (Path.IsPathRooted(userProfile)) { return userProfile; } return Environment.GetEnvironmentVariable("SYSTEMROOT"); } } internal interface IServerMutex : IDisposable { bool TryLock(int timeoutMs); bool IsDisposed { get; } } /// <summary> /// An interprocess mutex abstraction based on OS advisory locking (FileStream.Lock/Unlock). /// If multiple processes running as the same user create FileMutex instances with the same name, /// those instances will all point to the same file somewhere in a selected temporary directory. /// The TryLock method can be used to attempt to acquire the mutex, with Unlock or Dispose used to release. /// Unlike Win32 named mutexes, there is no mechanism for detecting an abandoned mutex. The file /// will simply revert to being unlocked but remain where it is. /// </summary> internal sealed class FileMutex : IDisposable { public readonly FileStream Stream; public readonly string FilePath; public bool IsLocked { get; private set; } internal static string GetMutexDirectory() { var tempPath = BuildServerConnection.GetTempPath(null); var result = Path.Combine(tempPath!, ".roslyn"); Directory.CreateDirectory(result); return result; } public FileMutex(string name) { FilePath = Path.Combine(GetMutexDirectory(), name); Stream = new FileStream(FilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); } public bool TryLock(int timeoutMs) { if (IsLocked) throw new InvalidOperationException("Lock already held"); var sw = Stopwatch.StartNew(); do { try { Stream.Lock(0, 0); IsLocked = true; return true; } catch (IOException) { // Lock currently held by someone else. // We want to sleep for a short period of time to ensure that other processes // have an opportunity to finish their work and relinquish the lock. // Spinning here (via Yield) would work but risks creating a priority // inversion if the lock is held by a lower-priority process. Thread.Sleep(1); } catch (Exception) { // Something else went wrong. return false; } } while (sw.ElapsedMilliseconds < timeoutMs); return false; } public void Unlock() { if (!IsLocked) return; Stream.Unlock(0, 0); IsLocked = false; } public void Dispose() { var wasLocked = IsLocked; if (wasLocked) Unlock(); Stream.Dispose(); // We do not delete the lock file here because there is no reliable way to perform a // 'delete if no one has the file open' operation atomically on *nix. This is a leak. } } internal sealed class ServerNamedMutex : IServerMutex { public readonly Mutex Mutex; public bool IsDisposed { get; private set; } public bool IsLocked { get; private set; } public ServerNamedMutex(string mutexName, out bool createdNew) { Mutex = new Mutex( initiallyOwned: true, name: mutexName, createdNew: out createdNew ); if (createdNew) IsLocked = true; } public static bool WasOpen(string mutexName) { Mutex? m = null; try { return Mutex.TryOpenExisting(mutexName, out m); } catch { // In the case an exception occurred trying to open the Mutex then // the assumption is that it's not open. return false; } finally { m?.Dispose(); } } public bool TryLock(int timeoutMs) { if (IsDisposed) throw new ObjectDisposedException("Mutex"); if (IsLocked) throw new InvalidOperationException("Lock already held"); return IsLocked = Mutex.WaitOne(timeoutMs); } public void Dispose() { if (IsDisposed) return; IsDisposed = true; try { if (IsLocked) Mutex.ReleaseMutex(); } finally { Mutex.Dispose(); IsLocked = false; } } } /// <summary> /// Approximates a named mutex with 'locked', 'unlocked' and 'abandoned' states. /// There is no reliable way to detect whether a mutex has been abandoned on some target platforms, /// so we use the AliveMutex to manually track whether the creator of a mutex is still running, /// while the HeldMutex represents the actual lock state of the mutex. /// </summary> internal sealed class ServerFileMutexPair : IServerMutex { public readonly FileMutex AliveMutex; public readonly FileMutex HeldMutex; public bool IsDisposed { get; private set; } public ServerFileMutexPair(string mutexName, bool initiallyOwned, out bool createdNew) { AliveMutex = new FileMutex(mutexName + "-alive"); HeldMutex = new FileMutex(mutexName + "-held"); createdNew = AliveMutex.TryLock(0); if (initiallyOwned && createdNew) { if (!TryLock(0)) throw new Exception("Failed to lock mutex after creating it"); } } public bool TryLock(int timeoutMs) { if (IsDisposed) throw new ObjectDisposedException("Mutex"); return HeldMutex.TryLock(timeoutMs); } public void Dispose() { if (IsDisposed) return; IsDisposed = true; try { HeldMutex.Unlock(); AliveMutex.Unlock(); } finally { AliveMutex.Dispose(); HeldMutex.Dispose(); } } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/Core/Portable/PEWriter/ManagedResource.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.Globalization; using System.IO; using System.Reflection.Metadata; using Microsoft.CodeAnalysis; using Roslyn.Utilities; namespace Microsoft.Cci { internal sealed class ManagedResource { private readonly Func<Stream>? _streamProvider; private readonly IFileReference? _fileReference; private readonly uint _offset; private readonly string _name; private readonly bool _isPublic; /// <summary> /// <paramref name="streamProvider"/> streamProvider callers will dispose result after use. /// <paramref name="streamProvider"/> and <paramref name="fileReference"/> are mutually exclusive. /// </summary> internal ManagedResource(string name, bool isPublic, Func<Stream>? streamProvider, IFileReference? fileReference, uint offset) { RoslynDebug.Assert(streamProvider == null ^ fileReference == null); _streamProvider = streamProvider; _name = name; _fileReference = fileReference; _offset = offset; _isPublic = isPublic; } public void WriteData(BlobBuilder resourceWriter) { if (_fileReference == null) { try { #nullable disable // Can '_streamProvider' be null? https://github.com/dotnet/roslyn/issues/39166 using (Stream stream = _streamProvider()) #nullable enable { if (stream == null) { throw new InvalidOperationException(CodeAnalysisResources.ResourceStreamProviderShouldReturnNonNullStream); } var count = (int)(stream.Length - stream.Position); resourceWriter.WriteInt32(count); int bytesWritten = resourceWriter.TryWriteBytes(stream, count); if (bytesWritten != count) { throw new EndOfStreamException( string.Format(CultureInfo.CurrentUICulture, CodeAnalysisResources.ResourceStreamEndedUnexpectedly, bytesWritten, count)); } resourceWriter.Align(8); } } catch (Exception e) { throw new ResourceException(_name, e); } } } public IFileReference? ExternalFile { get { return _fileReference; } } public uint Offset { get { return _offset; } } public IEnumerable<ICustomAttribute> Attributes { get { return SpecializedCollections.EmptyEnumerable<ICustomAttribute>(); } } public bool IsPublic { get { return _isPublic; } } public string Name { get { return _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. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection.Metadata; using Microsoft.CodeAnalysis; using Roslyn.Utilities; namespace Microsoft.Cci { internal sealed class ManagedResource { private readonly Func<Stream>? _streamProvider; private readonly IFileReference? _fileReference; private readonly uint _offset; private readonly string _name; private readonly bool _isPublic; /// <summary> /// <paramref name="streamProvider"/> streamProvider callers will dispose result after use. /// <paramref name="streamProvider"/> and <paramref name="fileReference"/> are mutually exclusive. /// </summary> internal ManagedResource(string name, bool isPublic, Func<Stream>? streamProvider, IFileReference? fileReference, uint offset) { RoslynDebug.Assert(streamProvider == null ^ fileReference == null); _streamProvider = streamProvider; _name = name; _fileReference = fileReference; _offset = offset; _isPublic = isPublic; } public void WriteData(BlobBuilder resourceWriter) { if (_fileReference == null) { try { #nullable disable // Can '_streamProvider' be null? https://github.com/dotnet/roslyn/issues/39166 using (Stream stream = _streamProvider()) #nullable enable { if (stream == null) { throw new InvalidOperationException(CodeAnalysisResources.ResourceStreamProviderShouldReturnNonNullStream); } var count = (int)(stream.Length - stream.Position); resourceWriter.WriteInt32(count); int bytesWritten = resourceWriter.TryWriteBytes(stream, count); if (bytesWritten != count) { throw new EndOfStreamException( string.Format(CultureInfo.CurrentUICulture, CodeAnalysisResources.ResourceStreamEndedUnexpectedly, bytesWritten, count)); } resourceWriter.Align(8); } } catch (Exception e) { throw new ResourceException(_name, e); } } } public IFileReference? ExternalFile { get { return _fileReference; } } public uint Offset { get { return _offset; } } public IEnumerable<ICustomAttribute> Attributes { get { return SpecializedCollections.EmptyEnumerable<ICustomAttribute>(); } } public bool IsPublic { get { return _isPublic; } } public string Name { get { return _name; } } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/Test/Resources/Core/MetadataTests/InterfaceAndClass/CSInterfaces01.dll
MZ@ !L!This program cannot be run in DOS mode. $PELxN! ' @@ @&O@`  H.text$  `.rsrc@ @@.reloc `@B'HP |BSJB v4.0.30319l#~#Strings#US#GUID#BlobW %3 SLZLLLiL"+" 2":" n Vv V{ V V %+3? E J E J 7+ 7U7^7e7u7}7;BILILO;X__ILIeeIL}ILILIL)19A  ..#  $ PP)P CX X l<Module>CSInterfaces01.dllEFooMetadataDFoo`1ICSPropICSGen`2mscorlibSystemEnumTMulticastDelegateVvalue__ZeroOneTwoThree.ctorInvokeIAsyncResultAsyncCallbackBeginInvokeEndInvokeget_ReadOnlyPropset_WriteOnlyPropget_ReadWritePropset_ReadWritePropReadOnlyPropWriteOnlyPropReadWritePropM01objectmethodp1p2callbackresultvaluearyParamArrayAttributep3System.Runtime.InteropServicesOutAttributeSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttributeCSInterfaces01 &i1CmX~z\V4        (         TWrapNonExceptionThrows&' '_CorDllMainmscoree.dll% @0HX@dd4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0HInternalNameCSInterfaces01.dll(LegalCopyright POriginalFilenameCSInterfaces01.dll4ProductVersion0.0.0.08Assembly Version0.0.0.0 7
MZ@ !L!This program cannot be run in DOS mode. $PELxN! ' @@ @&O@`  H.text$  `.rsrc@ @@.reloc `@B'HP |BSJB v4.0.30319l#~#Strings#US#GUID#BlobW %3 SLZLLLiL"+" 2":" n Vv V{ V V %+3? E J E J 7+ 7U7^7e7u7}7;BILILO;X__ILIeeIL}ILILIL)19A  ..#  $ PP)P CX X l<Module>CSInterfaces01.dllEFooMetadataDFoo`1ICSPropICSGen`2mscorlibSystemEnumTMulticastDelegateVvalue__ZeroOneTwoThree.ctorInvokeIAsyncResultAsyncCallbackBeginInvokeEndInvokeget_ReadOnlyPropset_WriteOnlyPropget_ReadWritePropset_ReadWritePropReadOnlyPropWriteOnlyPropReadWritePropM01objectmethodp1p2callbackresultvaluearyParamArrayAttributep3System.Runtime.InteropServicesOutAttributeSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttributeCSInterfaces01 &i1CmX~z\V4        (         TWrapNonExceptionThrows&' '_CorDllMainmscoree.dll% @0HX@dd4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfo000004b0,FileDescription 0FileVersion0.0.0.0HInternalNameCSInterfaces01.dll(LegalCopyright POriginalFilenameCSInterfaces01.dll4ProductVersion0.0.0.08Assembly Version0.0.0.0 7
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Test/Syntax/Syntax/TrackNodeTests.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 Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using InternalSyntax = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class TrackNodeTests { [Fact] public void TestGetCurrentNodeAfterTrackNodesReturnsCurrentNode() { var expr = SyntaxFactory.ParseExpression("a + b"); var a = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a"); var trackedExpr = expr.TrackNodes(a); var currentA = trackedExpr.GetCurrentNode(a); Assert.NotNull(currentA); Assert.Equal("a", currentA.ToString()); } [Fact] public void TestGetCurrentNodesAfterTrackNodesReturnsSingletonSequence() { var expr = SyntaxFactory.ParseExpression("a + b"); var a = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a"); var trackedExpr = expr.TrackNodes(a); var currentAs = trackedExpr.GetCurrentNodes(a); Assert.NotNull(currentAs); Assert.Equal(1, currentAs.Count()); Assert.Equal("a", currentAs.ElementAt(0).ToString()); } [Fact] public void TestGetCurrentNodeWithoutTrackNodesReturnsNull() { var expr = SyntaxFactory.ParseExpression("a + b"); var a = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a"); var currentA = expr.GetCurrentNode(a); Assert.Null(currentA); } [Fact] public void TestGetCurrentNodesWithoutTrackNodesReturnsEmptySequence() { var expr = SyntaxFactory.ParseExpression("a + b"); var a = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a"); var currentAs = expr.GetCurrentNodes(a); Assert.NotNull(currentAs); Assert.Equal(0, currentAs.Count()); } [Fact] public void TestGetCurrentNodeAfterEditReturnsCurrentNode() { var expr = SyntaxFactory.ParseExpression("a + b"); var originalA = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a"); var trackedExpr = expr.TrackNodes(originalA); var currentA = trackedExpr.GetCurrentNode(originalA); var newA = currentA.WithLeadingTrivia(SyntaxFactory.Comment("/* ayup */")); var replacedExpr = trackedExpr.ReplaceNode(currentA, newA); var latestA = replacedExpr.GetCurrentNode(originalA); Assert.NotNull(latestA); Assert.NotSame(latestA, newA); // not the same reference Assert.Equal(newA.ToFullString(), latestA.ToFullString()); } [Fact] public void TestGetCurrentNodeAfterEditReturnsSingletonSequence() { var expr = SyntaxFactory.ParseExpression("a + b"); var originalA = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a"); var trackedExpr = expr.TrackNodes(originalA); var currentA = trackedExpr.GetCurrentNode(originalA); var newA = currentA.WithLeadingTrivia(SyntaxFactory.Comment("/* ayup */")); var replacedExpr = trackedExpr.ReplaceNode(currentA, newA); var latestAs = replacedExpr.GetCurrentNodes(originalA); Assert.NotNull(latestAs); Assert.Equal(1, latestAs.Count()); Assert.Equal(newA.ToFullString(), latestAs.ElementAt(0).ToFullString()); } [WorkItem(1070667, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070667")] [Fact] public void TestGetCurrentNodeAfterRemovalReturnsNull() { var expr = SyntaxFactory.ParseExpression("a + b"); var originalA = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a"); var trackedExpr = expr.TrackNodes(originalA); var currentA = trackedExpr.GetCurrentNode(originalA); var replacedExpr = trackedExpr.ReplaceNode(currentA, SyntaxFactory.IdentifierName("c")); var latestA = replacedExpr.GetCurrentNode(originalA); Assert.Null(latestA); } [Fact] public void TestGetCurrentNodesAfterRemovalEmptySequence() { var expr = SyntaxFactory.ParseExpression("a + b"); var originalA = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a"); var trackedExpr = expr.TrackNodes(originalA); var currentA = trackedExpr.GetCurrentNode(originalA); var replacedExpr = trackedExpr.ReplaceNode(currentA, SyntaxFactory.IdentifierName("c")); var latestAs = replacedExpr.GetCurrentNodes(originalA); Assert.NotNull(latestAs); Assert.Equal(0, latestAs.Count()); } [Fact] public void TestGetCurrentNodeAfterAddingMultipleThrows() { var expr = SyntaxFactory.ParseExpression("a + b"); var originalA = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a"); var trackedExpr = expr.TrackNodes(originalA); var currentA = trackedExpr.GetCurrentNode(originalA); // replace all identifiers with same 'a' var replacedExpr = trackedExpr.ReplaceNodes(trackedExpr.DescendantNodes().OfType<IdentifierNameSyntax>(), (original, changed) => currentA); Assert.Throws<InvalidOperationException>(() => replacedExpr.GetCurrentNode(originalA)); } [Fact] public void TestGetCurrentNodeAfterAddingMultipleReturnsMultiple() { var expr = SyntaxFactory.ParseExpression("a + b"); var originalA = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a"); var trackedExpr = expr.TrackNodes(originalA); var currentA = trackedExpr.GetCurrentNode(originalA); // replace all identifiers with same 'a' var replacedExpr = trackedExpr.ReplaceNodes(trackedExpr.DescendantNodes().OfType<IdentifierNameSyntax>(), (original, changed) => currentA); var nodes = replacedExpr.GetCurrentNodes(originalA).ToList(); Assert.Equal(2, nodes.Count); Assert.Equal("a", nodes[0].ToString()); Assert.Equal("a", nodes[1].ToString()); } [Fact] public void TestTrackNodesWithMultipleTracksAllNodes() { var expr = SyntaxFactory.ParseExpression("a + b + c"); var ids = expr.DescendantNodes().OfType<IdentifierNameSyntax>().ToList(); var trackedExpr = expr.TrackNodes(ids); Assert.Equal(3, ids.Count); foreach (var id in ids) { var currentId = trackedExpr.GetCurrentNode(id); Assert.NotNull(currentId); Assert.NotSame(id, currentId); Assert.Equal(id.ToString(), currentId.ToString()); } } [Fact] public void TestTrackNodesWithNoNodesTracksNothing() { var expr = SyntaxFactory.ParseExpression("a + b + c"); var ids = expr.DescendantNodes().OfType<IdentifierNameSyntax>().ToList(); var trackedExpr = expr.TrackNodes(); Assert.Equal(3, ids.Count); foreach (var id in ids) { var currentId = trackedExpr.GetCurrentNode(id); Assert.Null(currentId); } } [Fact] public void TestTrackNodeThatIsNotInTheSubtreeThrows() { var expr = SyntaxFactory.ParseExpression("a + b"); Assert.Throws<ArgumentException>(() => expr.TrackNodes(SyntaxFactory.IdentifierName("c"))); } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; using InternalSyntax = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class TrackNodeTests { [Fact] public void TestGetCurrentNodeAfterTrackNodesReturnsCurrentNode() { var expr = SyntaxFactory.ParseExpression("a + b"); var a = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a"); var trackedExpr = expr.TrackNodes(a); var currentA = trackedExpr.GetCurrentNode(a); Assert.NotNull(currentA); Assert.Equal("a", currentA.ToString()); } [Fact] public void TestGetCurrentNodesAfterTrackNodesReturnsSingletonSequence() { var expr = SyntaxFactory.ParseExpression("a + b"); var a = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a"); var trackedExpr = expr.TrackNodes(a); var currentAs = trackedExpr.GetCurrentNodes(a); Assert.NotNull(currentAs); Assert.Equal(1, currentAs.Count()); Assert.Equal("a", currentAs.ElementAt(0).ToString()); } [Fact] public void TestGetCurrentNodeWithoutTrackNodesReturnsNull() { var expr = SyntaxFactory.ParseExpression("a + b"); var a = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a"); var currentA = expr.GetCurrentNode(a); Assert.Null(currentA); } [Fact] public void TestGetCurrentNodesWithoutTrackNodesReturnsEmptySequence() { var expr = SyntaxFactory.ParseExpression("a + b"); var a = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a"); var currentAs = expr.GetCurrentNodes(a); Assert.NotNull(currentAs); Assert.Equal(0, currentAs.Count()); } [Fact] public void TestGetCurrentNodeAfterEditReturnsCurrentNode() { var expr = SyntaxFactory.ParseExpression("a + b"); var originalA = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a"); var trackedExpr = expr.TrackNodes(originalA); var currentA = trackedExpr.GetCurrentNode(originalA); var newA = currentA.WithLeadingTrivia(SyntaxFactory.Comment("/* ayup */")); var replacedExpr = trackedExpr.ReplaceNode(currentA, newA); var latestA = replacedExpr.GetCurrentNode(originalA); Assert.NotNull(latestA); Assert.NotSame(latestA, newA); // not the same reference Assert.Equal(newA.ToFullString(), latestA.ToFullString()); } [Fact] public void TestGetCurrentNodeAfterEditReturnsSingletonSequence() { var expr = SyntaxFactory.ParseExpression("a + b"); var originalA = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a"); var trackedExpr = expr.TrackNodes(originalA); var currentA = trackedExpr.GetCurrentNode(originalA); var newA = currentA.WithLeadingTrivia(SyntaxFactory.Comment("/* ayup */")); var replacedExpr = trackedExpr.ReplaceNode(currentA, newA); var latestAs = replacedExpr.GetCurrentNodes(originalA); Assert.NotNull(latestAs); Assert.Equal(1, latestAs.Count()); Assert.Equal(newA.ToFullString(), latestAs.ElementAt(0).ToFullString()); } [WorkItem(1070667, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1070667")] [Fact] public void TestGetCurrentNodeAfterRemovalReturnsNull() { var expr = SyntaxFactory.ParseExpression("a + b"); var originalA = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a"); var trackedExpr = expr.TrackNodes(originalA); var currentA = trackedExpr.GetCurrentNode(originalA); var replacedExpr = trackedExpr.ReplaceNode(currentA, SyntaxFactory.IdentifierName("c")); var latestA = replacedExpr.GetCurrentNode(originalA); Assert.Null(latestA); } [Fact] public void TestGetCurrentNodesAfterRemovalEmptySequence() { var expr = SyntaxFactory.ParseExpression("a + b"); var originalA = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a"); var trackedExpr = expr.TrackNodes(originalA); var currentA = trackedExpr.GetCurrentNode(originalA); var replacedExpr = trackedExpr.ReplaceNode(currentA, SyntaxFactory.IdentifierName("c")); var latestAs = replacedExpr.GetCurrentNodes(originalA); Assert.NotNull(latestAs); Assert.Equal(0, latestAs.Count()); } [Fact] public void TestGetCurrentNodeAfterAddingMultipleThrows() { var expr = SyntaxFactory.ParseExpression("a + b"); var originalA = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a"); var trackedExpr = expr.TrackNodes(originalA); var currentA = trackedExpr.GetCurrentNode(originalA); // replace all identifiers with same 'a' var replacedExpr = trackedExpr.ReplaceNodes(trackedExpr.DescendantNodes().OfType<IdentifierNameSyntax>(), (original, changed) => currentA); Assert.Throws<InvalidOperationException>(() => replacedExpr.GetCurrentNode(originalA)); } [Fact] public void TestGetCurrentNodeAfterAddingMultipleReturnsMultiple() { var expr = SyntaxFactory.ParseExpression("a + b"); var originalA = expr.DescendantNodes().OfType<IdentifierNameSyntax>().First(n => n.Identifier.Text == "a"); var trackedExpr = expr.TrackNodes(originalA); var currentA = trackedExpr.GetCurrentNode(originalA); // replace all identifiers with same 'a' var replacedExpr = trackedExpr.ReplaceNodes(trackedExpr.DescendantNodes().OfType<IdentifierNameSyntax>(), (original, changed) => currentA); var nodes = replacedExpr.GetCurrentNodes(originalA).ToList(); Assert.Equal(2, nodes.Count); Assert.Equal("a", nodes[0].ToString()); Assert.Equal("a", nodes[1].ToString()); } [Fact] public void TestTrackNodesWithMultipleTracksAllNodes() { var expr = SyntaxFactory.ParseExpression("a + b + c"); var ids = expr.DescendantNodes().OfType<IdentifierNameSyntax>().ToList(); var trackedExpr = expr.TrackNodes(ids); Assert.Equal(3, ids.Count); foreach (var id in ids) { var currentId = trackedExpr.GetCurrentNode(id); Assert.NotNull(currentId); Assert.NotSame(id, currentId); Assert.Equal(id.ToString(), currentId.ToString()); } } [Fact] public void TestTrackNodesWithNoNodesTracksNothing() { var expr = SyntaxFactory.ParseExpression("a + b + c"); var ids = expr.DescendantNodes().OfType<IdentifierNameSyntax>().ToList(); var trackedExpr = expr.TrackNodes(); Assert.Equal(3, ids.Count); foreach (var id in ids) { var currentId = trackedExpr.GetCurrentNode(id); Assert.Null(currentId); } } [Fact] public void TestTrackNodeThatIsNotInTheSubtreeThrows() { var expr = SyntaxFactory.ParseExpression("a + b"); Assert.Throws<ArgumentException>(() => expr.TrackNodes(SyntaxFactory.IdentifierName("c"))); } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/Core/Portable/Collections/IdentifierCollection.Collection.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class IdentifierCollection { private abstract class CollectionBase : ICollection<string> { protected readonly IdentifierCollection IdentifierCollection; private int _count = -1; protected CollectionBase(IdentifierCollection identifierCollection) { this.IdentifierCollection = identifierCollection; } public abstract bool Contains(string item); public void CopyTo(string[] array, int arrayIndex) { using (var enumerator = this.GetEnumerator()) { while (arrayIndex < array.Length && enumerator.MoveNext()) { array[arrayIndex] = enumerator.Current; arrayIndex++; } } } public int Count { get { if (_count == -1) { _count = this.IdentifierCollection._map.Values.Sum(o => o is string ? 1 : ((ISet<string>)o).Count); } return _count; } } public bool IsReadOnly => true; public IEnumerator<string> GetEnumerator() { foreach (var obj in this.IdentifierCollection._map.Values) { var strs = obj as HashSet<string>; if (strs != null) { foreach (var s in strs) { yield return s; } } else { yield return (string)obj; } } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #region Unsupported public void Add(string item) { throw new NotSupportedException(); } public void Clear() { throw new NotSupportedException(); } public bool Remove(string item) { throw new NotSupportedException(); } #endregion } private sealed class CaseSensitiveCollection : CollectionBase { public CaseSensitiveCollection(IdentifierCollection identifierCollection) : base(identifierCollection) { } public override bool Contains(string item) => IdentifierCollection.CaseSensitiveContains(item); } private sealed class CaseInsensitiveCollection : CollectionBase { public CaseInsensitiveCollection(IdentifierCollection identifierCollection) : base(identifierCollection) { } public override bool Contains(string item) => IdentifierCollection.CaseInsensitiveContains(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.Linq; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal partial class IdentifierCollection { private abstract class CollectionBase : ICollection<string> { protected readonly IdentifierCollection IdentifierCollection; private int _count = -1; protected CollectionBase(IdentifierCollection identifierCollection) { this.IdentifierCollection = identifierCollection; } public abstract bool Contains(string item); public void CopyTo(string[] array, int arrayIndex) { using (var enumerator = this.GetEnumerator()) { while (arrayIndex < array.Length && enumerator.MoveNext()) { array[arrayIndex] = enumerator.Current; arrayIndex++; } } } public int Count { get { if (_count == -1) { _count = this.IdentifierCollection._map.Values.Sum(o => o is string ? 1 : ((ISet<string>)o).Count); } return _count; } } public bool IsReadOnly => true; public IEnumerator<string> GetEnumerator() { foreach (var obj in this.IdentifierCollection._map.Values) { var strs = obj as HashSet<string>; if (strs != null) { foreach (var s in strs) { yield return s; } } else { yield return (string)obj; } } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #region Unsupported public void Add(string item) { throw new NotSupportedException(); } public void Clear() { throw new NotSupportedException(); } public bool Remove(string item) { throw new NotSupportedException(); } #endregion } private sealed class CaseSensitiveCollection : CollectionBase { public CaseSensitiveCollection(IdentifierCollection identifierCollection) : base(identifierCollection) { } public override bool Contains(string item) => IdentifierCollection.CaseSensitiveContains(item); } private sealed class CaseInsensitiveCollection : CollectionBase { public CaseInsensitiveCollection(IdentifierCollection identifierCollection) : base(identifierCollection) { } public override bool Contains(string item) => IdentifierCollection.CaseInsensitiveContains(item); } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Features/LanguageServer/ProtocolUnitTests/Ordering/NonLSPSolutionRequestHandlerProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.VisualStudio.LanguageServer.Protocol; using Xunit; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.RequestOrdering { [Shared, ExportLspRequestHandlerProvider, PartNotDiscoverable] [ProvidesMethod(NonLSPSolutionRequestHandler.MethodName)] internal class NonLSPSolutionRequestHandlerProvider : AbstractRequestHandlerProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public NonLSPSolutionRequestHandlerProvider() { } public override ImmutableArray<IRequestHandler> CreateRequestHandlers() { return ImmutableArray.Create<IRequestHandler>(new NonLSPSolutionRequestHandler()); } } internal class NonLSPSolutionRequestHandler : IRequestHandler<TestRequest, TestResponse> { public const string MethodName = nameof(NonLSPSolutionRequestHandler); public string Method => MethodName; public bool MutatesSolutionState => false; public bool RequiresLSPSolution => false; public TextDocumentIdentifier GetTextDocumentIdentifier(TestRequest request) => null; public Task<TestResponse> HandleRequestAsync(TestRequest request, RequestContext context, CancellationToken cancellationToken) { Assert.Null(context.Solution); return Task.FromResult(new TestResponse()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServer.Handler; using Microsoft.VisualStudio.LanguageServer.Protocol; using Xunit; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.RequestOrdering { [Shared, ExportLspRequestHandlerProvider, PartNotDiscoverable] [ProvidesMethod(NonLSPSolutionRequestHandler.MethodName)] internal class NonLSPSolutionRequestHandlerProvider : AbstractRequestHandlerProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public NonLSPSolutionRequestHandlerProvider() { } public override ImmutableArray<IRequestHandler> CreateRequestHandlers() { return ImmutableArray.Create<IRequestHandler>(new NonLSPSolutionRequestHandler()); } } internal class NonLSPSolutionRequestHandler : IRequestHandler<TestRequest, TestResponse> { public const string MethodName = nameof(NonLSPSolutionRequestHandler); public string Method => MethodName; public bool MutatesSolutionState => false; public bool RequiresLSPSolution => false; public TextDocumentIdentifier GetTextDocumentIdentifier(TestRequest request) => null; public Task<TestResponse> HandleRequestAsync(TestRequest request, RequestContext context, CancellationToken cancellationToken) { Assert.Null(context.Solution); return Task.FromResult(new TestResponse()); } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/CSharpTest/QuickInfo/DiagnosticAnalyzerQuickInfoSourceTests.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.CSharp; using Microsoft.CodeAnalysis.CSharp.QuickInfo; using Microsoft.CodeAnalysis.CSharp.RemoveUnusedMembers; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Diagnostics.CSharp; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.QuickInfo; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.QuickInfo { [UseExportProvider] public class DiagnosticAnalyzerQuickInfoSourceTests { [WorkItem(46604, "https://github.com/dotnet/roslyn/issues/46604")] [WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ErrorTitleIsShownOnDisablePragma() { await TestInMethodAsync( @" #pragma warning disable CS0219$$ var i = 0; #pragma warning restore CS0219 ", GetFormattedErrorTitle(ErrorCode.WRN_UnreferencedVarAssg)); } [WorkItem(46604, "https://github.com/dotnet/roslyn/issues/46604")] [WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ErrorTitleIsShownOnRestorePragma() { await TestInMethodAsync( @" #pragma warning disable CS0219 var i = 0; #pragma warning restore CS0219$$ ", GetFormattedErrorTitle(ErrorCode.WRN_UnreferencedVarAssg)); } [WorkItem(46604, "https://github.com/dotnet/roslyn/issues/46604")] [WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task DisabledWarningNotExistingInCodeIsDisplayedByTitleWithoutCodeDetails() { await TestInMethodAsync( @" #pragma warning disable CS0219$$ ", GetFormattedErrorTitle(ErrorCode.WRN_UnreferencedVarAssg)); } [WorkItem(49102, "https://github.com/dotnet/roslyn/issues/49102")] [WpfTheory, Trait(Traits.Feature, Traits.Features.QuickInfo)] [InlineData("CS0219$$")] [InlineData("219$$")] [InlineData("0219$$")] [InlineData("CS02$$19")] [InlineData("2$$19")] [InlineData("02$$19")] public async Task PragmaWarningCompilerWarningSyntaxKinds(string warning) { // Reference: https://docs.microsoft.com/en-US/dotnet/csharp/language-reference/preprocessor-directives/preprocessor-pragma-warning // "A comma-separated list of warning numbers. The "CS" prefix is optional." await TestInMethodAsync( @$" #pragma warning disable {warning} ", GetFormattedErrorTitle(ErrorCode.WRN_UnreferencedVarAssg)); } [WorkItem(49102, "https://github.com/dotnet/roslyn/issues/49102")] [WpfTheory, Trait(Traits.Feature, Traits.Features.QuickInfo)] [InlineData("#pragma warning $$CS0219", null)] [InlineData("#pragma warning disable$$", null)] [InlineData("#pragma warning disable $$true", null)] [InlineData("#pragma warning disable $$219.0", (int)ErrorCode.WRN_UnreferencedVarAssg)] [InlineData("#pragma warning disable $$219.5", (int)ErrorCode.WRN_UnreferencedVarAssg)] public async Task PragmaWarningDoesNotThrowInBrokenSyntax(string pragma, int? errorCode) { var expectedDescription = errorCode is int errorCodeValue ? GetFormattedErrorTitle((ErrorCode)errorCodeValue) : ""; await TestInMethodAsync( @$" {pragma} ", expectedDescription); } [WorkItem(46604, "https://github.com/dotnet/roslyn/issues/46604")] [WpfTheory, Trait(Traits.Feature, Traits.Features.QuickInfo)] [InlineData("#pragma warning disable $$CS0162", (int)ErrorCode.WRN_UnreachableCode)] [InlineData("#pragma warning disable $$CS0162, CS0219", (int)ErrorCode.WRN_UnreachableCode)] [InlineData("#pragma warning disable $$CS0219", (int)ErrorCode.WRN_UnreferencedVarAssg)] [InlineData("#pragma warning disable CS0162, $$CS0219", (int)ErrorCode.WRN_UnreferencedVarAssg)] [InlineData("#pragma warning disable CS0162, CS0219$$", (int)ErrorCode.WRN_UnreferencedVarAssg)] [InlineData("#pragma warning $$disable CS0162, CS0219", (int)ErrorCode.WRN_UnreachableCode)] [InlineData("#pragma warning $$disable CS0219, CS0162", (int)ErrorCode.WRN_UnreferencedVarAssg)] public async Task MultipleWarningsAreDisplayedDependingOnCursorPosition(string pragma, int errorCode) { await TestInMethodAsync( @$" {pragma} return; var i = 0; ", GetFormattedErrorTitle((ErrorCode)errorCode)); } [WorkItem(46604, "https://github.com/dotnet/roslyn/issues/46604")] [WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ErrorTitleIsShwonInSupressMessageAttribute() { await TestAsync( @" using System.Diagnostics.CodeAnalysis; namespace T { [SuppressMessage(""CodeQuality"", ""IDE0051$$"")] public class C { private int _i; } } ", GetFormattedIDEAnalyzerTitle(51, nameof(AnalyzersResources.Remove_unused_private_members)), ImmutableArray<TextSpan>.Empty); } [WorkItem(46604, "https://github.com/dotnet/roslyn/issues/46604")] [WpfTheory, Trait(Traits.Feature, Traits.Features.QuickInfo)] [InlineData(@"[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(""CodeQuality"", ""IDE0051$$"")]", true)] [InlineData(@"[System.Diagnostics.CodeAnalysis.SuppressMessage(""CodeQuality"", ""IDE0051$$"")]", true)] [InlineData(@"[System.Diagnostics.CodeAnalysis.SuppressMessage(""CodeQuality$$"", ""IDE0051"")]", false)] [InlineData(@"[System.Diagnostics.CodeAnalysis.SuppressMessage(""CodeQuality"", ""IDE0051"", Justification = ""WIP$$"")]", false)] [InlineData(@"[System.Diagnostics.CodeAnalysis.SuppressMessage$$(""CodeQuality"", ""IDE0051"")]", false)] [InlineData(@"[SuppressMessage(""CodeQuality"", ""$$IDE0051"")]", true)] [InlineData(@"[SuppressMessage(""CodeQuality"", ""$$IDE0051: Remove unused private member"")]", true)] [InlineData(@"[SuppressMessage(category: ""CodeQuality"", checkId$$: ""IDE0051: Remove unused private member"")]", true)] [InlineData(@"[SuppressMessage(category: ""CodeQuality"", $$checkId: ""IDE0051: Remove unused private member"")]", true)] [InlineData(@"[SuppressMessage(checkId$$: ""IDE0051: Remove unused private member"", category: ""CodeQuality"")]", true)] [InlineData(@"[SuppressMessage(checkId: ""IDE0051: Remove unused private member"", category$$: ""CodeQuality"")]", false)] [InlineData(@"[SuppressMessage(""CodeQuality"", DiagnosticIds.IDE0051 +$$ "": Remove unused private member"")]", true)] [InlineData(@"[SuppressMessage(""CodeQuality"", """" + (DiagnosticIds.IDE0051 +$$ "": Remove unused private member""))]", true)] [InlineData(@"[SuppressMessage(category: ""CodeQuality"", checkId$$: DiagnosticIds.IDE0051 + "": Remove unused private member"")]", true)] // False negative: Aliased attribute is not supported [InlineData(@"[SM(""CodeQuality"", ""IDE0051$$""", false)] public async Task QuickInfoSuppressMessageAttributeUseCases(string suppressMessageAttribute, bool shouldShowQuickInfo) { var description = shouldShowQuickInfo ? GetFormattedIDEAnalyzerTitle(51, nameof(AnalyzersResources.Remove_unused_private_members)) : null; await TestAsync( @$" using System.Diagnostics.CodeAnalysis; using SM = System.Diagnostics.CodeAnalysis.SuppressMessageAttribute; namespace T {{ public static class DiagnosticIds {{ public const string IDE0051 = ""IDE0051""; }} {suppressMessageAttribute} public class C {{ private int _i; }} }} ", description, ImmutableArray<TextSpan>.Empty); } protected static async Task AssertContentIsAsync(TestWorkspace workspace, Document document, int position, string expectedDescription, ImmutableArray<TextSpan> relatedSpans) { var info = await GetQuickinfo(workspace, document, position); var description = info?.Sections.FirstOrDefault(s => s.Kind == QuickInfoSectionKinds.Description); Assert.NotNull(description); Assert.Equal(expectedDescription, description.Text); Assert.Collection(relatedSpans, info.RelatedSpans.Select(actualSpan => new Action<TextSpan>(expectedSpan => Assert.Equal(expectedSpan, actualSpan))).ToArray()); } private static async Task<QuickInfoItem> GetQuickinfo(TestWorkspace workspace, Document document, int position) { var diagnosticAnalyzerService = workspace.ExportProvider.GetExportedValue<IDiagnosticAnalyzerService>(); var provider = new CSharpDiagnosticAnalyzerQuickInfoProvider(diagnosticAnalyzerService); var info = await provider.GetQuickInfoAsync(new QuickInfoContext(document, position, CancellationToken.None)); return info; } protected static async Task AssertNoContentAsync(TestWorkspace workspace, Document document, int position) { var info = await GetQuickinfo(workspace, document, position); Assert.Null(info); } protected static async Task TestAsync( string code, string expectedDescription, ImmutableArray<TextSpan> relatedSpans, CSharpParseOptions parseOptions = null) { using var workspace = TestWorkspace.CreateCSharp(code, parseOptions); var analyzerReference = new AnalyzerImageReference(ImmutableArray.Create<DiagnosticAnalyzer>( new CSharpCompilerDiagnosticAnalyzer(), new CSharpRemoveUnusedMembersDiagnosticAnalyzer())); workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference })); var testDocument = workspace.Documents.Single(); var position = testDocument.CursorPosition.Value; var document = workspace.CurrentSolution.Projects.First().Documents.First(); if (string.IsNullOrEmpty(expectedDescription)) { await AssertNoContentAsync(workspace, document, position); } else { await AssertContentIsAsync(workspace, document, position, expectedDescription, relatedSpans); } } private static string GetFormattedErrorTitle(ErrorCode errorCode) { var localizable = MessageProvider.Instance.GetTitle((int)errorCode); return $"CS{(int)errorCode:0000}: {localizable}"; } private static string GetFormattedIDEAnalyzerTitle(int ideDiagnosticId, string nameOfLocalizableStringResource) { var localizable = new LocalizableResourceString(nameOfLocalizableStringResource, AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); return $"IDE{ideDiagnosticId:0000}: {localizable}"; } protected static Task TestInClassAsync(string code, string expectedDescription, params TextSpan[] relatedSpans) => TestAsync( @"class C {" + code + "}", expectedDescription, relatedSpans.ToImmutableArray()); protected static Task TestInMethodAsync(string code, string expectedDescription, params TextSpan[] relatedSpans) => TestInClassAsync( @"void M() {" + code + "}", expectedDescription, relatedSpans); } }
// Licensed to the .NET Foundation under one or more 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.CSharp; using Microsoft.CodeAnalysis.CSharp.QuickInfo; using Microsoft.CodeAnalysis.CSharp.RemoveUnusedMembers; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Diagnostics.CSharp; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.QuickInfo; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.QuickInfo { [UseExportProvider] public class DiagnosticAnalyzerQuickInfoSourceTests { [WorkItem(46604, "https://github.com/dotnet/roslyn/issues/46604")] [WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ErrorTitleIsShownOnDisablePragma() { await TestInMethodAsync( @" #pragma warning disable CS0219$$ var i = 0; #pragma warning restore CS0219 ", GetFormattedErrorTitle(ErrorCode.WRN_UnreferencedVarAssg)); } [WorkItem(46604, "https://github.com/dotnet/roslyn/issues/46604")] [WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ErrorTitleIsShownOnRestorePragma() { await TestInMethodAsync( @" #pragma warning disable CS0219 var i = 0; #pragma warning restore CS0219$$ ", GetFormattedErrorTitle(ErrorCode.WRN_UnreferencedVarAssg)); } [WorkItem(46604, "https://github.com/dotnet/roslyn/issues/46604")] [WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task DisabledWarningNotExistingInCodeIsDisplayedByTitleWithoutCodeDetails() { await TestInMethodAsync( @" #pragma warning disable CS0219$$ ", GetFormattedErrorTitle(ErrorCode.WRN_UnreferencedVarAssg)); } [WorkItem(49102, "https://github.com/dotnet/roslyn/issues/49102")] [WpfTheory, Trait(Traits.Feature, Traits.Features.QuickInfo)] [InlineData("CS0219$$")] [InlineData("219$$")] [InlineData("0219$$")] [InlineData("CS02$$19")] [InlineData("2$$19")] [InlineData("02$$19")] public async Task PragmaWarningCompilerWarningSyntaxKinds(string warning) { // Reference: https://docs.microsoft.com/en-US/dotnet/csharp/language-reference/preprocessor-directives/preprocessor-pragma-warning // "A comma-separated list of warning numbers. The "CS" prefix is optional." await TestInMethodAsync( @$" #pragma warning disable {warning} ", GetFormattedErrorTitle(ErrorCode.WRN_UnreferencedVarAssg)); } [WorkItem(49102, "https://github.com/dotnet/roslyn/issues/49102")] [WpfTheory, Trait(Traits.Feature, Traits.Features.QuickInfo)] [InlineData("#pragma warning $$CS0219", null)] [InlineData("#pragma warning disable$$", null)] [InlineData("#pragma warning disable $$true", null)] [InlineData("#pragma warning disable $$219.0", (int)ErrorCode.WRN_UnreferencedVarAssg)] [InlineData("#pragma warning disable $$219.5", (int)ErrorCode.WRN_UnreferencedVarAssg)] public async Task PragmaWarningDoesNotThrowInBrokenSyntax(string pragma, int? errorCode) { var expectedDescription = errorCode is int errorCodeValue ? GetFormattedErrorTitle((ErrorCode)errorCodeValue) : ""; await TestInMethodAsync( @$" {pragma} ", expectedDescription); } [WorkItem(46604, "https://github.com/dotnet/roslyn/issues/46604")] [WpfTheory, Trait(Traits.Feature, Traits.Features.QuickInfo)] [InlineData("#pragma warning disable $$CS0162", (int)ErrorCode.WRN_UnreachableCode)] [InlineData("#pragma warning disable $$CS0162, CS0219", (int)ErrorCode.WRN_UnreachableCode)] [InlineData("#pragma warning disable $$CS0219", (int)ErrorCode.WRN_UnreferencedVarAssg)] [InlineData("#pragma warning disable CS0162, $$CS0219", (int)ErrorCode.WRN_UnreferencedVarAssg)] [InlineData("#pragma warning disable CS0162, CS0219$$", (int)ErrorCode.WRN_UnreferencedVarAssg)] [InlineData("#pragma warning $$disable CS0162, CS0219", (int)ErrorCode.WRN_UnreachableCode)] [InlineData("#pragma warning $$disable CS0219, CS0162", (int)ErrorCode.WRN_UnreferencedVarAssg)] public async Task MultipleWarningsAreDisplayedDependingOnCursorPosition(string pragma, int errorCode) { await TestInMethodAsync( @$" {pragma} return; var i = 0; ", GetFormattedErrorTitle((ErrorCode)errorCode)); } [WorkItem(46604, "https://github.com/dotnet/roslyn/issues/46604")] [WpfFact, Trait(Traits.Feature, Traits.Features.QuickInfo)] public async Task ErrorTitleIsShwonInSupressMessageAttribute() { await TestAsync( @" using System.Diagnostics.CodeAnalysis; namespace T { [SuppressMessage(""CodeQuality"", ""IDE0051$$"")] public class C { private int _i; } } ", GetFormattedIDEAnalyzerTitle(51, nameof(AnalyzersResources.Remove_unused_private_members)), ImmutableArray<TextSpan>.Empty); } [WorkItem(46604, "https://github.com/dotnet/roslyn/issues/46604")] [WpfTheory, Trait(Traits.Feature, Traits.Features.QuickInfo)] [InlineData(@"[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(""CodeQuality"", ""IDE0051$$"")]", true)] [InlineData(@"[System.Diagnostics.CodeAnalysis.SuppressMessage(""CodeQuality"", ""IDE0051$$"")]", true)] [InlineData(@"[System.Diagnostics.CodeAnalysis.SuppressMessage(""CodeQuality$$"", ""IDE0051"")]", false)] [InlineData(@"[System.Diagnostics.CodeAnalysis.SuppressMessage(""CodeQuality"", ""IDE0051"", Justification = ""WIP$$"")]", false)] [InlineData(@"[System.Diagnostics.CodeAnalysis.SuppressMessage$$(""CodeQuality"", ""IDE0051"")]", false)] [InlineData(@"[SuppressMessage(""CodeQuality"", ""$$IDE0051"")]", true)] [InlineData(@"[SuppressMessage(""CodeQuality"", ""$$IDE0051: Remove unused private member"")]", true)] [InlineData(@"[SuppressMessage(category: ""CodeQuality"", checkId$$: ""IDE0051: Remove unused private member"")]", true)] [InlineData(@"[SuppressMessage(category: ""CodeQuality"", $$checkId: ""IDE0051: Remove unused private member"")]", true)] [InlineData(@"[SuppressMessage(checkId$$: ""IDE0051: Remove unused private member"", category: ""CodeQuality"")]", true)] [InlineData(@"[SuppressMessage(checkId: ""IDE0051: Remove unused private member"", category$$: ""CodeQuality"")]", false)] [InlineData(@"[SuppressMessage(""CodeQuality"", DiagnosticIds.IDE0051 +$$ "": Remove unused private member"")]", true)] [InlineData(@"[SuppressMessage(""CodeQuality"", """" + (DiagnosticIds.IDE0051 +$$ "": Remove unused private member""))]", true)] [InlineData(@"[SuppressMessage(category: ""CodeQuality"", checkId$$: DiagnosticIds.IDE0051 + "": Remove unused private member"")]", true)] // False negative: Aliased attribute is not supported [InlineData(@"[SM(""CodeQuality"", ""IDE0051$$""", false)] public async Task QuickInfoSuppressMessageAttributeUseCases(string suppressMessageAttribute, bool shouldShowQuickInfo) { var description = shouldShowQuickInfo ? GetFormattedIDEAnalyzerTitle(51, nameof(AnalyzersResources.Remove_unused_private_members)) : null; await TestAsync( @$" using System.Diagnostics.CodeAnalysis; using SM = System.Diagnostics.CodeAnalysis.SuppressMessageAttribute; namespace T {{ public static class DiagnosticIds {{ public const string IDE0051 = ""IDE0051""; }} {suppressMessageAttribute} public class C {{ private int _i; }} }} ", description, ImmutableArray<TextSpan>.Empty); } protected static async Task AssertContentIsAsync(TestWorkspace workspace, Document document, int position, string expectedDescription, ImmutableArray<TextSpan> relatedSpans) { var info = await GetQuickinfo(workspace, document, position); var description = info?.Sections.FirstOrDefault(s => s.Kind == QuickInfoSectionKinds.Description); Assert.NotNull(description); Assert.Equal(expectedDescription, description.Text); Assert.Collection(relatedSpans, info.RelatedSpans.Select(actualSpan => new Action<TextSpan>(expectedSpan => Assert.Equal(expectedSpan, actualSpan))).ToArray()); } private static async Task<QuickInfoItem> GetQuickinfo(TestWorkspace workspace, Document document, int position) { var diagnosticAnalyzerService = workspace.ExportProvider.GetExportedValue<IDiagnosticAnalyzerService>(); var provider = new CSharpDiagnosticAnalyzerQuickInfoProvider(diagnosticAnalyzerService); var info = await provider.GetQuickInfoAsync(new QuickInfoContext(document, position, CancellationToken.None)); return info; } protected static async Task AssertNoContentAsync(TestWorkspace workspace, Document document, int position) { var info = await GetQuickinfo(workspace, document, position); Assert.Null(info); } protected static async Task TestAsync( string code, string expectedDescription, ImmutableArray<TextSpan> relatedSpans, CSharpParseOptions parseOptions = null) { using var workspace = TestWorkspace.CreateCSharp(code, parseOptions); var analyzerReference = new AnalyzerImageReference(ImmutableArray.Create<DiagnosticAnalyzer>( new CSharpCompilerDiagnosticAnalyzer(), new CSharpRemoveUnusedMembersDiagnosticAnalyzer())); workspace.TryApplyChanges(workspace.CurrentSolution.WithAnalyzerReferences(new[] { analyzerReference })); var testDocument = workspace.Documents.Single(); var position = testDocument.CursorPosition.Value; var document = workspace.CurrentSolution.Projects.First().Documents.First(); if (string.IsNullOrEmpty(expectedDescription)) { await AssertNoContentAsync(workspace, document, position); } else { await AssertContentIsAsync(workspace, document, position, expectedDescription, relatedSpans); } } private static string GetFormattedErrorTitle(ErrorCode errorCode) { var localizable = MessageProvider.Instance.GetTitle((int)errorCode); return $"CS{(int)errorCode:0000}: {localizable}"; } private static string GetFormattedIDEAnalyzerTitle(int ideDiagnosticId, string nameOfLocalizableStringResource) { var localizable = new LocalizableResourceString(nameOfLocalizableStringResource, AnalyzersResources.ResourceManager, typeof(AnalyzersResources)); return $"IDE{ideDiagnosticId:0000}: {localizable}"; } protected static Task TestInClassAsync(string code, string expectedDescription, params TextSpan[] relatedSpans) => TestAsync( @"class C {" + code + "}", expectedDescription, relatedSpans.ToImmutableArray()); protected static Task TestInMethodAsync(string code, string expectedDescription, params TextSpan[] relatedSpans) => TestInClassAsync( @"void M() {" + code + "}", expectedDescription, relatedSpans); } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/VisualBasic/Test/Semantic/Semantics/InitOnlyMemberTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class InitOnlyMemberTests Inherits BasicTestBase Protected Const IsExternalInitTypeDefinition As String = " namespace System.Runtime.CompilerServices { public static class IsExternalInit { } } " <Fact> Public Sub EvaluationInitOnlySetter_01() Dim csSource = " public class C : System.Attribute { public int Property0 { init { System.Console.Write(value + "" 0 ""); } } public int Property1 { init { System.Console.Write(value + "" 1 ""); } } public int Property2 { init { System.Console.Write(value + "" 2 ""); } } public int Property3 { init { System.Console.Write(value + "" 3 ""); } } public int Property4 { init { System.Console.Write(value + "" 4 ""); } } public int Property5 { init { System.Console.Write(value + "" 5 ""); } } public int Property6 { init { System.Console.Write(value + "" 6 ""); } } public int Property7 { init { System.Console.Write(value + "" 7 ""); } } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new B() With { .Property1 = 42, .Property2 = 43} End Sub End Class <C(Property7:= 48)> Class B Inherits C Public Sub New() Property0 = 41 Me.Property3 = 44 MyBase.Property4 = 45 MyClass.Property5 = 46 With Me .Property6 = 47 End With Me.GetType().GetCustomAttributes(False) End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="41 0 44 3 45 4 46 5 47 6 48 7 42 1 43 2 ").VerifyDiagnostics() Assert.True(DirectCast(comp1.GetMember(Of PropertySymbol)("C.Property0").SetMethod, IMethodSymbol).IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Dim x = new B() With { .Property1 = 42, .Property2 = 43} ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Dim x = new B() With { .Property1 = 42, .Property2 = 43} ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. <C(Property7:= 48)> ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Property0 = 41 ~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me.Property3 = 44 ~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyBase.Property4 = 45 ~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyClass.Property5 = 46 ~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. .Property6 = 47 ~~~~~~~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() x.Property1 = 42 With New B() .Property2 = 43 End With Dim y As New B() With { .F = Sub() .Property3 = 44 End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y .Property4 = 45 End With With Me With y .Property6 = 47 End With End With Dim x as New B() x.Property0 = 41 Dim z = Sub() Property5 = 46 End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Property1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Property1 = 42 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property2' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property2 = 43 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property3 = 44 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property4 = 45 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property6 = 47 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Property0 = 41 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Property5 = 46 ~~~~~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() Property0 = 41 Me.Property3 = 44 MyBase.Property4 = 45 MyClass.Property5 = 46 With Me .Property6 = 47 End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Property0 = 41 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me.Property3 = 44 ~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyBase.Property4 = 45 ~~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyClass.Property5 = 46 ~~~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property6 = 47 ~~~~~~~~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub EvaluationInitOnlySetter_02() Dim csSource = " public class C : System.Attribute { public int Property0 { init; get; } public int Property1 { init; get; } public int Property2 { init; get; } public int Property3 { init; get; } public int Property4 { init; get; } public int Property5 { init; get; } public int Property6 { init; get; } public int Property7 { init; get; } public int Property8 { init; get; } public int Property9 { init => throw new System.InvalidOperationException(); get => 0; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() With { .Property1 = 42 } System.Console.Write(b.Property0) System.Console.Write(" "c) System.Console.Write(b.Property1) System.Console.Write(" "c) System.Console.Write(b.Property2) System.Console.Write(" "c) System.Console.Write(b.Property3) System.Console.Write(" "c) System.Console.Write(b.Property4) System.Console.Write(" "c) System.Console.Write(b.Property5) System.Console.Write(" "c) System.Console.Write(b.Property6) System.Console.Write(" "c) System.Console.Write(DirectCast(b.GetType().GetCustomAttributes(False)(0), C).Property7) System.Console.Write(" "c) System.Console.Write(b.Property8) B.Init(b.Property9, 492) B.Init((b.Property9), 493) End Sub End Class <C(Property7:= 48)> Class B Inherits C Public Sub New() Property0 = 41 Me.Property3 = 44 MyBase.Property4 = 45 MyClass.Property5 = 46 With Me .Property6 = 47 End With Init(Property2, 43) Init((Property2), 430) With Me Init(.Property8, 49) Init((.Property9), 494) End With Dim b = Me Init(b.Property9, 490) Init((b.Property9), 491) With b Init(.Property9, 499) Init((.Property9), 450) End With Test() Dim d = Sub() Init(Property9, 600) Init((Property9), 601) End Sub d() End Sub Public Sub Test() With Me Init(.Property9, 495) Init((.Property9), 496) End With Init(Property9, 497) Init((Property9), 498) Dim b = Me With b Init(.Property9, 451) Init((.Property9), 452) End With End Sub Public Shared Sub Init(ByRef p as Integer, val As Integer) p = val End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16_9, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="41 42 43 44 45 46 47 48 49").VerifyDiagnostics() Assert.True(DirectCast(comp1.GetMember(Of PropertySymbol)("C.Property0").SetMethod, IMethodSymbol).IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Dim b = new B() With { .Property1 = 42 } ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. B.Init(b.Property9, 492) ~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. <C(Property7:= 48)> ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Property0 = 41 ~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me.Property3 = 44 ~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyBase.Property4 = 45 ~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyClass.Property5 = 46 ~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. .Property6 = 47 ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Property2, 43) ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(.Property8, 49) ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(b.Property9, 490) ~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(.Property9, 499) ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Property9, 600) ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(.Property9, 495) ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Property9, 497) ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(.Property9, 451) ~~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() x.Property1 = 42 With New B() .Property2 = 43 End With Dim y As New B() With { .F = Sub() .Property3 = 44 End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y .Property4 = 45 End With With Me With y .Property6 = 47 End With End With Dim x as New B() x.Property0 = 41 Dim z = Sub() Property5 = 46 End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Property1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Property1 = 42 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property2' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property2 = 43 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property3 = 44 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property4 = 45 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property6 = 47 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Property0 = 41 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Property5 = 46 ~~~~~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() Property0 = 41 Me.Property3 = 44 MyBase.Property4 = 45 MyClass.Property5 = 46 With Me .Property6 = 47 End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Property0 = 41 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me.Property3 = 44 ~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyBase.Property4 = 45 ~~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyClass.Property5 = 46 ~~~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property6 = 47 ~~~~~~~~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub EvaluationInitOnlySetter_03() Dim csSource = " public class C { public int this[int x] { init { System.Console.Write(value + "" ""); } } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new B() End Sub End Class Class B Inherits C Public Sub New() Item(0) = 40 Me.Item(0) = 41 MyBase.Item(0) = 42 MyClass.Item(0) = 43 Me(0) = 44 With Me .Item(0) = 45 End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="40 41 42 43 44 45 ").VerifyDiagnostics() Assert.True(DirectCast(comp1.GetMember(Of PropertySymbol)("C.Item").SetMethod, IMethodSymbol).IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Item(0) = 40 ~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me.Item(0) = 41 ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyBase.Item(0) = 42 ~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyClass.Item(0) = 43 ~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me(0) = 44 ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. .Item(0) = 45 ~~~~~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() x(0) = 40 x.Item(0) = 41 With New B() .Item(0) = 42 End With Dim y As New B() With { .F = Sub() .Item(0) = 43 End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y .Item(0) = 44 End With With Me With y .Item(0) = 45 End With End With Dim x as New B() x(0) = 46 x.Item(0) = 47 Dim z = Sub() Item(0) = 48 Me(0) = 49 End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x(0) = 40 ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Item(0) = 41 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) = 42 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) = 43 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) = 44 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) = 45 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x(0) = 46 ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Item(0) = 47 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Item(0) = 48 ~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me(0) = 49 ~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() Item(0) = 40 Me(0) = 41 Me.Item(0) = 42 MyBase.Item(0) = 43 MyClass.Item(0) = 44 With Me .Item(0) = 45 End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Item(0) = 40 ~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me(0) = 41 ~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me.Item(0) = 42 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyBase.Item(0) = 43 ~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyClass.Item(0) = 44 ~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) = 45 ~~~~~~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub EvaluationInitOnlySetter_04() Dim csSource = " public class C : System.Attribute { private int[] _item = new int[36]; public int this[int x] { init { if (x > 8) { throw new System.InvalidOperationException(); } _item[x] = value; } get => _item[x]; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() B.Init(b(9), 49) B.Init((b(19)), 59) B.Init(b.Item(10), 50) B.Init((b.Item(20)), 60) With b B.Init(.Item(11), 51) B.Init((.Item(21)), 61) End With for i as Integer = 0 To 35 System.Console.Write(b(i)) System.Console.Write(" "c) Next End Sub End Class Class B Inherits C Public Sub New() Item(0) = 40 Me(1) = 41 Me.Item(2) = 42 MyBase.Item(3) = 43 MyClass.Item(4) = 44 With Me .Item(5) = 45 End With Init(Item(6), 46) Init((Item(22)), 62) Init(Me(7), 47) Init((Me(23)), 63) Dim b = Me Init(b(12), 52) Init((b(24)), 64) Init(b.Item(13), 53) Init((b.Item(25)), 65) With Me Init(.Item(8), 48) Init((.Item(26)), 66) End With With b Init(.Item(14), 54) Init((.Item(27)), 67) End With Test() Dim d = Sub() Init(Item(32), 72) Init((Item(33)), 73) Init(Me(34), 74) Init((Me(35)), 75) End Sub d() End Sub Public Sub Test() With Me Init(.Item(15), 55) Init((.Item(28)), 68) End With Init(Me(16), 56) Init((Me(29)), 69) Init(Item(17), 57) Init((Item(30)), 70) Dim b = Me With b Init(.Item(18), 58) Init((.Item(31)), 71) End With End Sub Public Shared Sub Init(ByRef p as Integer, val As Integer) p = val End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16_9, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="40 41 42 43 44 45 46 47 48 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0").VerifyDiagnostics() Assert.True(DirectCast(comp1.GetMember(Of PropertySymbol)("C.Item").SetMethod, IMethodSymbol).IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. B.Init(b(9), 49) ~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. B.Init(b.Item(10), 50) ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. B.Init(.Item(11), 51) ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Item(0) = 40 ~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me(1) = 41 ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me.Item(2) = 42 ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyBase.Item(3) = 43 ~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyClass.Item(4) = 44 ~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. .Item(5) = 45 ~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Item(6), 46) ~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Me(7), 47) ~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(b(12), 52) ~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(b.Item(13), 53) ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(.Item(8), 48) ~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(.Item(14), 54) ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Item(32), 72) ~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Me(34), 74) ~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(.Item(15), 55) ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Me(16), 56) ~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Item(17), 57) ~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(.Item(18), 58) ~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() x(0) = 40 x.Item(1) = 41 With New B() .Item(2) = 42 End With Dim y As New B() With { .F = Sub() .Item(3) = 43 End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y .Item(4) = 44 End With With Me With y .Item(5) = 45 End With End With Dim x as New B() x(6) = 46 x.Item(7) = 47 Dim z = Sub() Item(8) = 48 Me(9) = 49 End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x(0) = 40 ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Item(1) = 41 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(2) = 42 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(3) = 43 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(4) = 44 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(5) = 45 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x(6) = 46 ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Item(7) = 47 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Item(8) = 48 ~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me(9) = 49 ~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() Item(0) = 40 Me(1) = 41 Me.Item(2) = 42 MyBase.Item(3) = 43 MyClass.Item(4) = 44 With Me .Item(5) = 45 End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Item(0) = 40 ~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me(1) = 41 ~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me.Item(2) = 42 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyBase.Item(3) = 43 ~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyClass.Item(4) = 44 ~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(5) = 45 ~~~~~~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub EvaluationInitOnlySetter_05() Dim csSource = " public class C { public int Property0 { get => 0; init { System.Console.Write(value + "" 0 ""); } } public int Property1 { get => 0; init { System.Console.Write(value + "" 1 ""); } } public int Property2 { get => 0; init { System.Console.Write(value + "" 2 ""); } } public int Property3 { get => 0; init { System.Console.Write(value + "" 3 ""); } } public int Property4 { get => 0; init { System.Console.Write(value + "" 4 ""); } } public int Property5 { get => 0; init { System.Console.Write(value + "" 5 ""); } } public int Property6 { get => 0; init { System.Console.Write(value + "" 6 ""); } } public int Property7 { get => 0; init { System.Console.Write(value + "" 7 ""); } } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x as New B() End Sub End Class Class B Inherits C Public Sub New() Property0 += 41 Me.Property3 += 44 MyBase.Property4 += 45 MyClass.Property5 += 46 With Me .Property6 += 47 End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="41 0 44 3 45 4 46 5 47 6 ").VerifyDiagnostics() Assert.True(DirectCast(comp1.GetMember(Of PropertySymbol)("C.Property0").SetMethod, IMethodSymbol).IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Property0 += 41 ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me.Property3 += 44 ~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyBase.Property4 += 45 ~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyClass.Property5 += 46 ~~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. .Property6 += 47 ~~~~~~~~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() x.Property1 += 42 With New B() .Property2 += 43 End With Dim y As New B() With { .F = Sub() .Property3 += 44 End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y .Property4 += 45 End With With Me With y .Property6 += 47 End With End With Dim x as New B() x.Property0 += 41 Dim z = Sub() Property5 += 46 End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Property1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Property1 += 42 ~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property2' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property2 += 43 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property3 += 44 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property4 += 45 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property6 += 47 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Property0 += 41 ~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Property5 += 46 ~~~~~~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() Property0 += 41 Me.Property3 += 44 MyBase.Property4 += 45 MyClass.Property5 += 46 With Me .Property6 += 47 End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Property0 += 41 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me.Property3 += 44 ~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyBase.Property4 += 45 ~~~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyClass.Property5 += 46 ~~~~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property6 += 47 ~~~~~~~~~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub EvaluationInitOnlySetter_06() Dim csSource = " public class C { public int this[int x] { get => 0; init { System.Console.Write(value + "" ""); } } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new B() End Sub End Class Class B Inherits C Public Sub New() Item(0) += 40 Me.Item(0) += 41 MyBase.Item(0) += 42 MyClass.Item(0) += 43 Me(0) += 44 With Me .Item(0) += 45 End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="40 41 42 43 44 45 ").VerifyDiagnostics() Assert.True(DirectCast(comp1.GetMember(Of PropertySymbol)("C.Item").SetMethod, IMethodSymbol).IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Item(0) += 40 ~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me.Item(0) += 41 ~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyBase.Item(0) += 42 ~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyClass.Item(0) += 43 ~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me(0) += 44 ~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. .Item(0) += 45 ~~~~~~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() x(0) += 40 x.Item(0) += 41 With New B() .Item(0) += 42 End With Dim y As New B() With { .F = Sub() .Item(0) += 43 End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y .Item(0) += 44 End With With Me With y .Item(0) += 45 End With End With Dim x as New B() x(0) += 46 x.Item(0) += 47 Dim z = Sub() Item(0) += 48 Me(0) += 49 End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x(0) += 40 ~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Item(0) += 41 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) += 42 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) += 43 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) += 44 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) += 45 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x(0) += 46 ~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Item(0) += 47 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Item(0) += 48 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me(0) += 49 ~~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() Item(0) += 40 Me(0) += 41 Me.Item(0) += 42 MyBase.Item(0) += 43 MyClass.Item(0) += 44 With Me .Item(0) += 45 End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Item(0) += 40 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me(0) += 41 ~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me.Item(0) += 42 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyBase.Item(0) += 43 ~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyClass.Item(0) += 44 ~~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) += 45 ~~~~~~~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub EvaluationInitOnlySetter_07() Dim csSource = " public interface I { public int Property1 { init; } public int Property2 { init; } public int Property3 { init; } public int Property4 { init; } public int Property5 { init; } } public class C : I { public int Property1 { init { System.Console.Write(value + "" 1 ""); } } public int Property2 { init { System.Console.Write(value + "" 2 ""); } } public int Property3 { init { System.Console.Write(value + "" 3 ""); } } public int Property4 { init { System.Console.Write(value + "" 4 ""); } } public int Property5 { init { System.Console.Write(value + "" 5 ""); } } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() M1(Of C)() M2(Of B)() End Sub Shared Sub M1(OF T As {New, I})() Dim x = new T() With { .Property1 = 42 } End Sub Shared Sub M2(OF T As {New, C})() Dim x = new T() With { .Property2 = 43 } End Sub End Class Class B Inherits C End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="42 1 43 2 ").VerifyDiagnostics() Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Dim x = new T() With { .Property1 = 42 } ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Dim x = new T() With { .Property2 = 43 } ~~~~~~~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() End Sub Shared Sub M1(Of T As {New, I})() Dim x = New T() x.Property1 = 42 With New T() .Property2 = 43 End With End Sub Shared Sub M2(Of T As {New, C})() Dim x = New T() x.Property3 = 44 With New T() .Property4 = 45 End With End Sub Shared Sub M3(x As I) x.Property5 = 46 End Sub End Class Class B Inherits C End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Property1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Property1 = 42 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property2' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property2 = 43 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Property3 = 44 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property4 = 45 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Property5 = 46 ~~~~~~~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) End Sub <Fact> Public Sub EvaluationInitOnlySetter_08() Dim csSource = " using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58277"")] [CoClass(typeof(C))] public interface I { public int Property1 { init; } public int Property2 { init; } } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public class C : I { int I.Property1 { init { System.Console.Write(value + "" 1 ""); } } int I.Property2 { init { System.Console.Write(value + "" 2 ""); } } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new I() With { .Property1 = 42 } End Sub End Class Class B Inherits C End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="42 1 ").VerifyDiagnostics() Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Dim x = new I() With { .Property1 = 42 } ~~~~~~~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() With New I() .Property2 = 43 End With End Sub End Class Class B Inherits C End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Property2' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property2 = 43 ~~~~~~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) End Sub <Fact> Public Sub EvaluationInitOnlySetter_09() Dim csSource = " public class C { public int Property1 { init { System.Console.Write(value + "" 1 ""); } } public int Property2 { init { System.Console.Write(value + "" 2 ""); } } public int Property3 { init { System.Console.Write(value + "" 3 ""); } } public int Property4 { init { System.Console.Write(value + "" 4 ""); } } public int Property5 { init { System.Console.Write(value + "" 5 ""); } } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Shared Sub New() Property1 = 41 Me.Property2 = 42 MyBase.Property3 = 43 MyClass.Property4 = 44 With Me .Property5 = 45 End With End Sub End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> 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. Property1 = 41 ~~~~~~~~~ BC30043: 'Me' is valid only within an instance method. Me.Property2 = 42 ~~ BC30043: 'MyBase' is valid only within an instance method. MyBase.Property3 = 43 ~~~~~~ BC30043: 'MyClass' is valid only within an instance method. MyClass.Property4 = 44 ~~~~~~~ BC30043: 'Me' is valid only within an instance method. With Me ~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property5 = 45 ~~~~~~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) End Sub <Fact> Public Sub EvaluationInitOnlySetter_10() Dim csSource = " public class C { public int P2 { init { System.Console.Write(value + "" 2 ""); } } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new B() End Sub End Class Class B Inherits C Public Sub New() With (Me) .P2 = 42 End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="42 2 ").VerifyDiagnostics() End Sub <Fact> Public Sub Overriding_01() Dim csSource = " public class C { public virtual int P0 { init { } } public virtual int P1 { init; get; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Class B1 Inherits C Public Overrides WriteOnly Property P0 As Integer Set End Set End Property Public Overrides Property P1 As Integer End Class Class B2 Inherits C Public Overrides Property P0 As Integer Public Overrides ReadOnly Property P1 As Integer End Class Class B3 Inherits C Public Overrides ReadOnly Property P0 As Integer Public Overrides WriteOnly Property P1 As Integer Set End Set End Property End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected1 = <expected> BC37312: 'Public Overrides WriteOnly Property P0 As Integer' cannot override init-only 'Public Overridable Overloads WriteOnly Property P0 As Integer'. Public Overrides WriteOnly Property P0 As Integer ~~ BC37312: 'Public Overrides Property P1 As Integer' cannot override init-only 'Public Overridable Overloads Property P1 As Integer'. Public Overrides Property P1 As Integer ~~ BC30362: 'Public Overrides Property P0 As Integer' cannot override 'Public Overridable Overloads WriteOnly Property P0 As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides Property P0 As Integer ~~ BC30362: 'Public Overrides ReadOnly Property P1 As Integer' cannot override 'Public Overridable Overloads Property P1 As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides ReadOnly Property P1 As Integer ~~ BC30362: 'Public Overrides ReadOnly Property P0 As Integer' cannot override 'Public Overridable Overloads WriteOnly Property P0 As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides ReadOnly Property P0 As Integer ~~ BC30362: 'Public Overrides WriteOnly Property P1 As Integer' cannot override 'Public Overridable Overloads Property P1 As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides WriteOnly Property P1 As Integer ~~ </expected> comp1.AssertTheseDiagnostics(expected1) Dim p0Set = comp1.GetMember(Of PropertySymbol)("B1.P0").SetMethod Assert.False(p0Set.IsInitOnly) Assert.True(p0Set.OverriddenMethod.IsInitOnly) Dim p1Set = comp1.GetMember(Of PropertySymbol)("B1.P1").SetMethod Assert.False(p1Set.IsInitOnly) Assert.True(p1Set.OverriddenMethod.IsInitOnly) Assert.False(comp1.GetMember(Of PropertySymbol)("B2.P0").SetMethod.IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics(expected1) End Sub <Fact> Public Sub Overriding_02() Dim csSource = " public class C<T> { public virtual T this[int x] { init { } } public virtual T this[short x] { init {} get => throw null; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Class B1 Inherits C(Of Integer) Public Overrides WriteOnly Property Item(x as Integer) As Integer Set End Set End Property Public Overrides Property Item(x as Short) As Integer Get Return Nothing End Get Set End Set End Property End Class Class B2 Inherits C(Of Integer) Public Overrides Property Item(x as Integer) As Integer Get Return Nothing End Get Set End Set End Property Public Overrides ReadOnly Property Item(x as Short) As Integer Get Return Nothing End Get End Property End Class Class B3 Inherits C(Of Integer) Public Overrides ReadOnly Property Item(x as Integer) As Integer Get Return Nothing End Get End Property Public Overrides WriteOnly Property Item(x as Short) As Integer Set End Set End Property End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected1 = <expected> BC37312: 'Public Overrides WriteOnly Property Item(x As Integer) As Integer' cannot override init-only 'Public Overridable Overloads WriteOnly Default Property Item(x As Integer) As Integer'. Public Overrides WriteOnly Property Item(x as Integer) As Integer ~~~~ BC37312: 'Public Overrides Property Item(x As Short) As Integer' cannot override init-only 'Public Overridable Overloads Default Property Item(x As Short) As Integer'. Public Overrides Property Item(x as Short) As Integer ~~~~ BC30362: 'Public Overrides Property Item(x As Integer) As Integer' cannot override 'Public Overridable Overloads WriteOnly Default Property Item(x As Integer) As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides Property Item(x as Integer) As Integer ~~~~ BC30362: 'Public Overrides ReadOnly Property Item(x As Short) As Integer' cannot override 'Public Overridable Overloads Default Property Item(x As Short) As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides ReadOnly Property Item(x as Short) As Integer ~~~~ BC30362: 'Public Overrides ReadOnly Property Item(x As Integer) As Integer' cannot override 'Public Overridable Overloads WriteOnly Default Property Item(x As Integer) As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides ReadOnly Property Item(x as Integer) As Integer ~~~~ BC30362: 'Public Overrides WriteOnly Property Item(x As Short) As Integer' cannot override 'Public Overridable Overloads Default Property Item(x As Short) As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides WriteOnly Property Item(x as Short) As Integer ~~~~ </expected> comp1.AssertTheseDiagnostics(expected1) Dim p0Set = comp1.GetTypeByMetadataName("B1").GetMembers("Item").OfType(Of PropertySymbol).First().SetMethod Assert.False(p0Set.IsInitOnly) Assert.True(p0Set.OverriddenMethod.IsInitOnly) Assert.True(DirectCast(p0Set.OverriddenMethod, IMethodSymbol).IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics(expected1) End Sub <Fact> Public Sub Overriding_03() Dim csSource = " public class A { public virtual int P1 { init; get; } public virtual int P2 { init; get; } } public class B : A { public override int P1 { get => throw null; } public override int P2 { init {} } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Class C1 Inherits B Public Overrides WriteOnly Property P1 As Integer Set End Set End Property Public Overrides WriteOnly Property P2 As Integer Set End Set End Property End Class Class C2 Inherits B Public Overrides Property P1 As Integer Public Overrides Property P2 As Integer End Class Class C3 Inherits B Public Overrides ReadOnly Property P1 As Integer Public Overrides ReadOnly Property P2 As Integer End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected1 = <expected> BC30362: 'Public Overrides WriteOnly Property P1 As Integer' cannot override 'Public Overrides ReadOnly Property P1 As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides WriteOnly Property P1 As Integer ~~ BC37312: 'Public Overrides WriteOnly Property P2 As Integer' cannot override init-only 'Public Overrides WriteOnly Property P2 As Integer'. Public Overrides WriteOnly Property P2 As Integer ~~ BC30362: 'Public Overrides Property P1 As Integer' cannot override 'Public Overrides ReadOnly Property P1 As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides Property P1 As Integer ~~ BC30362: 'Public Overrides Property P2 As Integer' cannot override 'Public Overrides WriteOnly Property P2 As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides Property P2 As Integer ~~ BC30362: 'Public Overrides ReadOnly Property P2 As Integer' cannot override 'Public Overrides WriteOnly Property P2 As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides ReadOnly Property P2 As Integer ~~ </expected> comp1.AssertTheseDiagnostics(expected1) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics(expected1) End Sub <Fact()> Public Sub Overriding_04() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit CL1 extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } .method public hidebysig newslot virtual instance int32 get_P() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void set_P(int32 x) cil managed { ret } .property instance int32 P() { .get instance int32 CL1::get_P() .set instance void CL1::set_P(int32) } .method public hidebysig newslot virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(int32 x) cil managed { ret } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL1::get_P() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL1::set_P(int32) } } // end of class CL1 .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Inherits CL1 Overrides Property P As Integer End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseDll) CompileAndVerify(compilation).VerifyDiagnostics() Dim p = compilation.GetMember(Of PropertySymbol)("Test.P") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.False(pSet.OverriddenMethod.IsInitOnly) Assert.Empty(pSet.OverriddenMethod.ReturnTypeCustomModifiers) Assert.Empty(p.GetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.Empty(p.OverriddenProperty.TypeCustomModifiers) End Sub <Fact()> Public Sub Overriding_05() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit CL1 extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } .method public hidebysig newslot virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(int32 x) cil managed { ret } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL1::get_P() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL1::set_P(int32) } .method public hidebysig newslot virtual instance int32 get_P() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void set_P(int32 x) cil managed { ret } .property instance int32 P() { .get instance int32 CL1::get_P() .set instance void CL1::set_P(int32) } } // end of class CL1 .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Inherits CL1 Overrides Property P As Integer End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseDll) CompileAndVerify(compilation).VerifyDiagnostics() Dim p = compilation.GetMember(Of PropertySymbol)("Test.P") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.False(pSet.OverriddenMethod.IsInitOnly) Assert.Empty(pSet.OverriddenMethod.ReturnTypeCustomModifiers) Assert.Empty(p.GetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.Empty(p.OverriddenProperty.TypeCustomModifiers) End Sub <Fact()> Public Sub Overriding_06() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit CL1 extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } .method public hidebysig newslot virtual instance int32 get_P() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void set_P(int32 x) cil managed { ret } .property instance int32 modopt(CL1) P() { .get instance int32 CL1::get_P() .set instance void CL1::set_P(int32) } .method public hidebysig newslot virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(int32 x) cil managed { ret } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL1::get_P() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL1::set_P(int32) } } // end of class CL1 .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Inherits CL1 Overrides Property P As Integer End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30935: Member 'Public Overridable Overloads Property P As Integer' that matches this signature cannot be overridden because the class 'CL1' contains multiple members with this same name and signature: 'Public Overridable Overloads Property P As Integer' 'Public Overridable Overloads Property P As Integer' Overrides Property P As Integer ~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("Test.P") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.False(pSet.OverriddenMethod.IsInitOnly) Assert.Empty(pSet.OverriddenMethod.ReturnTypeCustomModifiers) Assert.Empty(p.GetMethod.OverriddenMethod.ReturnTypeCustomModifiers) End Sub <Fact()> Public Sub Overriding_07() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit CL1 extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } .method public hidebysig newslot virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(int32 x) cil managed { ret } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL1::get_P() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL1::set_P(int32) } .method public hidebysig newslot virtual instance int32 get_P() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void set_P(int32 x) cil managed { ret } .property instance int32 modopt(CL1) P() { .get instance int32 CL1::get_P() .set instance void CL1::set_P(int32) } } // end of class CL1 .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Inherits CL1 Overrides Property P As Integer End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30935: Member 'Public Overridable Overloads Property P As Integer' that matches this signature cannot be overridden because the class 'CL1' contains multiple members with this same name and signature: 'Public Overridable Overloads Property P As Integer' 'Public Overridable Overloads Property P As Integer' Overrides Property P As Integer ~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("Test.P") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.True(pSet.OverriddenMethod.IsInitOnly) Assert.NotEmpty(pSet.OverriddenMethod.ReturnTypeCustomModifiers) Assert.NotEmpty(p.GetMethod.OverriddenMethod.ReturnTypeCustomModifiers) End Sub <Fact()> Public Sub Overriding_08() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit CL1 extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } .method public hidebysig newslot virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P1() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P1(int32 x) cil managed { ret } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P1() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL1::get_P1() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL1::set_P1(int32) } .method public hidebysig newslot virtual instance int32 get_P1() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void set_P1(int32 x) cil managed { ret } .property instance int32 P1() { .get instance int32 CL1::get_P1() .set instance void CL1::set_P1(int32) } .method public hidebysig newslot virtual instance int32 get_P2() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void set_P2(int32 x) cil managed { ret } .property instance int32 P2() { .get instance int32 CL1::get_P2() .set instance void CL1::set_P2(int32) } .method public hidebysig newslot virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P2() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P2(int32 x) cil managed { ret } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P2() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL1::get_P2() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL1::set_P2(int32) } } // end of class CL1 .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi beforefieldinit CL2 extends CL1 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { IL_0000: ldarg.0 IL_0001: call instance void CL1::.ctor() IL_0006: ret } .method public hidebysig virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P1() cil managed { ldc.i4.s 123 ret } .method public hidebysig virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P1(int32 x) cil managed { ret } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P1() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL2::get_P1() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL2::set_P1(int32) } .method public hidebysig virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P2() cil managed { ldc.i4.s 123 ret } .method public hidebysig virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P2(int32 x) cil managed { ret } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P2() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL2::get_P2() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL2::set_P2(int32) } } .class public auto ansi beforefieldinit CL3 extends CL1 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { IL_0000: ldarg.0 IL_0001: call instance void CL1::.ctor() IL_0006: ret } .method public hidebysig virtual instance int32 get_P1() cil managed { ldc.i4.s 123 ret } .method public hidebysig virtual instance void set_P1(int32 x) cil managed { ret } .property instance int32 P1() { .get instance int32 CL3::get_P1() .set instance void CL3::set_P1(int32) } .method public hidebysig virtual instance int32 get_P2() cil managed { ldc.i4.s 123 ret } .method public hidebysig virtual instance void set_P2(int32 x) cil managed { ret } .property instance int32 P2() { .get instance int32 CL3::get_P2() .set instance void CL3::set_P2(int32) } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ ]]></file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseDll) Dim cl2p1 = compilation.GetMember(Of PropertySymbol)("CL2.P1") Assert.NotEmpty(cl2p1.SetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.NotEmpty(cl2p1.GetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.NotEmpty(cl2p1.OverriddenProperty.TypeCustomModifiers) Dim cl2p2 = compilation.GetMember(Of PropertySymbol)("CL2.P2") Assert.NotEmpty(cl2p2.SetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.NotEmpty(cl2p2.GetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.NotEmpty(cl2p2.OverriddenProperty.TypeCustomModifiers) Dim cl3p1 = compilation.GetMember(Of PropertySymbol)("CL3.P1") Assert.Empty(cl3p1.SetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.Empty(cl3p1.GetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.Empty(cl3p1.OverriddenProperty.TypeCustomModifiers) Dim cl3p2 = compilation.GetMember(Of PropertySymbol)("CL3.P2") Assert.Empty(cl3p2.SetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.Empty(cl3p2.GetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.Empty(cl3p2.OverriddenProperty.TypeCustomModifiers) End Sub <Fact> Public Sub Implementing_01() Dim csSource = " public interface I { int P0 { init; } int P1 { init; get; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Class B1 Implements I Public WriteOnly Property P0 As Integer Implements I.P0 Set End Set End Property Public Property P1 As Integer Implements I.P1 End Class Class B2 Implements I Public Property P0 As Integer Implements I.P0 Public ReadOnly Property P1 As Integer Implements I.P1 End Class Class B3 Implements I Public ReadOnly Property P0 As Integer Implements I.P0 Public WriteOnly Property P1 As Integer Implements I.P1 Set End Set End Property End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected1 = <expected> BC37313: Init-only 'WriteOnly Property P0 As Integer' cannot be implemented. Public WriteOnly Property P0 As Integer Implements I.P0 ~~~~ BC37313: Init-only 'Property P1 As Integer' cannot be implemented. Public Property P1 As Integer Implements I.P1 ~~~~ BC37313: Init-only 'WriteOnly Property P0 As Integer' cannot be implemented. Public Property P0 As Integer Implements I.P0 ~~~~ BC31444: 'Property P1 As Integer' cannot be implemented by a ReadOnly property. Public ReadOnly Property P1 As Integer Implements I.P1 ~~~~ BC31444: 'WriteOnly Property P0 As Integer' cannot be implemented by a ReadOnly property. Public ReadOnly Property P0 As Integer Implements I.P0 ~~~~ BC31444: 'Property P1 As Integer' cannot be implemented by a WriteOnly property. Public WriteOnly Property P1 As Integer Implements I.P1 ~~~~ BC37313: Init-only 'Property P1 As Integer' cannot be implemented. Public WriteOnly Property P1 As Integer Implements I.P1 ~~~~ </expected> comp1.AssertTheseDiagnostics(expected1) Dim p0Set = comp1.GetMember(Of PropertySymbol)("B1.P0").SetMethod Assert.False(p0Set.IsInitOnly) Dim p1Set = comp1.GetMember(Of PropertySymbol)("B1.P1").SetMethod Assert.False(p1Set.IsInitOnly) Assert.False(comp1.GetMember(Of PropertySymbol)("B2.P0").SetMethod.IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics(expected1) End Sub <Fact> Public Sub Implementing_02() Dim csSource = " public interface I { int this[int x] { init; } int this[short x] { init; get; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Class B1 Implements I Public WriteOnly Property Item(x As Integer) As Integer Implements I.Item Set End Set End Property Public Property Item(x As Short) As Integer Implements I.Item Get Return Nothing End Get Set End Set End Property End Class Class B2 Implements I Public Property Item(x As Integer) As Integer Implements I.Item Get Return Nothing End Get Set End Set End Property Public ReadOnly Property Item(x As Short) As Integer Implements I.Item Get Return Nothing End Get End Property End Class Class B3 Implements I Public ReadOnly Property Item(x As Integer) As Integer Implements I.Item Get Return Nothing End Get End Property Public WriteOnly Property Item(x As Short) As Integer Implements I.Item Set End Set End Property End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected1 = <expected> BC37313: Init-only 'WriteOnly Default Property Item(x As Integer) As Integer' cannot be implemented. Public WriteOnly Property Item(x As Integer) As Integer Implements I.Item ~~~~~~ BC37313: Init-only 'Default Property Item(x As Short) As Integer' cannot be implemented. Public Property Item(x As Short) As Integer Implements I.Item ~~~~~~ BC37313: Init-only 'WriteOnly Default Property Item(x As Integer) As Integer' cannot be implemented. Public Property Item(x As Integer) As Integer Implements I.Item ~~~~~~ BC31444: 'Default Property Item(x As Short) As Integer' cannot be implemented by a ReadOnly property. Public ReadOnly Property Item(x As Short) As Integer Implements I.Item ~~~~~~ BC31444: 'WriteOnly Default Property Item(x As Integer) As Integer' cannot be implemented by a ReadOnly property. Public ReadOnly Property Item(x As Integer) As Integer Implements I.Item ~~~~~~ BC31444: 'Default Property Item(x As Short) As Integer' cannot be implemented by a WriteOnly property. Public WriteOnly Property Item(x As Short) As Integer Implements I.Item ~~~~~~ BC37313: Init-only 'Default Property Item(x As Short) As Integer' cannot be implemented. Public WriteOnly Property Item(x As Short) As Integer Implements I.Item ~~~~~~ </expected> comp1.AssertTheseDiagnostics(expected1) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics(expected1) End Sub <Fact> Public Sub Implementing_03() Dim csSource = " public interface I { int P0 { set; get; } int P1 { init; get; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Class B2 Implements I Public Property P0 As Integer Implements I.P0, I.P1 End Class Class B3 Implements I Public Property P0 As Integer Implements I.P1, I.P0 End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected1 = <expected> BC37313: Init-only 'Property P1 As Integer' cannot be implemented. Public Property P0 As Integer Implements I.P0, I.P1 ~~~~ BC37313: Init-only 'Property P1 As Integer' cannot be implemented. Public Property P0 As Integer Implements I.P1, I.P0 ~~~~ </expected> comp1.AssertTheseDiagnostics(expected1) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics(expected1) End Sub <Fact()> Public Sub Implementing_04() Dim ilSource = <![CDATA[ .class interface public abstract auto ansi CL1 { .method public hidebysig newslot specialname abstract virtual instance int32 get_P() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void set_P(int32 x) cil managed { } .property instance int32 P() { .get instance int32 CL1::get_P() .set instance void CL1::set_P(int32) } .method public hidebysig newslot specialname abstract virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(int32 x) cil managed { } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL1::get_P() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL1::set_P(int32) } } // end of class CL1 .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Implements CL1 Property P As Integer Implements CL1.P End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30149: Class 'Test' must implement 'Property P As Integer' for interface 'CL1'. Implements CL1 ~~~ BC30937: Member 'CL1.P' that matches this signature cannot be implemented because the interface 'CL1' contains multiple members with this same name and signature: 'Property P As Integer' 'Property P As Integer' Property P As Integer Implements CL1.P ~~~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("Test.P") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.False(pSet.ExplicitInterfaceImplementations.Single().IsInitOnly) Assert.Empty(pSet.ExplicitInterfaceImplementations.Single().ReturnTypeCustomModifiers) Assert.Empty(p.GetMethod.ExplicitInterfaceImplementations.Single().ReturnTypeCustomModifiers) Assert.Empty(p.ExplicitInterfaceImplementations.Single().TypeCustomModifiers) End Sub <Fact()> Public Sub Implementing_05() Dim ilSource = <![CDATA[ .class interface public abstract auto ansi CL1 { .method public hidebysig newslot specialname abstract virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(int32 x) cil managed { } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL1::get_P() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL1::set_P(int32) } .method public hidebysig newslot specialname abstract virtual instance int32 get_P() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void set_P(int32 x) cil managed { } .property instance int32 P() { .get instance int32 CL1::get_P() .set instance void CL1::set_P(int32) } } // end of class CL1 .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Implements CL1 Property P As Integer Implements CL1.P End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30149: Class 'Test' must implement 'Property P As Integer' for interface 'CL1'. Implements CL1 ~~~ BC30937: Member 'CL1.P' that matches this signature cannot be implemented because the interface 'CL1' contains multiple members with this same name and signature: 'Property P As Integer' 'Property P As Integer' Property P As Integer Implements CL1.P ~~~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("Test.P") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.True(pSet.ExplicitInterfaceImplementations.Single().IsInitOnly) Assert.NotEmpty(pSet.ExplicitInterfaceImplementations.Single().ReturnTypeCustomModifiers) Assert.NotEmpty(p.GetMethod.ExplicitInterfaceImplementations.Single().ReturnTypeCustomModifiers) Assert.NotEmpty(p.ExplicitInterfaceImplementations.Single().TypeCustomModifiers) End Sub <Fact> Public Sub LateBound_01() Dim csSource = " public class C { public int P0 { init; get; } public int P1 { init; get; } public int P2 { init; get; } public int P3 { init; get; } private int[] _item = new int[10]; public int this[int x] { init => _item[x] = value; get => _item[x]; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() Dim ob As Object = b Dim x = new C() Dim ox As Object = x ox.P0 = -40 b.Init(ox.P1, -41) ob.Init(x.P2, -42) ob.Init(ox.P3, -43) ox(0) = 40 ox.Item(1) = 41 b.Init(ox(2), 42) ob.Init(x(3), 43) b.Init(ox.Item(4), 44) ob.Init(x.Item(5), 45) ob.Init(ox(6), 46) ob.Init(ox.Item(7), 47) System.Console.Write(x.P0) System.Console.Write(" ") System.Console.Write(x.P1) System.Console.Write(" ") System.Console.Write(x.P2) System.Console.Write(" ") System.Console.Write(x.P3) For i as Integer = 0 To 7 System.Console.Write(" ") System.Console.Write(x(i)) Next End Sub End Class Class B Public Sub Init(ByRef p as Integer, val As Integer) p = val End Sub End Class ]]></file> </compilation> Dim expectedOutput As String = "-40 -41 0 -43 40 41 42 0 44 0 46 47" Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:=expectedOutput).VerifyDiagnostics() Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp2, expectedOutput:=expectedOutput).VerifyDiagnostics() End Sub <Fact> Public Sub LateBound_02() Dim csSource = " public class C { private int[] _item = new int[12]; public int this[int x] { init => _item[x] = value; get => _item[x]; } public int this[short x] { init => throw null; get => throw null; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() Dim ob As Object = b Dim x = new C() Dim ox As Object = x ox(0) = 40 ox.Item(1) = 41 x(CObj(2)) = 42 x.Item(CObj(3)) = 43 b.Init(ox(4), 44) ob.Init(ox(5), 45) b.Init(ox.Item(6), 46) ob.Init(ox.Item(7), 47) b.Init(x(CObj(8)), 48) ob.Init(x(CObj(9)), 49) b.Init(x.Item(CObj(10)), 50) ob.Init(x.Item(CObj(11)), 51) System.Console.Write(x(0)) For i as Integer = 1 To 11 System.Console.Write(" ") System.Console.Write(x(i)) Next End Sub End Class Class B Public Sub Init(ByRef p as Integer, val As Integer) p = val End Sub End Class ]]></file> </compilation> Dim expectedOutput As String = "40 41 42 43 44 45 46 47 48 49 50 51" Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:=expectedOutput).VerifyDiagnostics() Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp2, expectedOutput:=expectedOutput).VerifyDiagnostics() End Sub <Fact> Public Sub Redim_01() Dim csSource = " public class C { public int[] Property0 { init; get; } public int[] Property1 { init; get; } public int[] Property2 { init; get; } public int[] Property3 { init; get; } public int[] Property4 { init; get; } public int[] Property5 { init; get; } public int[] Property6 { init; get; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.Property0.Length) System.Console.Write(" "c) System.Console.Write(b.Property3.Length) System.Console.Write(" "c) System.Console.Write(b.Property4.Length) System.Console.Write(" "c) System.Console.Write(b.Property5.Length) System.Console.Write(" "c) System.Console.Write(b.Property6.Length) End Sub End Class Class B Inherits C Public Sub New() ReDim Property0(41) Redim Me.Property3(44), MyBase.Property4(45), MyClass.Property5(46) With Me Redim .Property6(47) End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16_9, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="42 45 46 47 48").VerifyDiagnostics() Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. ReDim Property0(41) ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Redim Me.Property3(44), MyBase.Property4(45), MyClass.Property5(46) ~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Redim Me.Property3(44), MyBase.Property4(45), MyClass.Property5(46) ~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Redim Me.Property3(44), MyBase.Property4(45), MyClass.Property5(46) ~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Redim .Property6(47) ~~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() ReDim x.Property1(42) With New B() Redim .Property2(43) End With Dim y As New B() With { .F = Sub() ReDim .Property3(44) End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y Redim .Property4(45) End With With Me With y Redim .Property6(47) End With End With Dim x as New B() Redim x.Property0(41) Dim z = Sub() Redim Property5(46) End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Property1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim x.Property1(42) ~~~~~~~~~~~ BC37311: Init-only property 'Property2' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Redim .Property2(43) ~~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim .Property3(44) ~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Redim .Property4(45) ~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Redim .Property6(47) ~~~~~~~~~~ BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Redim x.Property0(41) ~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Redim Property5(46) ~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() ReDim Property0(41) ReDim Me.Property3(44), MyBase.Property4(45), MyClass.Property5(46) With Me ReDim .Property6(47) End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Property0(41) ~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Me.Property3(44), MyBase.Property4(45), MyClass.Property5(46) ~~~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Me.Property3(44), MyBase.Property4(45), MyClass.Property5(46) ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Me.Property3(44), MyBase.Property4(45), MyClass.Property5(46) ~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim .Property6(47) ~~~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub Redim_02() Dim csSource = " public class C { private int[][] _item = new int[6][]; public int[] this[int x] { init { _item[x] = value; } get => _item[x]; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() for i as Integer = 0 To 5 System.Console.Write(b(i).Length) System.Console.Write(" "c) Next End Sub End Class Class B Inherits C Public Sub New() ReDim Item(0)(40) ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) With Me ReDim .Item(5)(45) End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16_9, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="41 42 43 44 45 46").VerifyDiagnostics() Assert.True(DirectCast(comp1.GetMember(Of PropertySymbol)("C.Item").SetMethod, IMethodSymbol).IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. ReDim Item(0)(40) ~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) ~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) ~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. ReDim .Item(5)(45) ~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() ReDim x(0)(40) ReDim x.Item(1)(41) With New B() ReDim .Item(2)(42) End With Dim y As New B() With { .F = Sub() ReDim .Item(3)(43) End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y ReDim .Item(4)(44) End With With Me With y ReDim .Item(5)(45) End With End With Dim x as New B() ReDim x(6)(46) ReDim x.Item(7)(47) Dim z = Sub() ReDim Item(8)(48) ReDim Me(9)(49) End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim x(0)(40) ~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim x.Item(1)(41) ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim .Item(2)(42) ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim .Item(3)(43) ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim .Item(4)(44) ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim .Item(5)(45) ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim x(6)(46) ~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim x.Item(7)(47) ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Item(8)(48) ~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Me(9)(49) ~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() ReDim Item(0)(40) ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) With Me ReDim .Item(5)(45) End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Item(0)(40) ~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) ~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) ~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim .Item(5)(45) ~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub Erase_01() Dim csSource = " public class C { public int[] Property0 { init; get; } = new int[] {}; public int[] Property1 { init; get; } = new int[] {}; public int[] Property2 { init; get; } = new int[] {}; public int[] Property3 { init; get; } = new int[] {}; public int[] Property4 { init; get; } = new int[] {}; public int[] Property5 { init; get; } = new int[] {}; public int[] Property6 { init; get; } = new int[] {}; } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.Property0 Is Nothing) System.Console.Write(" "c) System.Console.Write(b.Property3 Is Nothing) System.Console.Write(" "c) System.Console.Write(b.Property4 Is Nothing) System.Console.Write(" "c) System.Console.Write(b.Property5 Is Nothing) System.Console.Write(" "c) System.Console.Write(b.Property6 Is Nothing) End Sub End Class Class B Inherits C Public Sub New() Erase Property0 Erase Me.Property3, MyBase.Property4, MyClass.Property5 With Me Erase .Property6 End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16_9, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="True True True True True").VerifyDiagnostics() Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase Property0 ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase Me.Property3, MyBase.Property4, MyClass.Property5 ~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase Me.Property3, MyBase.Property4, MyClass.Property5 ~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase Me.Property3, MyBase.Property4, MyClass.Property5 ~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase .Property6 ~~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() Erase x.Property1 With New B() Erase .Property2 End With Dim y As New B() With { .F = Sub() Erase .Property3 End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y Erase .Property4 End With With Me With y Erase .Property6 End With End With Dim x as New B() Erase x.Property0 Dim z = Sub() Erase Property5 End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Property1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase x.Property1 ~~~~~~~~~~~ BC37311: Init-only property 'Property2' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Property2 ~~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Property3 ~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Property4 ~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Property6 ~~~~~~~~~~ BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase x.Property0 ~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Property5 ~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() Erase Property0 Erase Me.Property3, MyBase.Property4, MyClass.Property5 With Me Erase .Property6 End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Property0 ~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Me.Property3, MyBase.Property4, MyClass.Property5 ~~~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Me.Property3, MyBase.Property4, MyClass.Property5 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Me.Property3, MyBase.Property4, MyClass.Property5 ~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Property6 ~~~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub Erase_02() Dim csSource = " public class C { private int[][] _item = new int[6][] {new int[]{}, new int[]{}, new int[]{}, new int[]{}, new int[]{}, new int[]{}}; public int[] this[int x] { init { _item[x] = value; } get => _item[x]; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() for i as Integer = 0 To 5 System.Console.Write(b(i) Is Nothing) System.Console.Write(" "c) Next End Sub End Class Class B Inherits C Public Sub New() Erase Item(0) Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) With Me Erase .Item(5) End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16_9, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="True True True True True True ").VerifyDiagnostics() Assert.True(DirectCast(comp1.GetMember(Of PropertySymbol)("C.Item").SetMethod, IMethodSymbol).IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase Item(0) ~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) ~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) ~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase .Item(5) ~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() Erase x(0) Erase x.Item(1) With New B() Erase .Item(2) End With Dim y As New B() With { .F = Sub() Erase .Item(3) End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y Erase .Item(4) End With With Me With y Erase .Item(5) End With End With Dim x as New B() Erase x(6) Erase x.Item(7) Dim z = Sub() Erase Item(8) Erase Me(9) End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase x(0) ~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase x.Item(1) ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Item(2) ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Item(3) ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Item(4) ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Item(5) ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase x(6) ~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase x.Item(7) ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Item(8) ~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Me(9) ~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() Erase Item(0) Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) With Me Erase .Item(5) End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Item(0) ~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) ~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) ~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Item(5) ~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub DictionaryAccess_01() Dim csSource = " public class C { private int[] _item = new int[36]; public int this[string id] { init { int x = int.Parse(id.Substring(1, id.Length - 1)); if (x != 1 && x != 5 && x != 7 && x != 8) { throw new System.InvalidOperationException(); } _item[x] = value; } get { int x = int.Parse(id.Substring(1, id.Length - 1)); return _item[x]; } } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() B.Init(b!c9, 49) B.Init((b!c19), 59) With b B.Init(!c11, 51) B.Init((!c21), 61) End With for i as Integer = 0 To 35 System.Console.Write(b("c" & i)) System.Console.Write(" "c) Next End Sub End Class Class B Inherits C Public Sub New() Me!c1 = 41 With Me !c5 = 45 End With Init(Me!c7, 47) Init((Me!c23), 63) Dim b = Me Init(b!c12, 52) Init((b!c24), 64) With Me Init(!c8, 48) Init((!c26), 66) End With With b Init(!c14, 54) Init((!c27), 67) End With Test() Dim d = Sub() Init(Me!c34, 74) Init((Me!c35), 75) End Sub d() End Sub Public Sub Test() With Me Init(!c15, 55) Init((!c28), 68) End With Init(Me!c16, 56) Init((Me!c29), 69) Dim b = Me With b Init(!c18, 58) Init((!c31), 71) End With End Sub Public Shared Sub Init(ByRef p as Integer, val As Integer) p = val End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16_9, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="0 41 0 0 0 45 0 47 48 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0").VerifyDiagnostics() Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. B.Init(b!c9, 49) ~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. B.Init(!c11, 51) ~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me!c1 = 41 ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. !c5 = 45 ~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Me!c7, 47) ~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(b!c12, 52) ~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(!c8, 48) ~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(!c14, 54) ~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Me!c34, 74) ~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(!c15, 55) ~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Me!c16, 56) ~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(!c18, 58) ~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() x!c0 = 40 With New B() !c2 = 42 End With Dim y As New B() With { .F = Sub() !c3 = 43 End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y !c4 = 44 End With With Me With y !c5 = 45 End With End With Dim x as New B() x!c6 = 46 Dim z = Sub() Me!c9 = 49 End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x!c0 = 40 ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. !c2 = 42 ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. !c3 = 43 ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. !c4 = 44 ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. !c5 = 45 ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x!c6 = 46 ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me!c9 = 49 ~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() Me!c1 = 41 With Me !c5 = 45 End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me!c1 = 41 ~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. !c5 = 45 ~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact()> <WorkItem(50327, "https://github.com/dotnet/roslyn/issues/50327")> Public Sub ModReqOnSetAccessorParameter() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance void set_Property1 ( int32 modreq(System.Runtime.CompilerServices.IsExternalInit) 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 Property1() { .set instance void C::set_Property1(int32 modreq(System.Runtime.CompilerServices.IsExternalInit)) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Inherits C Public Overrides WriteOnly Property Property1 As Integer Set End Set End Property Sub M(c As C) c.Property1 = 42 c.set_Property1(43) End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30657: 'Property1' has a return type that is not supported or parameter types that are not supported. Set ~~~ BC30657: 'Property1' has a return type that is not supported or parameter types that are not supported. c.Property1 = 42 ~~~~~~~~~~~ BC30456: 'set_Property1' is not a member of 'C'. c.set_Property1(43) ~~~~~~~~~~~~~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("C.Property1") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.NotNull(pSet.GetUseSiteErrorInfo()) Assert.True(pSet.HasUnsupportedMetadata) Assert.Null(p.GetUseSiteErrorInfo()) Assert.False(p.HasUnsupportedMetadata) End Sub <Fact()> Public Sub ModReqOnSetAccessorParameter_AndProperty() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance void set_Property1 ( int32 modreq(System.Runtime.CompilerServices.IsExternalInit) 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit) Property1() { .set instance void C::set_Property1(int32 modreq(System.Runtime.CompilerServices.IsExternalInit)) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Inherits C Public Overrides WriteOnly Property Property1 As Integer Set End Set End Property Sub M(c As C) c.Property1 = 42 c.set_Property1(43) End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30643: Property 'C.Property1' is of an unsupported type. Public Overrides WriteOnly Property Property1 As Integer ~~~~~~~~~ BC30643: Property 'C.Property1' is of an unsupported type. c.Property1 = 42 ~~~~~~~~~ BC30456: 'set_Property1' is not a member of 'C'. c.set_Property1(43) ~~~~~~~~~~~~~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("C.Property1") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.NotNull(pSet.GetUseSiteErrorInfo()) Assert.True(pSet.HasUnsupportedMetadata) Assert.NotNull(p.GetUseSiteErrorInfo()) Assert.True(p.HasUnsupportedMetadata) End Sub <Fact()> Public Sub ModReqOnStaticMethod() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig static void modreq(System.Runtime.CompilerServices.IsExternalInit) M () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Sub M() C.M() End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30657: 'M' has a return type that is not supported or parameter types that are not supported. C.M() ~ </expected>) Dim m = compilation.GetMember(Of MethodSymbol)("C.M") Assert.False(m.IsInitOnly) Assert.NotNull(m.GetUseSiteErrorInfo()) Assert.True(m.HasUnsupportedMetadata) End Sub <Fact()> Public Sub ModReqOnInstanceMethod() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig instance void modreq(System.Runtime.CompilerServices.IsExternalInit) M () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Sub M(c As C) c.M() End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30657: 'M' has a return type that is not supported or parameter types that are not supported. c.M() ~ </expected>) Dim m = compilation.GetMember(Of MethodSymbol)("C.M") Assert.False(m.IsInitOnly) Assert.NotNull(m.GetUseSiteErrorInfo()) Assert.True(m.HasUnsupportedMetadata) End Sub <Fact()> Public Sub ModReqOnStaticSet() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig newslot specialname static void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(int32 x) cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 P() { .set void modreq(System.Runtime.CompilerServices.IsExternalInit) C::set_P(int32) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Sub M() C.P = 2 End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30657: 'P' has a return type that is not supported or parameter types that are not supported. C.P = 2 ~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("C.P") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.NotNull(pSet.GetUseSiteErrorInfo()) Assert.True(pSet.HasUnsupportedMetadata) Assert.Null(p.GetUseSiteErrorInfo()) Assert.False(p.HasUnsupportedMetadata) End Sub <Fact()> Public Sub ModReqOnSetterOfRefProperty() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance int32& get_Property1 () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname newslot virtual instance void set_Property1 ( int32& modreq(System.Runtime.CompilerServices.IsExternalInit) 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32& Property1() { .get instance int32& C::get_Property1() .set instance void C::set_Property1(int32& modreq(System.Runtime.CompilerServices.IsExternalInit)) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Sub M(c As C, ByRef i as Integer) Dim x1 = c.get_Property1() c.set_Property(i) Dim x2 = c.Property1 c.Property1 = i End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30456: 'get_Property1' is not a member of 'C'. Dim x1 = c.get_Property1() ~~~~~~~~~~~~~~~ BC30456: 'set_Property' is not a member of 'C'. c.set_Property(i) ~~~~~~~~~~~~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("C.Property1") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.NotNull(pSet.GetUseSiteErrorInfo()) Assert.True(pSet.HasUnsupportedMetadata) Assert.Null(p.GetUseSiteErrorInfo()) Assert.False(p.HasUnsupportedMetadata) End Sub <Fact()> Public Sub ModReqOnRefProperty_OnRefReturn() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance int32& modreq(System.Runtime.CompilerServices.IsExternalInit) get_Property1 () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname newslot virtual instance void set_Property1 ( int32& modreq(System.Runtime.CompilerServices.IsExternalInit) 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32& modreq(System.Runtime.CompilerServices.IsExternalInit) Property1() { .get instance int32& modreq(System.Runtime.CompilerServices.IsExternalInit) C::get_Property1() .set instance void C::set_Property1(int32& modreq(System.Runtime.CompilerServices.IsExternalInit)) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Sub M(c As C, ByRef i as Integer) Dim x1 = c.get_Property1() c.set_Property(i) Dim x2 = c.Property1 c.Property1 = i End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30456: 'get_Property1' is not a member of 'C'. Dim x1 = c.get_Property1() ~~~~~~~~~~~~~~~ BC30456: 'set_Property' is not a member of 'C'. c.set_Property(i) ~~~~~~~~~~~~~~ BC30643: Property 'C.Property1' is of an unsupported type. Dim x2 = c.Property1 ~~~~~~~~~ BC30643: Property 'C.Property1' is of an unsupported type. c.Property1 = i ~~~~~~~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("C.Property1") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.NotNull(pSet.GetUseSiteErrorInfo()) Assert.True(pSet.HasUnsupportedMetadata) Dim pGet = p.GetMethod Assert.False(pGet.IsInitOnly) Assert.NotNull(pGet.GetUseSiteErrorInfo()) Assert.True(pGet.HasUnsupportedMetadata) Assert.NotNull(p.GetUseSiteErrorInfo()) Assert.True(p.HasUnsupportedMetadata) End Sub <Fact()> Public Sub ModReqOnRefProperty_OnReturn() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit)& get_Property1 () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname newslot virtual instance void set_Property1 ( int32 modreq(System.Runtime.CompilerServices.IsExternalInit)& 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit)& Property1() { .get instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit)& C::get_Property1() .set instance void C::set_Property1(int32 modreq(System.Runtime.CompilerServices.IsExternalInit)&) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Sub M(c As C, ByRef i as Integer) Dim x1 = c.get_Property1() c.set_Property(i) Dim x2 = c.Property1 c.Property1 = i End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30456: 'get_Property1' is not a member of 'C'. Dim x1 = c.get_Property1() ~~~~~~~~~~~~~~~ BC30456: 'set_Property' is not a member of 'C'. c.set_Property(i) ~~~~~~~~~~~~~~ BC30643: Property 'C.Property1' is of an unsupported type. Dim x2 = c.Property1 ~~~~~~~~~ BC30643: Property 'C.Property1' is of an unsupported type. c.Property1 = i ~~~~~~~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("C.Property1") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.NotNull(pSet.GetUseSiteErrorInfo()) Assert.True(pSet.HasUnsupportedMetadata) Dim pGet = p.GetMethod Assert.False(pGet.IsInitOnly) Assert.NotNull(pGet.GetUseSiteErrorInfo()) Assert.True(pGet.HasUnsupportedMetadata) Assert.NotNull(p.GetUseSiteErrorInfo()) Assert.True(p.HasUnsupportedMetadata) End Sub <Fact()> <WorkItem(50327, "https://github.com/dotnet/roslyn/issues/50327")> Public Sub ModReqOnGetAccessorReturnValue() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit) get_Property1 () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname newslot virtual instance void set_Property1 ( int32 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 Property1() { .get instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit) C::get_Property1() .set instance void C::set_Property1(int32) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Inherits C Overrides Property Property1 As Integer Sub M(c As C) Dim x1 = c.get_Property1() c.set_Property(1) Dim x2 = c.Property1 c.Property1 = 2 End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30657: 'Property1' has a return type that is not supported or parameter types that are not supported. Overrides Property Property1 As Integer ~~~~~~~~~ BC30456: 'get_Property1' is not a member of 'C'. Dim x1 = c.get_Property1() ~~~~~~~~~~~~~~~ BC30456: 'set_Property' is not a member of 'C'. c.set_Property(1) ~~~~~~~~~~~~~~ BC30657: 'Property1' has a return type that is not supported or parameter types that are not supported. Dim x2 = c.Property1 ~~~~~~~~~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("C.Property1") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.Null(pSet.GetUseSiteErrorInfo()) Assert.False(pSet.HasUnsupportedMetadata) Dim pGet = p.GetMethod Assert.False(pGet.IsInitOnly) Assert.NotNull(pGet.GetUseSiteErrorInfo()) Assert.True(pGet.HasUnsupportedMetadata) Assert.Null(p.GetUseSiteErrorInfo()) Assert.False(p.HasUnsupportedMetadata) End Sub <Fact()> Public Sub ModReqOnPropertyAndGetAccessorReturnValue() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit) get_Property1 () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname newslot virtual instance void set_Property1 ( int32 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit) Property1() { .get instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit) C::get_Property1() .set instance void C::set_Property1(int32) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Inherits C Overrides Property Property1 As Integer Sub M(c As C) Dim x1 = c.get_Property1() c.set_Property(1) Dim x2 = c.Property1 c.Property1 = 2 End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30643: Property 'C.Property1' is of an unsupported type. Overrides Property Property1 As Integer ~~~~~~~~~ BC30456: 'get_Property1' is not a member of 'C'. Dim x1 = c.get_Property1() ~~~~~~~~~~~~~~~ BC30456: 'set_Property' is not a member of 'C'. c.set_Property(1) ~~~~~~~~~~~~~~ BC30643: Property 'C.Property1' is of an unsupported type. Dim x2 = c.Property1 ~~~~~~~~~ BC30643: Property 'C.Property1' is of an unsupported type. c.Property1 = 2 ~~~~~~~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("C.Property1") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.Null(pSet.GetUseSiteErrorInfo()) Assert.False(pSet.HasUnsupportedMetadata) Dim pGet = p.GetMethod Assert.False(pGet.IsInitOnly) Assert.NotNull(pGet.GetUseSiteErrorInfo()) Assert.True(pGet.HasUnsupportedMetadata) Assert.NotNull(p.GetUseSiteErrorInfo()) Assert.True(p.HasUnsupportedMetadata) End Sub <Fact()> Public Sub ModOptOnSet() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig newslot specialname instance void modopt(System.Runtime.CompilerServices.IsExternalInit) set_P(int32 x) cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 P() { .set instance void modopt(System.Runtime.CompilerServices.IsExternalInit) C::set_P(int32) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Shared Sub M(c As C) c.P = 2 End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) CompileAndVerify(compilation).VerifyDiagnostics() Dim p = compilation.GetMember(Of PropertySymbol)("C.P") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.Null(pSet.GetUseSiteErrorInfo()) Assert.False(pSet.HasUnsupportedMetadata) Assert.Null(p.GetUseSiteErrorInfo()) Assert.False(p.HasUnsupportedMetadata) End Sub <Theory, InlineData("Runtime.CompilerServices.IsExternalInit"), InlineData("CompilerServices.IsExternalInit"), InlineData("IsExternalInit"), InlineData("ns.System.Runtime.CompilerServices.IsExternalInit"), InlineData("system.Runtime.CompilerServices.IsExternalInit"), InlineData("System.runtime.CompilerServices.IsExternalInit"), InlineData("System.Runtime.compilerServices.IsExternalInit"), InlineData("System.Runtime.CompilerServices.isExternalInit") > Public Sub IsExternalInitCheck(modifierName As String) Dim ilSource = " .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig newslot specialname instance void modreq(" + modifierName + ") set_P(int32 x) cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 P() { .set instance void modreq(" + modifierName + ") C::set_P(int32) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit " + modifierName + " extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } " Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Sub M(c As C) c.P = 2 End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30657: 'P' has a return type that is not supported or parameter types that are not supported. c.P = 2 ~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("C.P") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.NotNull(pSet.GetUseSiteErrorInfo()) Assert.True(pSet.HasUnsupportedMetadata) Assert.Null(p.GetUseSiteErrorInfo()) Assert.False(p.HasUnsupportedMetadata) End Sub <Fact()> Public Sub IsInitOnlyValue() Dim vbSource1 = <compilation> <file name="c.vb"><![CDATA[ ]]> </file> </compilation> Dim compilation1 = CreateCompilation(vbSource1, options:=TestOptions.ReleaseDll) Dim vbSource2 = <compilation> <file name="c.vb"><![CDATA[ Class Test1(Of T) Public Shared Sub M1() Dim x as Integer = 0 x.DoSomething() End Sub Public Function M2() As System.Action return Sub() End Sub End Function Public Property P As Integer End Class Class Test2 Inherits Test1(Of Integer) End Class Delegate Sub D() Module Ext <System.Runtime.CompilerServices.Extension> Sub DoSomething(x As Integer) End Sub End Module ]]> </file> </compilation> Dim compilation2 = CreateCompilation(vbSource2, references:={compilation1.ToMetadataReference()}, options:=TestOptions.ReleaseDll) Dim tree = compilation2.SyntaxTrees.Single() Dim model = compilation2.GetSemanticModel(tree) Dim lambda = tree.GetRoot.DescendantNodes().OfType(Of LambdaExpressionSyntax)().Single() Assert.False(DirectCast(model.GetSymbolInfo(lambda).Symbol, MethodSymbol).IsInitOnly) Dim invocation = tree.GetRoot.DescendantNodes().OfType(Of InvocationExpressionSyntax)().Single() Assert.False(DirectCast(model.GetSymbolInfo(invocation).Symbol, MethodSymbol).IsInitOnly) Dim verify = Sub(compilation As VisualBasicCompilation) Dim test1 = compilation.GetTypeByMetadataName("Test1`1") Dim p = test1.GetMember(Of PropertySymbol)("P") Assert.False(p.SetMethod.IsInitOnly) Assert.False(p.GetMethod.IsInitOnly) Assert.False(test1.GetMember(Of MethodSymbol)("M1").IsInitOnly) Assert.False(test1.GetMember(Of MethodSymbol)("M2").IsInitOnly) Dim test1Constructed = compilation.GetTypeByMetadataName("Test2").BaseTypeNoUseSiteDiagnostics p = test1Constructed.GetMember(Of PropertySymbol)("P") Assert.False(p.SetMethod.IsInitOnly) Assert.False(p.GetMethod.IsInitOnly) Assert.False(test1Constructed.GetMember(Of MethodSymbol)("M1").IsInitOnly) Assert.False(test1Constructed.GetMember(Of MethodSymbol)("M2").IsInitOnly) Dim d = compilation.GetTypeByMetadataName("D") For Each m As MethodSymbol In d.GetMembers() Assert.False(m.IsInitOnly) Next End Sub verify(compilation2) Dim compilation3 = CreateCompilation(vbSource1, references:={compilation2.ToMetadataReference()}, options:=TestOptions.ReleaseDll) verify(compilation3) End Sub <Fact> Public Sub ReferenceConversion_01() Dim csSource = " public interface I1 { int P1 { get; init; } } public interface I2 {} public class C : I1, I2 { public int P0 { init; get; } int I1.P1 { get => P0; init => P0 = value; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.P0) End Sub End Class Class B Inherits C Public Sub New() DirectCast(Me, I1).P1 = 41 End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC37311: Init-only property 'P1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. DirectCast(Me, I1).P1 = 41 ~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub ReferenceConversion_02() Dim csSource = " public interface I1 { int P1 { get; init; } } public interface I2 {} public class C : I1, I2 { public int P0 { init; get; } int I1.P1 { get => P0; init => P0 = value; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.P0) End Sub End Class Class B Inherits C Public Sub New() With CType(Me, I1) .P1 = 41 End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC37311: Init-only property 'P1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .P1 = 41 ~~~~~~~~ </expected>) End Sub <Fact> Public Sub ReferenceConversion_03() Dim csSource = " public interface I1 { int P1 { get; init; } } public class C : I1 { public int P0 { init; get; } int I1.P1 { get => P0; init => P0 = value; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.P0) End Sub End Class Class B Inherits C Public Sub New() TryCast(Me, I1).P1 = 41 End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC37311: Init-only property 'P1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. TryCast(Me, I1).P1 = 41 ~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub ReferenceConversion_04() Dim csSource = " public interface I1 { int P1 { get; init; } } public class C : I1 { public int P0 { init; get; } int I1.P1 { get => P0; init => P0 = value; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.P0) End Sub End Class Class B Inherits C Public Sub New() With TryCast(Me, I1) .P1 = 41 End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC37311: Init-only property 'P1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .P1 = 41 ~~~~~~~~ </expected>) End Sub <Fact> Public Sub ReferenceConversion_05() Dim csSource = " public interface I1 { int P1 { get; init; } } public class C : I1 { public int P0 { init; get; } int I1.P1 { get => P0; init => P0 = value; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.P0) End Sub End Class Class B Inherits C Public Sub New() CType(MyBase, I1).P1 = 41 End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC37311: Init-only property 'P1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. CType(MyBase, I1).P1 = 41 ~~~~~~~~~~~~~~~~~~~~~~~~~ BC32027: 'MyBase' must be followed by '.' and an identifier. CType(MyBase, I1).P1 = 41 ~~~~~~ </expected>) End Sub <Fact> Public Sub ReferenceConversion_06() Dim csSource = " public interface I1 { int P1 { get; init; } } public class C : I1 { public int P0 { init; get; } int I1.P1 { get => P0; init => P0 = value; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.P0) End Sub End Class Class B Inherits C Public Sub New() DirectCast(MyClass, I1).P1 = 41 With MyClass .P0 = 1 End With With MyBase .P0 = 2 End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC37311: Init-only property 'P1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. DirectCast(MyClass, I1).P1 = 41 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC32028: 'MyClass' must be followed by '.' and an identifier. DirectCast(MyClass, I1).P1 = 41 ~~~~~~~ BC32028: 'MyClass' must be followed by '.' and an identifier. With MyClass ~~~~~~~ BC32027: 'MyBase' must be followed by '.' and an identifier. With MyBase ~~~~~~ </expected>) End Sub <Fact> Public Sub ReferenceConversion_07() Dim csSource = " public class C { public int P0 { init; get; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() End Sub End Class Class B Inherits C Public Sub New() Me.P0 = 41 End Sub End Class Class D Public Shared Widening Operator CType(x As D) As B Return Nothing End Operator Public Sub New() CType(Me, B).P0 = 42 End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC37311: Init-only property 'P0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. CType(Me, B).P0 = 42 ~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub ReferenceConversion_08() Dim csSource = " public class C { public int P0 { init; get; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.P0) End Sub End Class Class B Inherits C Public Sub New() DirectCast(Me, B).P0 = 41 End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC37311: Init-only property 'P0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. DirectCast(Me, B).P0 = 41 ~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub ReferenceConversion_09() Dim csSource = " public class C { public int P0 { init; get; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.P0) End Sub End Class Class B Inherits C Public Sub New() With CType(Me, B) .P0 = 41 End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC37311: Init-only property 'P0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .P0 = 41 ~~~~~~~~ </expected>) End Sub <Fact> Public Sub ReferenceConversion_10() Dim csSource = " public interface I1 { int P1 { get; init; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() End Sub End Class Structure B Implements I1 Public Sub New(x As Integer) DirectCast(Me, I1).P1 = 41 CType(Me, I1).P1 = 42 DirectCast(CObj(Me), I1).P1 = 43 End Sub End Structure ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC30149: Structure 'B' must implement 'Property P1 As Integer' for interface 'I1'. Implements I1 ~~ BC37311: Init-only property 'P1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. DirectCast(Me, I1).P1 = 41 ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'P1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. CType(Me, I1).P1 = 42 ~~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'P1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. DirectCast(CObj(Me), I1).P1 = 43 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics Public Class InitOnlyMemberTests Inherits BasicTestBase Protected Const IsExternalInitTypeDefinition As String = " namespace System.Runtime.CompilerServices { public static class IsExternalInit { } } " <Fact> Public Sub EvaluationInitOnlySetter_01() Dim csSource = " public class C : System.Attribute { public int Property0 { init { System.Console.Write(value + "" 0 ""); } } public int Property1 { init { System.Console.Write(value + "" 1 ""); } } public int Property2 { init { System.Console.Write(value + "" 2 ""); } } public int Property3 { init { System.Console.Write(value + "" 3 ""); } } public int Property4 { init { System.Console.Write(value + "" 4 ""); } } public int Property5 { init { System.Console.Write(value + "" 5 ""); } } public int Property6 { init { System.Console.Write(value + "" 6 ""); } } public int Property7 { init { System.Console.Write(value + "" 7 ""); } } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new B() With { .Property1 = 42, .Property2 = 43} End Sub End Class <C(Property7:= 48)> Class B Inherits C Public Sub New() Property0 = 41 Me.Property3 = 44 MyBase.Property4 = 45 MyClass.Property5 = 46 With Me .Property6 = 47 End With Me.GetType().GetCustomAttributes(False) End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="41 0 44 3 45 4 46 5 47 6 48 7 42 1 43 2 ").VerifyDiagnostics() Assert.True(DirectCast(comp1.GetMember(Of PropertySymbol)("C.Property0").SetMethod, IMethodSymbol).IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Dim x = new B() With { .Property1 = 42, .Property2 = 43} ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Dim x = new B() With { .Property1 = 42, .Property2 = 43} ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. <C(Property7:= 48)> ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Property0 = 41 ~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me.Property3 = 44 ~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyBase.Property4 = 45 ~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyClass.Property5 = 46 ~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. .Property6 = 47 ~~~~~~~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() x.Property1 = 42 With New B() .Property2 = 43 End With Dim y As New B() With { .F = Sub() .Property3 = 44 End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y .Property4 = 45 End With With Me With y .Property6 = 47 End With End With Dim x as New B() x.Property0 = 41 Dim z = Sub() Property5 = 46 End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Property1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Property1 = 42 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property2' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property2 = 43 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property3 = 44 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property4 = 45 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property6 = 47 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Property0 = 41 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Property5 = 46 ~~~~~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() Property0 = 41 Me.Property3 = 44 MyBase.Property4 = 45 MyClass.Property5 = 46 With Me .Property6 = 47 End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Property0 = 41 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me.Property3 = 44 ~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyBase.Property4 = 45 ~~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyClass.Property5 = 46 ~~~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property6 = 47 ~~~~~~~~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub EvaluationInitOnlySetter_02() Dim csSource = " public class C : System.Attribute { public int Property0 { init; get; } public int Property1 { init; get; } public int Property2 { init; get; } public int Property3 { init; get; } public int Property4 { init; get; } public int Property5 { init; get; } public int Property6 { init; get; } public int Property7 { init; get; } public int Property8 { init; get; } public int Property9 { init => throw new System.InvalidOperationException(); get => 0; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() With { .Property1 = 42 } System.Console.Write(b.Property0) System.Console.Write(" "c) System.Console.Write(b.Property1) System.Console.Write(" "c) System.Console.Write(b.Property2) System.Console.Write(" "c) System.Console.Write(b.Property3) System.Console.Write(" "c) System.Console.Write(b.Property4) System.Console.Write(" "c) System.Console.Write(b.Property5) System.Console.Write(" "c) System.Console.Write(b.Property6) System.Console.Write(" "c) System.Console.Write(DirectCast(b.GetType().GetCustomAttributes(False)(0), C).Property7) System.Console.Write(" "c) System.Console.Write(b.Property8) B.Init(b.Property9, 492) B.Init((b.Property9), 493) End Sub End Class <C(Property7:= 48)> Class B Inherits C Public Sub New() Property0 = 41 Me.Property3 = 44 MyBase.Property4 = 45 MyClass.Property5 = 46 With Me .Property6 = 47 End With Init(Property2, 43) Init((Property2), 430) With Me Init(.Property8, 49) Init((.Property9), 494) End With Dim b = Me Init(b.Property9, 490) Init((b.Property9), 491) With b Init(.Property9, 499) Init((.Property9), 450) End With Test() Dim d = Sub() Init(Property9, 600) Init((Property9), 601) End Sub d() End Sub Public Sub Test() With Me Init(.Property9, 495) Init((.Property9), 496) End With Init(Property9, 497) Init((Property9), 498) Dim b = Me With b Init(.Property9, 451) Init((.Property9), 452) End With End Sub Public Shared Sub Init(ByRef p as Integer, val As Integer) p = val End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16_9, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="41 42 43 44 45 46 47 48 49").VerifyDiagnostics() Assert.True(DirectCast(comp1.GetMember(Of PropertySymbol)("C.Property0").SetMethod, IMethodSymbol).IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Dim b = new B() With { .Property1 = 42 } ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. B.Init(b.Property9, 492) ~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. <C(Property7:= 48)> ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Property0 = 41 ~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me.Property3 = 44 ~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyBase.Property4 = 45 ~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyClass.Property5 = 46 ~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. .Property6 = 47 ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Property2, 43) ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(.Property8, 49) ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(b.Property9, 490) ~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(.Property9, 499) ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Property9, 600) ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(.Property9, 495) ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Property9, 497) ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(.Property9, 451) ~~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() x.Property1 = 42 With New B() .Property2 = 43 End With Dim y As New B() With { .F = Sub() .Property3 = 44 End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y .Property4 = 45 End With With Me With y .Property6 = 47 End With End With Dim x as New B() x.Property0 = 41 Dim z = Sub() Property5 = 46 End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Property1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Property1 = 42 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property2' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property2 = 43 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property3 = 44 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property4 = 45 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property6 = 47 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Property0 = 41 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Property5 = 46 ~~~~~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() Property0 = 41 Me.Property3 = 44 MyBase.Property4 = 45 MyClass.Property5 = 46 With Me .Property6 = 47 End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Property0 = 41 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me.Property3 = 44 ~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyBase.Property4 = 45 ~~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyClass.Property5 = 46 ~~~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property6 = 47 ~~~~~~~~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub EvaluationInitOnlySetter_03() Dim csSource = " public class C { public int this[int x] { init { System.Console.Write(value + "" ""); } } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new B() End Sub End Class Class B Inherits C Public Sub New() Item(0) = 40 Me.Item(0) = 41 MyBase.Item(0) = 42 MyClass.Item(0) = 43 Me(0) = 44 With Me .Item(0) = 45 End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="40 41 42 43 44 45 ").VerifyDiagnostics() Assert.True(DirectCast(comp1.GetMember(Of PropertySymbol)("C.Item").SetMethod, IMethodSymbol).IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Item(0) = 40 ~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me.Item(0) = 41 ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyBase.Item(0) = 42 ~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyClass.Item(0) = 43 ~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me(0) = 44 ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. .Item(0) = 45 ~~~~~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() x(0) = 40 x.Item(0) = 41 With New B() .Item(0) = 42 End With Dim y As New B() With { .F = Sub() .Item(0) = 43 End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y .Item(0) = 44 End With With Me With y .Item(0) = 45 End With End With Dim x as New B() x(0) = 46 x.Item(0) = 47 Dim z = Sub() Item(0) = 48 Me(0) = 49 End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x(0) = 40 ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Item(0) = 41 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) = 42 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) = 43 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) = 44 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) = 45 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x(0) = 46 ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Item(0) = 47 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Item(0) = 48 ~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me(0) = 49 ~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() Item(0) = 40 Me(0) = 41 Me.Item(0) = 42 MyBase.Item(0) = 43 MyClass.Item(0) = 44 With Me .Item(0) = 45 End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Item(0) = 40 ~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me(0) = 41 ~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me.Item(0) = 42 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyBase.Item(0) = 43 ~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyClass.Item(0) = 44 ~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) = 45 ~~~~~~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub EvaluationInitOnlySetter_04() Dim csSource = " public class C : System.Attribute { private int[] _item = new int[36]; public int this[int x] { init { if (x > 8) { throw new System.InvalidOperationException(); } _item[x] = value; } get => _item[x]; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() B.Init(b(9), 49) B.Init((b(19)), 59) B.Init(b.Item(10), 50) B.Init((b.Item(20)), 60) With b B.Init(.Item(11), 51) B.Init((.Item(21)), 61) End With for i as Integer = 0 To 35 System.Console.Write(b(i)) System.Console.Write(" "c) Next End Sub End Class Class B Inherits C Public Sub New() Item(0) = 40 Me(1) = 41 Me.Item(2) = 42 MyBase.Item(3) = 43 MyClass.Item(4) = 44 With Me .Item(5) = 45 End With Init(Item(6), 46) Init((Item(22)), 62) Init(Me(7), 47) Init((Me(23)), 63) Dim b = Me Init(b(12), 52) Init((b(24)), 64) Init(b.Item(13), 53) Init((b.Item(25)), 65) With Me Init(.Item(8), 48) Init((.Item(26)), 66) End With With b Init(.Item(14), 54) Init((.Item(27)), 67) End With Test() Dim d = Sub() Init(Item(32), 72) Init((Item(33)), 73) Init(Me(34), 74) Init((Me(35)), 75) End Sub d() End Sub Public Sub Test() With Me Init(.Item(15), 55) Init((.Item(28)), 68) End With Init(Me(16), 56) Init((Me(29)), 69) Init(Item(17), 57) Init((Item(30)), 70) Dim b = Me With b Init(.Item(18), 58) Init((.Item(31)), 71) End With End Sub Public Shared Sub Init(ByRef p as Integer, val As Integer) p = val End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16_9, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="40 41 42 43 44 45 46 47 48 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0").VerifyDiagnostics() Assert.True(DirectCast(comp1.GetMember(Of PropertySymbol)("C.Item").SetMethod, IMethodSymbol).IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. B.Init(b(9), 49) ~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. B.Init(b.Item(10), 50) ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. B.Init(.Item(11), 51) ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Item(0) = 40 ~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me(1) = 41 ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me.Item(2) = 42 ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyBase.Item(3) = 43 ~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyClass.Item(4) = 44 ~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. .Item(5) = 45 ~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Item(6), 46) ~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Me(7), 47) ~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(b(12), 52) ~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(b.Item(13), 53) ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(.Item(8), 48) ~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(.Item(14), 54) ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Item(32), 72) ~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Me(34), 74) ~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(.Item(15), 55) ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Me(16), 56) ~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Item(17), 57) ~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(.Item(18), 58) ~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() x(0) = 40 x.Item(1) = 41 With New B() .Item(2) = 42 End With Dim y As New B() With { .F = Sub() .Item(3) = 43 End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y .Item(4) = 44 End With With Me With y .Item(5) = 45 End With End With Dim x as New B() x(6) = 46 x.Item(7) = 47 Dim z = Sub() Item(8) = 48 Me(9) = 49 End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x(0) = 40 ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Item(1) = 41 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(2) = 42 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(3) = 43 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(4) = 44 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(5) = 45 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x(6) = 46 ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Item(7) = 47 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Item(8) = 48 ~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me(9) = 49 ~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() Item(0) = 40 Me(1) = 41 Me.Item(2) = 42 MyBase.Item(3) = 43 MyClass.Item(4) = 44 With Me .Item(5) = 45 End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Item(0) = 40 ~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me(1) = 41 ~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me.Item(2) = 42 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyBase.Item(3) = 43 ~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyClass.Item(4) = 44 ~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(5) = 45 ~~~~~~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub EvaluationInitOnlySetter_05() Dim csSource = " public class C { public int Property0 { get => 0; init { System.Console.Write(value + "" 0 ""); } } public int Property1 { get => 0; init { System.Console.Write(value + "" 1 ""); } } public int Property2 { get => 0; init { System.Console.Write(value + "" 2 ""); } } public int Property3 { get => 0; init { System.Console.Write(value + "" 3 ""); } } public int Property4 { get => 0; init { System.Console.Write(value + "" 4 ""); } } public int Property5 { get => 0; init { System.Console.Write(value + "" 5 ""); } } public int Property6 { get => 0; init { System.Console.Write(value + "" 6 ""); } } public int Property7 { get => 0; init { System.Console.Write(value + "" 7 ""); } } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x as New B() End Sub End Class Class B Inherits C Public Sub New() Property0 += 41 Me.Property3 += 44 MyBase.Property4 += 45 MyClass.Property5 += 46 With Me .Property6 += 47 End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="41 0 44 3 45 4 46 5 47 6 ").VerifyDiagnostics() Assert.True(DirectCast(comp1.GetMember(Of PropertySymbol)("C.Property0").SetMethod, IMethodSymbol).IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Property0 += 41 ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me.Property3 += 44 ~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyBase.Property4 += 45 ~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyClass.Property5 += 46 ~~~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. .Property6 += 47 ~~~~~~~~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() x.Property1 += 42 With New B() .Property2 += 43 End With Dim y As New B() With { .F = Sub() .Property3 += 44 End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y .Property4 += 45 End With With Me With y .Property6 += 47 End With End With Dim x as New B() x.Property0 += 41 Dim z = Sub() Property5 += 46 End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Property1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Property1 += 42 ~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property2' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property2 += 43 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property3 += 44 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property4 += 45 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property6 += 47 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Property0 += 41 ~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Property5 += 46 ~~~~~~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() Property0 += 41 Me.Property3 += 44 MyBase.Property4 += 45 MyClass.Property5 += 46 With Me .Property6 += 47 End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Property0 += 41 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me.Property3 += 44 ~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyBase.Property4 += 45 ~~~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyClass.Property5 += 46 ~~~~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property6 += 47 ~~~~~~~~~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub EvaluationInitOnlySetter_06() Dim csSource = " public class C { public int this[int x] { get => 0; init { System.Console.Write(value + "" ""); } } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new B() End Sub End Class Class B Inherits C Public Sub New() Item(0) += 40 Me.Item(0) += 41 MyBase.Item(0) += 42 MyClass.Item(0) += 43 Me(0) += 44 With Me .Item(0) += 45 End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="40 41 42 43 44 45 ").VerifyDiagnostics() Assert.True(DirectCast(comp1.GetMember(Of PropertySymbol)("C.Item").SetMethod, IMethodSymbol).IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Item(0) += 40 ~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me.Item(0) += 41 ~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyBase.Item(0) += 42 ~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. MyClass.Item(0) += 43 ~~~~~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me(0) += 44 ~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. .Item(0) += 45 ~~~~~~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() x(0) += 40 x.Item(0) += 41 With New B() .Item(0) += 42 End With Dim y As New B() With { .F = Sub() .Item(0) += 43 End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y .Item(0) += 44 End With With Me With y .Item(0) += 45 End With End With Dim x as New B() x(0) += 46 x.Item(0) += 47 Dim z = Sub() Item(0) += 48 Me(0) += 49 End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x(0) += 40 ~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Item(0) += 41 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) += 42 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) += 43 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) += 44 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) += 45 ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x(0) += 46 ~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Item(0) += 47 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Item(0) += 48 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me(0) += 49 ~~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() Item(0) += 40 Me(0) += 41 Me.Item(0) += 42 MyBase.Item(0) += 43 MyClass.Item(0) += 44 With Me .Item(0) += 45 End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Item(0) += 40 ~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me(0) += 41 ~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me.Item(0) += 42 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyBase.Item(0) += 43 ~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. MyClass.Item(0) += 44 ~~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Item(0) += 45 ~~~~~~~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub EvaluationInitOnlySetter_07() Dim csSource = " public interface I { public int Property1 { init; } public int Property2 { init; } public int Property3 { init; } public int Property4 { init; } public int Property5 { init; } } public class C : I { public int Property1 { init { System.Console.Write(value + "" 1 ""); } } public int Property2 { init { System.Console.Write(value + "" 2 ""); } } public int Property3 { init { System.Console.Write(value + "" 3 ""); } } public int Property4 { init { System.Console.Write(value + "" 4 ""); } } public int Property5 { init { System.Console.Write(value + "" 5 ""); } } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() M1(Of C)() M2(Of B)() End Sub Shared Sub M1(OF T As {New, I})() Dim x = new T() With { .Property1 = 42 } End Sub Shared Sub M2(OF T As {New, C})() Dim x = new T() With { .Property2 = 43 } End Sub End Class Class B Inherits C End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="42 1 43 2 ").VerifyDiagnostics() Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Dim x = new T() With { .Property1 = 42 } ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Dim x = new T() With { .Property2 = 43 } ~~~~~~~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() End Sub Shared Sub M1(Of T As {New, I})() Dim x = New T() x.Property1 = 42 With New T() .Property2 = 43 End With End Sub Shared Sub M2(Of T As {New, C})() Dim x = New T() x.Property3 = 44 With New T() .Property4 = 45 End With End Sub Shared Sub M3(x As I) x.Property5 = 46 End Sub End Class Class B Inherits C End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Property1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Property1 = 42 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property2' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property2 = 43 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Property3 = 44 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property4 = 45 ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x.Property5 = 46 ~~~~~~~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) End Sub <Fact> Public Sub EvaluationInitOnlySetter_08() Dim csSource = " using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58277"")] [CoClass(typeof(C))] public interface I { public int Property1 { init; } public int Property2 { init; } } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public class C : I { int I.Property1 { init { System.Console.Write(value + "" 1 ""); } } int I.Property2 { init { System.Console.Write(value + "" 2 ""); } } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new I() With { .Property1 = 42 } End Sub End Class Class B Inherits C End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="42 1 ").VerifyDiagnostics() Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Dim x = new I() With { .Property1 = 42 } ~~~~~~~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() With New I() .Property2 = 43 End With End Sub End Class Class B Inherits C End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Property2' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property2 = 43 ~~~~~~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) End Sub <Fact> Public Sub EvaluationInitOnlySetter_09() Dim csSource = " public class C { public int Property1 { init { System.Console.Write(value + "" 1 ""); } } public int Property2 { init { System.Console.Write(value + "" 2 ""); } } public int Property3 { init { System.Console.Write(value + "" 3 ""); } } public int Property4 { init { System.Console.Write(value + "" 4 ""); } } public int Property5 { init { System.Console.Write(value + "" 5 ""); } } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Shared Sub New() Property1 = 41 Me.Property2 = 42 MyBase.Property3 = 43 MyClass.Property4 = 44 With Me .Property5 = 45 End With End Sub End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> 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. Property1 = 41 ~~~~~~~~~ BC30043: 'Me' is valid only within an instance method. Me.Property2 = 42 ~~ BC30043: 'MyBase' is valid only within an instance method. MyBase.Property3 = 43 ~~~~~~ BC30043: 'MyClass' is valid only within an instance method. MyClass.Property4 = 44 ~~~~~~~ BC30043: 'Me' is valid only within an instance method. With Me ~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .Property5 = 45 ~~~~~~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) End Sub <Fact> Public Sub EvaluationInitOnlySetter_10() Dim csSource = " public class C { public int P2 { init { System.Console.Write(value + "" 2 ""); } } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new B() End Sub End Class Class B Inherits C Public Sub New() With (Me) .P2 = 42 End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="42 2 ").VerifyDiagnostics() End Sub <Fact> Public Sub Overriding_01() Dim csSource = " public class C { public virtual int P0 { init { } } public virtual int P1 { init; get; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Class B1 Inherits C Public Overrides WriteOnly Property P0 As Integer Set End Set End Property Public Overrides Property P1 As Integer End Class Class B2 Inherits C Public Overrides Property P0 As Integer Public Overrides ReadOnly Property P1 As Integer End Class Class B3 Inherits C Public Overrides ReadOnly Property P0 As Integer Public Overrides WriteOnly Property P1 As Integer Set End Set End Property End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected1 = <expected> BC37312: 'Public Overrides WriteOnly Property P0 As Integer' cannot override init-only 'Public Overridable Overloads WriteOnly Property P0 As Integer'. Public Overrides WriteOnly Property P0 As Integer ~~ BC37312: 'Public Overrides Property P1 As Integer' cannot override init-only 'Public Overridable Overloads Property P1 As Integer'. Public Overrides Property P1 As Integer ~~ BC30362: 'Public Overrides Property P0 As Integer' cannot override 'Public Overridable Overloads WriteOnly Property P0 As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides Property P0 As Integer ~~ BC30362: 'Public Overrides ReadOnly Property P1 As Integer' cannot override 'Public Overridable Overloads Property P1 As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides ReadOnly Property P1 As Integer ~~ BC30362: 'Public Overrides ReadOnly Property P0 As Integer' cannot override 'Public Overridable Overloads WriteOnly Property P0 As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides ReadOnly Property P0 As Integer ~~ BC30362: 'Public Overrides WriteOnly Property P1 As Integer' cannot override 'Public Overridable Overloads Property P1 As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides WriteOnly Property P1 As Integer ~~ </expected> comp1.AssertTheseDiagnostics(expected1) Dim p0Set = comp1.GetMember(Of PropertySymbol)("B1.P0").SetMethod Assert.False(p0Set.IsInitOnly) Assert.True(p0Set.OverriddenMethod.IsInitOnly) Dim p1Set = comp1.GetMember(Of PropertySymbol)("B1.P1").SetMethod Assert.False(p1Set.IsInitOnly) Assert.True(p1Set.OverriddenMethod.IsInitOnly) Assert.False(comp1.GetMember(Of PropertySymbol)("B2.P0").SetMethod.IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics(expected1) End Sub <Fact> Public Sub Overriding_02() Dim csSource = " public class C<T> { public virtual T this[int x] { init { } } public virtual T this[short x] { init {} get => throw null; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Class B1 Inherits C(Of Integer) Public Overrides WriteOnly Property Item(x as Integer) As Integer Set End Set End Property Public Overrides Property Item(x as Short) As Integer Get Return Nothing End Get Set End Set End Property End Class Class B2 Inherits C(Of Integer) Public Overrides Property Item(x as Integer) As Integer Get Return Nothing End Get Set End Set End Property Public Overrides ReadOnly Property Item(x as Short) As Integer Get Return Nothing End Get End Property End Class Class B3 Inherits C(Of Integer) Public Overrides ReadOnly Property Item(x as Integer) As Integer Get Return Nothing End Get End Property Public Overrides WriteOnly Property Item(x as Short) As Integer Set End Set End Property End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected1 = <expected> BC37312: 'Public Overrides WriteOnly Property Item(x As Integer) As Integer' cannot override init-only 'Public Overridable Overloads WriteOnly Default Property Item(x As Integer) As Integer'. Public Overrides WriteOnly Property Item(x as Integer) As Integer ~~~~ BC37312: 'Public Overrides Property Item(x As Short) As Integer' cannot override init-only 'Public Overridable Overloads Default Property Item(x As Short) As Integer'. Public Overrides Property Item(x as Short) As Integer ~~~~ BC30362: 'Public Overrides Property Item(x As Integer) As Integer' cannot override 'Public Overridable Overloads WriteOnly Default Property Item(x As Integer) As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides Property Item(x as Integer) As Integer ~~~~ BC30362: 'Public Overrides ReadOnly Property Item(x As Short) As Integer' cannot override 'Public Overridable Overloads Default Property Item(x As Short) As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides ReadOnly Property Item(x as Short) As Integer ~~~~ BC30362: 'Public Overrides ReadOnly Property Item(x As Integer) As Integer' cannot override 'Public Overridable Overloads WriteOnly Default Property Item(x As Integer) As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides ReadOnly Property Item(x as Integer) As Integer ~~~~ BC30362: 'Public Overrides WriteOnly Property Item(x As Short) As Integer' cannot override 'Public Overridable Overloads Default Property Item(x As Short) As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides WriteOnly Property Item(x as Short) As Integer ~~~~ </expected> comp1.AssertTheseDiagnostics(expected1) Dim p0Set = comp1.GetTypeByMetadataName("B1").GetMembers("Item").OfType(Of PropertySymbol).First().SetMethod Assert.False(p0Set.IsInitOnly) Assert.True(p0Set.OverriddenMethod.IsInitOnly) Assert.True(DirectCast(p0Set.OverriddenMethod, IMethodSymbol).IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics(expected1) End Sub <Fact> Public Sub Overriding_03() Dim csSource = " public class A { public virtual int P1 { init; get; } public virtual int P2 { init; get; } } public class B : A { public override int P1 { get => throw null; } public override int P2 { init {} } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Class C1 Inherits B Public Overrides WriteOnly Property P1 As Integer Set End Set End Property Public Overrides WriteOnly Property P2 As Integer Set End Set End Property End Class Class C2 Inherits B Public Overrides Property P1 As Integer Public Overrides Property P2 As Integer End Class Class C3 Inherits B Public Overrides ReadOnly Property P1 As Integer Public Overrides ReadOnly Property P2 As Integer End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected1 = <expected> BC30362: 'Public Overrides WriteOnly Property P1 As Integer' cannot override 'Public Overrides ReadOnly Property P1 As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides WriteOnly Property P1 As Integer ~~ BC37312: 'Public Overrides WriteOnly Property P2 As Integer' cannot override init-only 'Public Overrides WriteOnly Property P2 As Integer'. Public Overrides WriteOnly Property P2 As Integer ~~ BC30362: 'Public Overrides Property P1 As Integer' cannot override 'Public Overrides ReadOnly Property P1 As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides Property P1 As Integer ~~ BC30362: 'Public Overrides Property P2 As Integer' cannot override 'Public Overrides WriteOnly Property P2 As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides Property P2 As Integer ~~ BC30362: 'Public Overrides ReadOnly Property P2 As Integer' cannot override 'Public Overrides WriteOnly Property P2 As Integer' because they differ by 'ReadOnly' or 'WriteOnly'. Public Overrides ReadOnly Property P2 As Integer ~~ </expected> comp1.AssertTheseDiagnostics(expected1) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics(expected1) End Sub <Fact()> Public Sub Overriding_04() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit CL1 extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } .method public hidebysig newslot virtual instance int32 get_P() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void set_P(int32 x) cil managed { ret } .property instance int32 P() { .get instance int32 CL1::get_P() .set instance void CL1::set_P(int32) } .method public hidebysig newslot virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(int32 x) cil managed { ret } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL1::get_P() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL1::set_P(int32) } } // end of class CL1 .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Inherits CL1 Overrides Property P As Integer End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseDll) CompileAndVerify(compilation).VerifyDiagnostics() Dim p = compilation.GetMember(Of PropertySymbol)("Test.P") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.False(pSet.OverriddenMethod.IsInitOnly) Assert.Empty(pSet.OverriddenMethod.ReturnTypeCustomModifiers) Assert.Empty(p.GetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.Empty(p.OverriddenProperty.TypeCustomModifiers) End Sub <Fact()> Public Sub Overriding_05() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit CL1 extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } .method public hidebysig newslot virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(int32 x) cil managed { ret } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL1::get_P() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL1::set_P(int32) } .method public hidebysig newslot virtual instance int32 get_P() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void set_P(int32 x) cil managed { ret } .property instance int32 P() { .get instance int32 CL1::get_P() .set instance void CL1::set_P(int32) } } // end of class CL1 .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Inherits CL1 Overrides Property P As Integer End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseDll) CompileAndVerify(compilation).VerifyDiagnostics() Dim p = compilation.GetMember(Of PropertySymbol)("Test.P") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.False(pSet.OverriddenMethod.IsInitOnly) Assert.Empty(pSet.OverriddenMethod.ReturnTypeCustomModifiers) Assert.Empty(p.GetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.Empty(p.OverriddenProperty.TypeCustomModifiers) End Sub <Fact()> Public Sub Overriding_06() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit CL1 extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } .method public hidebysig newslot virtual instance int32 get_P() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void set_P(int32 x) cil managed { ret } .property instance int32 modopt(CL1) P() { .get instance int32 CL1::get_P() .set instance void CL1::set_P(int32) } .method public hidebysig newslot virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(int32 x) cil managed { ret } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL1::get_P() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL1::set_P(int32) } } // end of class CL1 .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Inherits CL1 Overrides Property P As Integer End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30935: Member 'Public Overridable Overloads Property P As Integer' that matches this signature cannot be overridden because the class 'CL1' contains multiple members with this same name and signature: 'Public Overridable Overloads Property P As Integer' 'Public Overridable Overloads Property P As Integer' Overrides Property P As Integer ~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("Test.P") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.False(pSet.OverriddenMethod.IsInitOnly) Assert.Empty(pSet.OverriddenMethod.ReturnTypeCustomModifiers) Assert.Empty(p.GetMethod.OverriddenMethod.ReturnTypeCustomModifiers) End Sub <Fact()> Public Sub Overriding_07() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit CL1 extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } .method public hidebysig newslot virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(int32 x) cil managed { ret } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL1::get_P() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL1::set_P(int32) } .method public hidebysig newslot virtual instance int32 get_P() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void set_P(int32 x) cil managed { ret } .property instance int32 modopt(CL1) P() { .get instance int32 CL1::get_P() .set instance void CL1::set_P(int32) } } // end of class CL1 .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Inherits CL1 Overrides Property P As Integer End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30935: Member 'Public Overridable Overloads Property P As Integer' that matches this signature cannot be overridden because the class 'CL1' contains multiple members with this same name and signature: 'Public Overridable Overloads Property P As Integer' 'Public Overridable Overloads Property P As Integer' Overrides Property P As Integer ~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("Test.P") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.True(pSet.OverriddenMethod.IsInitOnly) Assert.NotEmpty(pSet.OverriddenMethod.ReturnTypeCustomModifiers) Assert.NotEmpty(p.GetMethod.OverriddenMethod.ReturnTypeCustomModifiers) End Sub <Fact()> Public Sub Overriding_08() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit CL1 extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { IL_0000: ldarg.0 IL_0001: call instance void System.Object::.ctor() IL_0006: ret } .method public hidebysig newslot virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P1() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P1(int32 x) cil managed { ret } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P1() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL1::get_P1() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL1::set_P1(int32) } .method public hidebysig newslot virtual instance int32 get_P1() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void set_P1(int32 x) cil managed { ret } .property instance int32 P1() { .get instance int32 CL1::get_P1() .set instance void CL1::set_P1(int32) } .method public hidebysig newslot virtual instance int32 get_P2() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void set_P2(int32 x) cil managed { ret } .property instance int32 P2() { .get instance int32 CL1::get_P2() .set instance void CL1::set_P2(int32) } .method public hidebysig newslot virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P2() cil managed { ldc.i4.s 123 ret } .method public hidebysig newslot virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P2(int32 x) cil managed { ret } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P2() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL1::get_P2() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL1::set_P2(int32) } } // end of class CL1 .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi beforefieldinit CL2 extends CL1 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { IL_0000: ldarg.0 IL_0001: call instance void CL1::.ctor() IL_0006: ret } .method public hidebysig virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P1() cil managed { ldc.i4.s 123 ret } .method public hidebysig virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P1(int32 x) cil managed { ret } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P1() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL2::get_P1() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL2::set_P1(int32) } .method public hidebysig virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P2() cil managed { ldc.i4.s 123 ret } .method public hidebysig virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P2(int32 x) cil managed { ret } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P2() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL2::get_P2() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL2::set_P2(int32) } } .class public auto ansi beforefieldinit CL3 extends CL1 { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { IL_0000: ldarg.0 IL_0001: call instance void CL1::.ctor() IL_0006: ret } .method public hidebysig virtual instance int32 get_P1() cil managed { ldc.i4.s 123 ret } .method public hidebysig virtual instance void set_P1(int32 x) cil managed { ret } .property instance int32 P1() { .get instance int32 CL3::get_P1() .set instance void CL3::set_P1(int32) } .method public hidebysig virtual instance int32 get_P2() cil managed { ldc.i4.s 123 ret } .method public hidebysig virtual instance void set_P2(int32 x) cil managed { ret } .property instance int32 P2() { .get instance int32 CL3::get_P2() .set instance void CL3::set_P2(int32) } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ ]]></file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseDll) Dim cl2p1 = compilation.GetMember(Of PropertySymbol)("CL2.P1") Assert.NotEmpty(cl2p1.SetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.NotEmpty(cl2p1.GetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.NotEmpty(cl2p1.OverriddenProperty.TypeCustomModifiers) Dim cl2p2 = compilation.GetMember(Of PropertySymbol)("CL2.P2") Assert.NotEmpty(cl2p2.SetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.NotEmpty(cl2p2.GetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.NotEmpty(cl2p2.OverriddenProperty.TypeCustomModifiers) Dim cl3p1 = compilation.GetMember(Of PropertySymbol)("CL3.P1") Assert.Empty(cl3p1.SetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.Empty(cl3p1.GetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.Empty(cl3p1.OverriddenProperty.TypeCustomModifiers) Dim cl3p2 = compilation.GetMember(Of PropertySymbol)("CL3.P2") Assert.Empty(cl3p2.SetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.Empty(cl3p2.GetMethod.OverriddenMethod.ReturnTypeCustomModifiers) Assert.Empty(cl3p2.OverriddenProperty.TypeCustomModifiers) End Sub <Fact> Public Sub Implementing_01() Dim csSource = " public interface I { int P0 { init; } int P1 { init; get; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Class B1 Implements I Public WriteOnly Property P0 As Integer Implements I.P0 Set End Set End Property Public Property P1 As Integer Implements I.P1 End Class Class B2 Implements I Public Property P0 As Integer Implements I.P0 Public ReadOnly Property P1 As Integer Implements I.P1 End Class Class B3 Implements I Public ReadOnly Property P0 As Integer Implements I.P0 Public WriteOnly Property P1 As Integer Implements I.P1 Set End Set End Property End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected1 = <expected> BC37313: Init-only 'WriteOnly Property P0 As Integer' cannot be implemented. Public WriteOnly Property P0 As Integer Implements I.P0 ~~~~ BC37313: Init-only 'Property P1 As Integer' cannot be implemented. Public Property P1 As Integer Implements I.P1 ~~~~ BC37313: Init-only 'WriteOnly Property P0 As Integer' cannot be implemented. Public Property P0 As Integer Implements I.P0 ~~~~ BC31444: 'Property P1 As Integer' cannot be implemented by a ReadOnly property. Public ReadOnly Property P1 As Integer Implements I.P1 ~~~~ BC31444: 'WriteOnly Property P0 As Integer' cannot be implemented by a ReadOnly property. Public ReadOnly Property P0 As Integer Implements I.P0 ~~~~ BC31444: 'Property P1 As Integer' cannot be implemented by a WriteOnly property. Public WriteOnly Property P1 As Integer Implements I.P1 ~~~~ BC37313: Init-only 'Property P1 As Integer' cannot be implemented. Public WriteOnly Property P1 As Integer Implements I.P1 ~~~~ </expected> comp1.AssertTheseDiagnostics(expected1) Dim p0Set = comp1.GetMember(Of PropertySymbol)("B1.P0").SetMethod Assert.False(p0Set.IsInitOnly) Dim p1Set = comp1.GetMember(Of PropertySymbol)("B1.P1").SetMethod Assert.False(p1Set.IsInitOnly) Assert.False(comp1.GetMember(Of PropertySymbol)("B2.P0").SetMethod.IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics(expected1) End Sub <Fact> Public Sub Implementing_02() Dim csSource = " public interface I { int this[int x] { init; } int this[short x] { init; get; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Class B1 Implements I Public WriteOnly Property Item(x As Integer) As Integer Implements I.Item Set End Set End Property Public Property Item(x As Short) As Integer Implements I.Item Get Return Nothing End Get Set End Set End Property End Class Class B2 Implements I Public Property Item(x As Integer) As Integer Implements I.Item Get Return Nothing End Get Set End Set End Property Public ReadOnly Property Item(x As Short) As Integer Implements I.Item Get Return Nothing End Get End Property End Class Class B3 Implements I Public ReadOnly Property Item(x As Integer) As Integer Implements I.Item Get Return Nothing End Get End Property Public WriteOnly Property Item(x As Short) As Integer Implements I.Item Set End Set End Property End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected1 = <expected> BC37313: Init-only 'WriteOnly Default Property Item(x As Integer) As Integer' cannot be implemented. Public WriteOnly Property Item(x As Integer) As Integer Implements I.Item ~~~~~~ BC37313: Init-only 'Default Property Item(x As Short) As Integer' cannot be implemented. Public Property Item(x As Short) As Integer Implements I.Item ~~~~~~ BC37313: Init-only 'WriteOnly Default Property Item(x As Integer) As Integer' cannot be implemented. Public Property Item(x As Integer) As Integer Implements I.Item ~~~~~~ BC31444: 'Default Property Item(x As Short) As Integer' cannot be implemented by a ReadOnly property. Public ReadOnly Property Item(x As Short) As Integer Implements I.Item ~~~~~~ BC31444: 'WriteOnly Default Property Item(x As Integer) As Integer' cannot be implemented by a ReadOnly property. Public ReadOnly Property Item(x As Integer) As Integer Implements I.Item ~~~~~~ BC31444: 'Default Property Item(x As Short) As Integer' cannot be implemented by a WriteOnly property. Public WriteOnly Property Item(x As Short) As Integer Implements I.Item ~~~~~~ BC37313: Init-only 'Default Property Item(x As Short) As Integer' cannot be implemented. Public WriteOnly Property Item(x As Short) As Integer Implements I.Item ~~~~~~ </expected> comp1.AssertTheseDiagnostics(expected1) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics(expected1) End Sub <Fact> Public Sub Implementing_03() Dim csSource = " public interface I { int P0 { set; get; } int P1 { init; get; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Class B2 Implements I Public Property P0 As Integer Implements I.P0, I.P1 End Class Class B3 Implements I Public Property P0 As Integer Implements I.P1, I.P0 End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected1 = <expected> BC37313: Init-only 'Property P1 As Integer' cannot be implemented. Public Property P0 As Integer Implements I.P0, I.P1 ~~~~ BC37313: Init-only 'Property P1 As Integer' cannot be implemented. Public Property P0 As Integer Implements I.P1, I.P0 ~~~~ </expected> comp1.AssertTheseDiagnostics(expected1) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics(expected1) End Sub <Fact()> Public Sub Implementing_04() Dim ilSource = <![CDATA[ .class interface public abstract auto ansi CL1 { .method public hidebysig newslot specialname abstract virtual instance int32 get_P() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void set_P(int32 x) cil managed { } .property instance int32 P() { .get instance int32 CL1::get_P() .set instance void CL1::set_P(int32) } .method public hidebysig newslot specialname abstract virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(int32 x) cil managed { } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL1::get_P() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL1::set_P(int32) } } // end of class CL1 .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Implements CL1 Property P As Integer Implements CL1.P End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30149: Class 'Test' must implement 'Property P As Integer' for interface 'CL1'. Implements CL1 ~~~ BC30937: Member 'CL1.P' that matches this signature cannot be implemented because the interface 'CL1' contains multiple members with this same name and signature: 'Property P As Integer' 'Property P As Integer' Property P As Integer Implements CL1.P ~~~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("Test.P") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.False(pSet.ExplicitInterfaceImplementations.Single().IsInitOnly) Assert.Empty(pSet.ExplicitInterfaceImplementations.Single().ReturnTypeCustomModifiers) Assert.Empty(p.GetMethod.ExplicitInterfaceImplementations.Single().ReturnTypeCustomModifiers) Assert.Empty(p.ExplicitInterfaceImplementations.Single().TypeCustomModifiers) End Sub <Fact()> Public Sub Implementing_05() Dim ilSource = <![CDATA[ .class interface public abstract auto ansi CL1 { .method public hidebysig newslot specialname abstract virtual instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) get_P() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(int32 x) cil managed { } .property instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) P() { .get instance int32 modopt(System.Runtime.CompilerServices.IsExternalInit) CL1::get_P() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) CL1::set_P(int32) } .method public hidebysig newslot specialname abstract virtual instance int32 get_P() cil managed { } .method public hidebysig newslot specialname abstract virtual instance void set_P(int32 x) cil managed { } .property instance int32 P() { .get instance int32 CL1::get_P() .set instance void CL1::set_P(int32) } } // end of class CL1 .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Implements CL1 Property P As Integer Implements CL1.P End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30149: Class 'Test' must implement 'Property P As Integer' for interface 'CL1'. Implements CL1 ~~~ BC30937: Member 'CL1.P' that matches this signature cannot be implemented because the interface 'CL1' contains multiple members with this same name and signature: 'Property P As Integer' 'Property P As Integer' Property P As Integer Implements CL1.P ~~~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("Test.P") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.True(pSet.ExplicitInterfaceImplementations.Single().IsInitOnly) Assert.NotEmpty(pSet.ExplicitInterfaceImplementations.Single().ReturnTypeCustomModifiers) Assert.NotEmpty(p.GetMethod.ExplicitInterfaceImplementations.Single().ReturnTypeCustomModifiers) Assert.NotEmpty(p.ExplicitInterfaceImplementations.Single().TypeCustomModifiers) End Sub <Fact> Public Sub LateBound_01() Dim csSource = " public class C { public int P0 { init; get; } public int P1 { init; get; } public int P2 { init; get; } public int P3 { init; get; } private int[] _item = new int[10]; public int this[int x] { init => _item[x] = value; get => _item[x]; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() Dim ob As Object = b Dim x = new C() Dim ox As Object = x ox.P0 = -40 b.Init(ox.P1, -41) ob.Init(x.P2, -42) ob.Init(ox.P3, -43) ox(0) = 40 ox.Item(1) = 41 b.Init(ox(2), 42) ob.Init(x(3), 43) b.Init(ox.Item(4), 44) ob.Init(x.Item(5), 45) ob.Init(ox(6), 46) ob.Init(ox.Item(7), 47) System.Console.Write(x.P0) System.Console.Write(" ") System.Console.Write(x.P1) System.Console.Write(" ") System.Console.Write(x.P2) System.Console.Write(" ") System.Console.Write(x.P3) For i as Integer = 0 To 7 System.Console.Write(" ") System.Console.Write(x(i)) Next End Sub End Class Class B Public Sub Init(ByRef p as Integer, val As Integer) p = val End Sub End Class ]]></file> </compilation> Dim expectedOutput As String = "-40 -41 0 -43 40 41 42 0 44 0 46 47" Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:=expectedOutput).VerifyDiagnostics() Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp2, expectedOutput:=expectedOutput).VerifyDiagnostics() End Sub <Fact> Public Sub LateBound_02() Dim csSource = " public class C { private int[] _item = new int[12]; public int this[int x] { init => _item[x] = value; get => _item[x]; } public int this[short x] { init => throw null; get => throw null; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() Dim ob As Object = b Dim x = new C() Dim ox As Object = x ox(0) = 40 ox.Item(1) = 41 x(CObj(2)) = 42 x.Item(CObj(3)) = 43 b.Init(ox(4), 44) ob.Init(ox(5), 45) b.Init(ox.Item(6), 46) ob.Init(ox.Item(7), 47) b.Init(x(CObj(8)), 48) ob.Init(x(CObj(9)), 49) b.Init(x.Item(CObj(10)), 50) ob.Init(x.Item(CObj(11)), 51) System.Console.Write(x(0)) For i as Integer = 1 To 11 System.Console.Write(" ") System.Console.Write(x(i)) Next End Sub End Class Class B Public Sub Init(ByRef p as Integer, val As Integer) p = val End Sub End Class ]]></file> </compilation> Dim expectedOutput As String = "40 41 42 43 44 45 46 47 48 49 50 51" Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:=expectedOutput).VerifyDiagnostics() Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp2, expectedOutput:=expectedOutput).VerifyDiagnostics() End Sub <Fact> Public Sub Redim_01() Dim csSource = " public class C { public int[] Property0 { init; get; } public int[] Property1 { init; get; } public int[] Property2 { init; get; } public int[] Property3 { init; get; } public int[] Property4 { init; get; } public int[] Property5 { init; get; } public int[] Property6 { init; get; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.Property0.Length) System.Console.Write(" "c) System.Console.Write(b.Property3.Length) System.Console.Write(" "c) System.Console.Write(b.Property4.Length) System.Console.Write(" "c) System.Console.Write(b.Property5.Length) System.Console.Write(" "c) System.Console.Write(b.Property6.Length) End Sub End Class Class B Inherits C Public Sub New() ReDim Property0(41) Redim Me.Property3(44), MyBase.Property4(45), MyClass.Property5(46) With Me Redim .Property6(47) End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16_9, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="42 45 46 47 48").VerifyDiagnostics() Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. ReDim Property0(41) ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Redim Me.Property3(44), MyBase.Property4(45), MyClass.Property5(46) ~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Redim Me.Property3(44), MyBase.Property4(45), MyClass.Property5(46) ~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Redim Me.Property3(44), MyBase.Property4(45), MyClass.Property5(46) ~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Redim .Property6(47) ~~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() ReDim x.Property1(42) With New B() Redim .Property2(43) End With Dim y As New B() With { .F = Sub() ReDim .Property3(44) End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y Redim .Property4(45) End With With Me With y Redim .Property6(47) End With End With Dim x as New B() Redim x.Property0(41) Dim z = Sub() Redim Property5(46) End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Property1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim x.Property1(42) ~~~~~~~~~~~ BC37311: Init-only property 'Property2' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Redim .Property2(43) ~~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim .Property3(44) ~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Redim .Property4(45) ~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Redim .Property6(47) ~~~~~~~~~~ BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Redim x.Property0(41) ~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Redim Property5(46) ~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() ReDim Property0(41) ReDim Me.Property3(44), MyBase.Property4(45), MyClass.Property5(46) With Me ReDim .Property6(47) End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Property0(41) ~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Me.Property3(44), MyBase.Property4(45), MyClass.Property5(46) ~~~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Me.Property3(44), MyBase.Property4(45), MyClass.Property5(46) ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Me.Property3(44), MyBase.Property4(45), MyClass.Property5(46) ~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim .Property6(47) ~~~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub Redim_02() Dim csSource = " public class C { private int[][] _item = new int[6][]; public int[] this[int x] { init { _item[x] = value; } get => _item[x]; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() for i as Integer = 0 To 5 System.Console.Write(b(i).Length) System.Console.Write(" "c) Next End Sub End Class Class B Inherits C Public Sub New() ReDim Item(0)(40) ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) With Me ReDim .Item(5)(45) End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16_9, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="41 42 43 44 45 46").VerifyDiagnostics() Assert.True(DirectCast(comp1.GetMember(Of PropertySymbol)("C.Item").SetMethod, IMethodSymbol).IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. ReDim Item(0)(40) ~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) ~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) ~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. ReDim .Item(5)(45) ~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() ReDim x(0)(40) ReDim x.Item(1)(41) With New B() ReDim .Item(2)(42) End With Dim y As New B() With { .F = Sub() ReDim .Item(3)(43) End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y ReDim .Item(4)(44) End With With Me With y ReDim .Item(5)(45) End With End With Dim x as New B() ReDim x(6)(46) ReDim x.Item(7)(47) Dim z = Sub() ReDim Item(8)(48) ReDim Me(9)(49) End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim x(0)(40) ~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim x.Item(1)(41) ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim .Item(2)(42) ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim .Item(3)(43) ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim .Item(4)(44) ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim .Item(5)(45) ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim x(6)(46) ~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim x.Item(7)(47) ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Item(8)(48) ~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Me(9)(49) ~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() ReDim Item(0)(40) ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) With Me ReDim .Item(5)(45) End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Item(0)(40) ~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) ~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) ~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim Me(1)(41), Me.Item(2)(42), MyBase.Item(3)(43), MyClass.Item(4)(44) ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. ReDim .Item(5)(45) ~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub Erase_01() Dim csSource = " public class C { public int[] Property0 { init; get; } = new int[] {}; public int[] Property1 { init; get; } = new int[] {}; public int[] Property2 { init; get; } = new int[] {}; public int[] Property3 { init; get; } = new int[] {}; public int[] Property4 { init; get; } = new int[] {}; public int[] Property5 { init; get; } = new int[] {}; public int[] Property6 { init; get; } = new int[] {}; } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.Property0 Is Nothing) System.Console.Write(" "c) System.Console.Write(b.Property3 Is Nothing) System.Console.Write(" "c) System.Console.Write(b.Property4 Is Nothing) System.Console.Write(" "c) System.Console.Write(b.Property5 Is Nothing) System.Console.Write(" "c) System.Console.Write(b.Property6 Is Nothing) End Sub End Class Class B Inherits C Public Sub New() Erase Property0 Erase Me.Property3, MyBase.Property4, MyClass.Property5 With Me Erase .Property6 End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16_9, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="True True True True True").VerifyDiagnostics() Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase Property0 ~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase Me.Property3, MyBase.Property4, MyClass.Property5 ~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase Me.Property3, MyBase.Property4, MyClass.Property5 ~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase Me.Property3, MyBase.Property4, MyClass.Property5 ~~~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase .Property6 ~~~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() Erase x.Property1 With New B() Erase .Property2 End With Dim y As New B() With { .F = Sub() Erase .Property3 End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y Erase .Property4 End With With Me With y Erase .Property6 End With End With Dim x as New B() Erase x.Property0 Dim z = Sub() Erase Property5 End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Property1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase x.Property1 ~~~~~~~~~~~ BC37311: Init-only property 'Property2' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Property2 ~~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Property3 ~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Property4 ~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Property6 ~~~~~~~~~~ BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase x.Property0 ~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Property5 ~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() Erase Property0 Erase Me.Property3, MyBase.Property4, MyClass.Property5 With Me Erase .Property6 End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Property0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Property0 ~~~~~~~~~ BC37311: Init-only property 'Property3' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Me.Property3, MyBase.Property4, MyClass.Property5 ~~~~~~~~~~~~ BC37311: Init-only property 'Property4' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Me.Property3, MyBase.Property4, MyClass.Property5 ~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property5' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Me.Property3, MyBase.Property4, MyClass.Property5 ~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'Property6' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Property6 ~~~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub Erase_02() Dim csSource = " public class C { private int[][] _item = new int[6][] {new int[]{}, new int[]{}, new int[]{}, new int[]{}, new int[]{}, new int[]{}}; public int[] this[int x] { init { _item[x] = value; } get => _item[x]; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() for i as Integer = 0 To 5 System.Console.Write(b(i) Is Nothing) System.Console.Write(" "c) Next End Sub End Class Class B Inherits C Public Sub New() Erase Item(0) Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) With Me Erase .Item(5) End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16_9, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="True True True True True True ").VerifyDiagnostics() Assert.True(DirectCast(comp1.GetMember(Of PropertySymbol)("C.Item").SetMethod, IMethodSymbol).IsInitOnly) Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase Item(0) ~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) ~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) ~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) ~~~~~~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Erase .Item(5) ~~~~~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() Erase x(0) Erase x.Item(1) With New B() Erase .Item(2) End With Dim y As New B() With { .F = Sub() Erase .Item(3) End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y Erase .Item(4) End With With Me With y Erase .Item(5) End With End With Dim x as New B() Erase x(6) Erase x.Item(7) Dim z = Sub() Erase Item(8) Erase Me(9) End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase x(0) ~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase x.Item(1) ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Item(2) ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Item(3) ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Item(4) ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Item(5) ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase x(6) ~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase x.Item(7) ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Item(8) ~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Me(9) ~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() Erase Item(0) Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) With Me Erase .Item(5) End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Item(0) ~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) ~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) ~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) ~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase Me(1), Me.Item(2), MyBase.Item(3), MyClass.Item(4) ~~~~~~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Erase .Item(5) ~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact> Public Sub DictionaryAccess_01() Dim csSource = " public class C { private int[] _item = new int[36]; public int this[string id] { init { int x = int.Parse(id.Substring(1, id.Length - 1)); if (x != 1 && x != 5 && x != 7 && x != 8) { throw new System.InvalidOperationException(); } _item[x] = value; } get { int x = int.Parse(id.Substring(1, id.Length - 1)); return _item[x]; } } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() B.Init(b!c9, 49) B.Init((b!c19), 59) With b B.Init(!c11, 51) B.Init((!c21), 61) End With for i as Integer = 0 To 35 System.Console.Write(b("c" & i)) System.Console.Write(" "c) Next End Sub End Class Class B Inherits C Public Sub New() Me!c1 = 41 With Me !c5 = 45 End With Init(Me!c7, 47) Init((Me!c23), 63) Dim b = Me Init(b!c12, 52) Init((b!c24), 64) With Me Init(!c8, 48) Init((!c26), 66) End With With b Init(!c14, 54) Init((!c27), 67) End With Test() Dim d = Sub() Init(Me!c34, 74) Init((Me!c35), 75) End Sub d() End Sub Public Sub Test() With Me Init(!c15, 55) Init((!c28), 68) End With Init(Me!c16, 56) Init((Me!c29), 69) Dim b = Me With b Init(!c18, 58) Init((!c31), 71) End With End Sub Public Shared Sub Init(ByRef p as Integer, val As Integer) p = val End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16_9, options:=TestOptions.DebugExe, references:={csCompilation}) CompileAndVerify(comp1, expectedOutput:="0 41 0 0 0 45 0 47 48 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0").VerifyDiagnostics() Dim comp2 = CreateCompilation(source1, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp2.AssertTheseDiagnostics( <expected><![CDATA[ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. B.Init(b!c9, 49) ~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. B.Init(!c11, 51) ~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Me!c1 = 41 ~~~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. !c5 = 45 ~~~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Me!c7, 47) ~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(b!c12, 52) ~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(!c8, 48) ~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(!c14, 54) ~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Me!c34, 74) ~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(!c15, 55) ~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(Me!c16, 56) ~~~~~~ BC36716: Visual Basic 16 does not support assigning to or passing 'ByRef' properties with init-only setters. Init(!c18, 58) ~~~~ ]]></expected>) Dim source3 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim x = new C() x!c0 = 40 With New B() !c2 = 42 End With Dim y As New B() With { .F = Sub() !c3 = 43 End Sub} End Sub End Class Class B Inherits C Public Sub New() Dim y = new B() With y !c4 = 44 End With With Me With y !c5 = 45 End With End With Dim x as New B() x!c6 = 46 Dim z = Sub() Me!c9 = 49 End Sub End Sub Public F As System.Action End Class ]]></file> </compilation> Dim comp3 = CreateCompilation(source3, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected3 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x!c0 = 40 ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. !c2 = 42 ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. !c3 = 43 ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. !c4 = 44 ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. !c5 = 45 ~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. x!c6 = 46 ~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me!c9 = 49 ~~~~~~~~~~ </expected> comp3.AssertTheseDiagnostics(expected3) Dim comp4 = CreateCompilation(source3, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp4.AssertTheseDiagnostics(expected3) Dim source5 = <compilation> <file name="c.vb"><![CDATA[ Class B Inherits C Public Sub Test() Me!c1 = 41 With Me !c5 = 45 End With End Sub End Class ]]></file> </compilation> Dim comp5 = CreateCompilation(source5, parseOptions:=TestOptions.RegularLatest, references:={csCompilation}) Dim expected5 = <expected> BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. Me!c1 = 41 ~~~~~~~~~~ BC37311: Init-only property 'Item' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. !c5 = 45 ~~~~~~~~ </expected> comp5.AssertTheseDiagnostics(expected5) Dim comp6 = CreateCompilation(source5, parseOptions:=TestOptions.Regular16, references:={csCompilation}) comp6.AssertTheseDiagnostics(expected5) End Sub <Fact()> <WorkItem(50327, "https://github.com/dotnet/roslyn/issues/50327")> Public Sub ModReqOnSetAccessorParameter() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance void set_Property1 ( int32 modreq(System.Runtime.CompilerServices.IsExternalInit) 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 Property1() { .set instance void C::set_Property1(int32 modreq(System.Runtime.CompilerServices.IsExternalInit)) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Inherits C Public Overrides WriteOnly Property Property1 As Integer Set End Set End Property Sub M(c As C) c.Property1 = 42 c.set_Property1(43) End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30657: 'Property1' has a return type that is not supported or parameter types that are not supported. Set ~~~ BC30657: 'Property1' has a return type that is not supported or parameter types that are not supported. c.Property1 = 42 ~~~~~~~~~~~ BC30456: 'set_Property1' is not a member of 'C'. c.set_Property1(43) ~~~~~~~~~~~~~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("C.Property1") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.NotNull(pSet.GetUseSiteErrorInfo()) Assert.True(pSet.HasUnsupportedMetadata) Assert.Null(p.GetUseSiteErrorInfo()) Assert.False(p.HasUnsupportedMetadata) End Sub <Fact()> Public Sub ModReqOnSetAccessorParameter_AndProperty() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance void set_Property1 ( int32 modreq(System.Runtime.CompilerServices.IsExternalInit) 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit) Property1() { .set instance void C::set_Property1(int32 modreq(System.Runtime.CompilerServices.IsExternalInit)) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Inherits C Public Overrides WriteOnly Property Property1 As Integer Set End Set End Property Sub M(c As C) c.Property1 = 42 c.set_Property1(43) End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30643: Property 'C.Property1' is of an unsupported type. Public Overrides WriteOnly Property Property1 As Integer ~~~~~~~~~ BC30643: Property 'C.Property1' is of an unsupported type. c.Property1 = 42 ~~~~~~~~~ BC30456: 'set_Property1' is not a member of 'C'. c.set_Property1(43) ~~~~~~~~~~~~~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("C.Property1") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.NotNull(pSet.GetUseSiteErrorInfo()) Assert.True(pSet.HasUnsupportedMetadata) Assert.NotNull(p.GetUseSiteErrorInfo()) Assert.True(p.HasUnsupportedMetadata) End Sub <Fact()> Public Sub ModReqOnStaticMethod() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig static void modreq(System.Runtime.CompilerServices.IsExternalInit) M () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Sub M() C.M() End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30657: 'M' has a return type that is not supported or parameter types that are not supported. C.M() ~ </expected>) Dim m = compilation.GetMember(Of MethodSymbol)("C.M") Assert.False(m.IsInitOnly) Assert.NotNull(m.GetUseSiteErrorInfo()) Assert.True(m.HasUnsupportedMetadata) End Sub <Fact()> Public Sub ModReqOnInstanceMethod() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig instance void modreq(System.Runtime.CompilerServices.IsExternalInit) M () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Sub M(c As C) c.M() End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30657: 'M' has a return type that is not supported or parameter types that are not supported. c.M() ~ </expected>) Dim m = compilation.GetMember(Of MethodSymbol)("C.M") Assert.False(m.IsInitOnly) Assert.NotNull(m.GetUseSiteErrorInfo()) Assert.True(m.HasUnsupportedMetadata) End Sub <Fact()> Public Sub ModReqOnStaticSet() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig newslot specialname static void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(int32 x) cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 P() { .set void modreq(System.Runtime.CompilerServices.IsExternalInit) C::set_P(int32) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Sub M() C.P = 2 End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30657: 'P' has a return type that is not supported or parameter types that are not supported. C.P = 2 ~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("C.P") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.NotNull(pSet.GetUseSiteErrorInfo()) Assert.True(pSet.HasUnsupportedMetadata) Assert.Null(p.GetUseSiteErrorInfo()) Assert.False(p.HasUnsupportedMetadata) End Sub <Fact()> Public Sub ModReqOnSetterOfRefProperty() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance int32& get_Property1 () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname newslot virtual instance void set_Property1 ( int32& modreq(System.Runtime.CompilerServices.IsExternalInit) 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32& Property1() { .get instance int32& C::get_Property1() .set instance void C::set_Property1(int32& modreq(System.Runtime.CompilerServices.IsExternalInit)) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Sub M(c As C, ByRef i as Integer) Dim x1 = c.get_Property1() c.set_Property(i) Dim x2 = c.Property1 c.Property1 = i End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30456: 'get_Property1' is not a member of 'C'. Dim x1 = c.get_Property1() ~~~~~~~~~~~~~~~ BC30456: 'set_Property' is not a member of 'C'. c.set_Property(i) ~~~~~~~~~~~~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("C.Property1") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.NotNull(pSet.GetUseSiteErrorInfo()) Assert.True(pSet.HasUnsupportedMetadata) Assert.Null(p.GetUseSiteErrorInfo()) Assert.False(p.HasUnsupportedMetadata) End Sub <Fact()> Public Sub ModReqOnRefProperty_OnRefReturn() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance int32& modreq(System.Runtime.CompilerServices.IsExternalInit) get_Property1 () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname newslot virtual instance void set_Property1 ( int32& modreq(System.Runtime.CompilerServices.IsExternalInit) 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32& modreq(System.Runtime.CompilerServices.IsExternalInit) Property1() { .get instance int32& modreq(System.Runtime.CompilerServices.IsExternalInit) C::get_Property1() .set instance void C::set_Property1(int32& modreq(System.Runtime.CompilerServices.IsExternalInit)) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Sub M(c As C, ByRef i as Integer) Dim x1 = c.get_Property1() c.set_Property(i) Dim x2 = c.Property1 c.Property1 = i End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30456: 'get_Property1' is not a member of 'C'. Dim x1 = c.get_Property1() ~~~~~~~~~~~~~~~ BC30456: 'set_Property' is not a member of 'C'. c.set_Property(i) ~~~~~~~~~~~~~~ BC30643: Property 'C.Property1' is of an unsupported type. Dim x2 = c.Property1 ~~~~~~~~~ BC30643: Property 'C.Property1' is of an unsupported type. c.Property1 = i ~~~~~~~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("C.Property1") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.NotNull(pSet.GetUseSiteErrorInfo()) Assert.True(pSet.HasUnsupportedMetadata) Dim pGet = p.GetMethod Assert.False(pGet.IsInitOnly) Assert.NotNull(pGet.GetUseSiteErrorInfo()) Assert.True(pGet.HasUnsupportedMetadata) Assert.NotNull(p.GetUseSiteErrorInfo()) Assert.True(p.HasUnsupportedMetadata) End Sub <Fact()> Public Sub ModReqOnRefProperty_OnReturn() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit)& get_Property1 () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname newslot virtual instance void set_Property1 ( int32 modreq(System.Runtime.CompilerServices.IsExternalInit)& 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit)& Property1() { .get instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit)& C::get_Property1() .set instance void C::set_Property1(int32 modreq(System.Runtime.CompilerServices.IsExternalInit)&) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Sub M(c As C, ByRef i as Integer) Dim x1 = c.get_Property1() c.set_Property(i) Dim x2 = c.Property1 c.Property1 = i End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30456: 'get_Property1' is not a member of 'C'. Dim x1 = c.get_Property1() ~~~~~~~~~~~~~~~ BC30456: 'set_Property' is not a member of 'C'. c.set_Property(i) ~~~~~~~~~~~~~~ BC30643: Property 'C.Property1' is of an unsupported type. Dim x2 = c.Property1 ~~~~~~~~~ BC30643: Property 'C.Property1' is of an unsupported type. c.Property1 = i ~~~~~~~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("C.Property1") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.NotNull(pSet.GetUseSiteErrorInfo()) Assert.True(pSet.HasUnsupportedMetadata) Dim pGet = p.GetMethod Assert.False(pGet.IsInitOnly) Assert.NotNull(pGet.GetUseSiteErrorInfo()) Assert.True(pGet.HasUnsupportedMetadata) Assert.NotNull(p.GetUseSiteErrorInfo()) Assert.True(p.HasUnsupportedMetadata) End Sub <Fact()> <WorkItem(50327, "https://github.com/dotnet/roslyn/issues/50327")> Public Sub ModReqOnGetAccessorReturnValue() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit) get_Property1 () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname newslot virtual instance void set_Property1 ( int32 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 Property1() { .get instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit) C::get_Property1() .set instance void C::set_Property1(int32) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Inherits C Overrides Property Property1 As Integer Sub M(c As C) Dim x1 = c.get_Property1() c.set_Property(1) Dim x2 = c.Property1 c.Property1 = 2 End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30657: 'Property1' has a return type that is not supported or parameter types that are not supported. Overrides Property Property1 As Integer ~~~~~~~~~ BC30456: 'get_Property1' is not a member of 'C'. Dim x1 = c.get_Property1() ~~~~~~~~~~~~~~~ BC30456: 'set_Property' is not a member of 'C'. c.set_Property(1) ~~~~~~~~~~~~~~ BC30657: 'Property1' has a return type that is not supported or parameter types that are not supported. Dim x2 = c.Property1 ~~~~~~~~~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("C.Property1") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.Null(pSet.GetUseSiteErrorInfo()) Assert.False(pSet.HasUnsupportedMetadata) Dim pGet = p.GetMethod Assert.False(pGet.IsInitOnly) Assert.NotNull(pGet.GetUseSiteErrorInfo()) Assert.True(pGet.HasUnsupportedMetadata) Assert.Null(p.GetUseSiteErrorInfo()) Assert.False(p.HasUnsupportedMetadata) End Sub <Fact()> Public Sub ModReqOnPropertyAndGetAccessorReturnValue() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig specialname newslot virtual instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit) get_Property1 () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname newslot virtual instance void set_Property1 ( int32 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit) Property1() { .get instance int32 modreq(System.Runtime.CompilerServices.IsExternalInit) C::get_Property1() .set instance void C::set_Property1(int32) } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Inherits C Overrides Property Property1 As Integer Sub M(c As C) Dim x1 = c.get_Property1() c.set_Property(1) Dim x2 = c.Property1 c.Property1 = 2 End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30643: Property 'C.Property1' is of an unsupported type. Overrides Property Property1 As Integer ~~~~~~~~~ BC30456: 'get_Property1' is not a member of 'C'. Dim x1 = c.get_Property1() ~~~~~~~~~~~~~~~ BC30456: 'set_Property' is not a member of 'C'. c.set_Property(1) ~~~~~~~~~~~~~~ BC30643: Property 'C.Property1' is of an unsupported type. Dim x2 = c.Property1 ~~~~~~~~~ BC30643: Property 'C.Property1' is of an unsupported type. c.Property1 = 2 ~~~~~~~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("C.Property1") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.Null(pSet.GetUseSiteErrorInfo()) Assert.False(pSet.HasUnsupportedMetadata) Dim pGet = p.GetMethod Assert.False(pGet.IsInitOnly) Assert.NotNull(pGet.GetUseSiteErrorInfo()) Assert.True(pGet.HasUnsupportedMetadata) Assert.NotNull(p.GetUseSiteErrorInfo()) Assert.True(p.HasUnsupportedMetadata) End Sub <Fact()> Public Sub ModOptOnSet() Dim ilSource = <![CDATA[ .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig newslot specialname instance void modopt(System.Runtime.CompilerServices.IsExternalInit) set_P(int32 x) cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 P() { .set instance void modopt(System.Runtime.CompilerServices.IsExternalInit) C::set_P(int32) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } ]]>.Value Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Shared Sub M(c As C) c.P = 2 End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) CompileAndVerify(compilation).VerifyDiagnostics() Dim p = compilation.GetMember(Of PropertySymbol)("C.P") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.Null(pSet.GetUseSiteErrorInfo()) Assert.False(pSet.HasUnsupportedMetadata) Assert.Null(p.GetUseSiteErrorInfo()) Assert.False(p.HasUnsupportedMetadata) End Sub <Theory, InlineData("Runtime.CompilerServices.IsExternalInit"), InlineData("CompilerServices.IsExternalInit"), InlineData("IsExternalInit"), InlineData("ns.System.Runtime.CompilerServices.IsExternalInit"), InlineData("system.Runtime.CompilerServices.IsExternalInit"), InlineData("System.runtime.CompilerServices.IsExternalInit"), InlineData("System.Runtime.compilerServices.IsExternalInit"), InlineData("System.Runtime.CompilerServices.isExternalInit") > Public Sub IsExternalInitCheck(modifierName As String) Dim ilSource = " .class public auto ansi beforefieldinit C extends System.Object { .method public hidebysig newslot specialname instance void modreq(" + modifierName + ") set_P(int32 x) cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 P() { .set instance void modreq(" + modifierName + ") C::set_P(int32) } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi sealed beforefieldinit " + modifierName + " extends System.Object { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } " Dim vbSource = <compilation> <file name="c.vb"><![CDATA[ Class Test Sub M(c As C) c.P = 2 End Sub End Class ]]> </file> </compilation> Dim compilation = CreateCompilationWithCustomILSource(vbSource, ilSource, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.ReleaseDll) compilation.AssertTheseDiagnostics( <expected> BC30657: 'P' has a return type that is not supported or parameter types that are not supported. c.P = 2 ~~~ </expected>) Dim p = compilation.GetMember(Of PropertySymbol)("C.P") Dim pSet = p.SetMethod Assert.False(pSet.IsInitOnly) Assert.NotNull(pSet.GetUseSiteErrorInfo()) Assert.True(pSet.HasUnsupportedMetadata) Assert.Null(p.GetUseSiteErrorInfo()) Assert.False(p.HasUnsupportedMetadata) End Sub <Fact()> Public Sub IsInitOnlyValue() Dim vbSource1 = <compilation> <file name="c.vb"><![CDATA[ ]]> </file> </compilation> Dim compilation1 = CreateCompilation(vbSource1, options:=TestOptions.ReleaseDll) Dim vbSource2 = <compilation> <file name="c.vb"><![CDATA[ Class Test1(Of T) Public Shared Sub M1() Dim x as Integer = 0 x.DoSomething() End Sub Public Function M2() As System.Action return Sub() End Sub End Function Public Property P As Integer End Class Class Test2 Inherits Test1(Of Integer) End Class Delegate Sub D() Module Ext <System.Runtime.CompilerServices.Extension> Sub DoSomething(x As Integer) End Sub End Module ]]> </file> </compilation> Dim compilation2 = CreateCompilation(vbSource2, references:={compilation1.ToMetadataReference()}, options:=TestOptions.ReleaseDll) Dim tree = compilation2.SyntaxTrees.Single() Dim model = compilation2.GetSemanticModel(tree) Dim lambda = tree.GetRoot.DescendantNodes().OfType(Of LambdaExpressionSyntax)().Single() Assert.False(DirectCast(model.GetSymbolInfo(lambda).Symbol, MethodSymbol).IsInitOnly) Dim invocation = tree.GetRoot.DescendantNodes().OfType(Of InvocationExpressionSyntax)().Single() Assert.False(DirectCast(model.GetSymbolInfo(invocation).Symbol, MethodSymbol).IsInitOnly) Dim verify = Sub(compilation As VisualBasicCompilation) Dim test1 = compilation.GetTypeByMetadataName("Test1`1") Dim p = test1.GetMember(Of PropertySymbol)("P") Assert.False(p.SetMethod.IsInitOnly) Assert.False(p.GetMethod.IsInitOnly) Assert.False(test1.GetMember(Of MethodSymbol)("M1").IsInitOnly) Assert.False(test1.GetMember(Of MethodSymbol)("M2").IsInitOnly) Dim test1Constructed = compilation.GetTypeByMetadataName("Test2").BaseTypeNoUseSiteDiagnostics p = test1Constructed.GetMember(Of PropertySymbol)("P") Assert.False(p.SetMethod.IsInitOnly) Assert.False(p.GetMethod.IsInitOnly) Assert.False(test1Constructed.GetMember(Of MethodSymbol)("M1").IsInitOnly) Assert.False(test1Constructed.GetMember(Of MethodSymbol)("M2").IsInitOnly) Dim d = compilation.GetTypeByMetadataName("D") For Each m As MethodSymbol In d.GetMembers() Assert.False(m.IsInitOnly) Next End Sub verify(compilation2) Dim compilation3 = CreateCompilation(vbSource1, references:={compilation2.ToMetadataReference()}, options:=TestOptions.ReleaseDll) verify(compilation3) End Sub <Fact> Public Sub ReferenceConversion_01() Dim csSource = " public interface I1 { int P1 { get; init; } } public interface I2 {} public class C : I1, I2 { public int P0 { init; get; } int I1.P1 { get => P0; init => P0 = value; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.P0) End Sub End Class Class B Inherits C Public Sub New() DirectCast(Me, I1).P1 = 41 End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC37311: Init-only property 'P1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. DirectCast(Me, I1).P1 = 41 ~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub ReferenceConversion_02() Dim csSource = " public interface I1 { int P1 { get; init; } } public interface I2 {} public class C : I1, I2 { public int P0 { init; get; } int I1.P1 { get => P0; init => P0 = value; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.P0) End Sub End Class Class B Inherits C Public Sub New() With CType(Me, I1) .P1 = 41 End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC37311: Init-only property 'P1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .P1 = 41 ~~~~~~~~ </expected>) End Sub <Fact> Public Sub ReferenceConversion_03() Dim csSource = " public interface I1 { int P1 { get; init; } } public class C : I1 { public int P0 { init; get; } int I1.P1 { get => P0; init => P0 = value; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.P0) End Sub End Class Class B Inherits C Public Sub New() TryCast(Me, I1).P1 = 41 End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC37311: Init-only property 'P1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. TryCast(Me, I1).P1 = 41 ~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub ReferenceConversion_04() Dim csSource = " public interface I1 { int P1 { get; init; } } public class C : I1 { public int P0 { init; get; } int I1.P1 { get => P0; init => P0 = value; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.P0) End Sub End Class Class B Inherits C Public Sub New() With TryCast(Me, I1) .P1 = 41 End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC37311: Init-only property 'P1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .P1 = 41 ~~~~~~~~ </expected>) End Sub <Fact> Public Sub ReferenceConversion_05() Dim csSource = " public interface I1 { int P1 { get; init; } } public class C : I1 { public int P0 { init; get; } int I1.P1 { get => P0; init => P0 = value; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.P0) End Sub End Class Class B Inherits C Public Sub New() CType(MyBase, I1).P1 = 41 End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC37311: Init-only property 'P1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. CType(MyBase, I1).P1 = 41 ~~~~~~~~~~~~~~~~~~~~~~~~~ BC32027: 'MyBase' must be followed by '.' and an identifier. CType(MyBase, I1).P1 = 41 ~~~~~~ </expected>) End Sub <Fact> Public Sub ReferenceConversion_06() Dim csSource = " public interface I1 { int P1 { get; init; } } public class C : I1 { public int P0 { init; get; } int I1.P1 { get => P0; init => P0 = value; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.P0) End Sub End Class Class B Inherits C Public Sub New() DirectCast(MyClass, I1).P1 = 41 With MyClass .P0 = 1 End With With MyBase .P0 = 2 End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC37311: Init-only property 'P1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. DirectCast(MyClass, I1).P1 = 41 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ BC32028: 'MyClass' must be followed by '.' and an identifier. DirectCast(MyClass, I1).P1 = 41 ~~~~~~~ BC32028: 'MyClass' must be followed by '.' and an identifier. With MyClass ~~~~~~~ BC32027: 'MyBase' must be followed by '.' and an identifier. With MyBase ~~~~~~ </expected>) End Sub <Fact> Public Sub ReferenceConversion_07() Dim csSource = " public class C { public int P0 { init; get; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() End Sub End Class Class B Inherits C Public Sub New() Me.P0 = 41 End Sub End Class Class D Public Shared Widening Operator CType(x As D) As B Return Nothing End Operator Public Sub New() CType(Me, B).P0 = 42 End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC37311: Init-only property 'P0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. CType(Me, B).P0 = 42 ~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub ReferenceConversion_08() Dim csSource = " public class C { public int P0 { init; get; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.P0) End Sub End Class Class B Inherits C Public Sub New() DirectCast(Me, B).P0 = 41 End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC37311: Init-only property 'P0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. DirectCast(Me, B).P0 = 41 ~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub <Fact> Public Sub ReferenceConversion_09() Dim csSource = " public class C { public int P0 { init; get; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() Dim b = new B() System.Console.Write(b.P0) End Sub End Class Class B Inherits C Public Sub New() With CType(Me, B) .P0 = 41 End With End Sub End Class ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC37311: Init-only property 'P0' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. .P0 = 41 ~~~~~~~~ </expected>) End Sub <Fact> Public Sub ReferenceConversion_10() Dim csSource = " public interface I1 { int P1 { get; init; } } " Dim csCompilation = CreateCSharpCompilation(csSource + IsExternalInitTypeDefinition).EmitToImageReference() Dim source1 = <compilation> <file name="c.vb"><![CDATA[ Public Class Test Shared Sub Main() End Sub End Class Structure B Implements I1 Public Sub New(x As Integer) DirectCast(Me, I1).P1 = 41 CType(Me, I1).P1 = 42 DirectCast(CObj(Me), I1).P1 = 43 End Sub End Structure ]]></file> </compilation> Dim comp1 = CreateCompilation(source1, parseOptions:=TestOptions.RegularLatest, options:=TestOptions.DebugExe, references:={csCompilation}) comp1.AssertTheseDiagnostics( <expected> BC30149: Structure 'B' must implement 'Property P1 As Integer' for interface 'I1'. Implements I1 ~~ BC37311: Init-only property 'P1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. DirectCast(Me, I1).P1 = 41 ~~~~~~~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'P1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. CType(Me, I1).P1 = 42 ~~~~~~~~~~~~~~~~~~~~~ BC37311: Init-only property 'P1' can only be assigned by an object member initializer, or on 'Me', 'MyClass` or 'MyBase' in an instance constructor. DirectCast(CObj(Me), I1).P1 = 43 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ </expected>) End Sub End Class End Namespace
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/Remote/ServiceHub/Host/SolutionAssetSource.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Serialization; using Microsoft.ServiceHub.Framework; using Microsoft.VisualStudio.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { internal sealed class SolutionAssetSource : IAssetSource { private readonly ServiceBrokerClient _client; public SolutionAssetSource(ServiceBrokerClient client) { _client = client; } public async ValueTask<ImmutableArray<(Checksum, object)>> GetAssetsAsync(int scopeId, ISet<Checksum> checksums, ISerializerService serializerService, CancellationToken cancellationToken) { // Make sure we are on the thread pool to avoid UI thread dependencies if external code uses ConfigureAwait(true) await TaskScheduler.Default; using var provider = await _client.GetProxyAsync<ISolutionAssetProvider>(SolutionAssetProvider.ServiceDescriptor, cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(provider.Proxy); return await new RemoteCallback<ISolutionAssetProvider>(provider.Proxy).InvokeAsync( (proxy, pipeWriter, cancellationToken) => proxy.GetAssetsAsync(pipeWriter, scopeId, checksums.ToArray(), cancellationToken), (pipeReader, cancellationToken) => RemoteHostAssetSerialization.ReadDataAsync(pipeReader, scopeId, checksums, serializerService, cancellationToken), cancellationToken).ConfigureAwait(false); } public async ValueTask<bool> IsExperimentEnabledAsync(string experimentName, CancellationToken cancellationToken) { // Make sure we are on the thread pool to avoid UI thread dependencies if external code uses ConfigureAwait(true) await TaskScheduler.Default; using var provider = await _client.GetProxyAsync<ISolutionAssetProvider>(SolutionAssetProvider.ServiceDescriptor, cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(provider.Proxy); return await new RemoteCallback<ISolutionAssetProvider>(provider.Proxy).InvokeAsync( (self, cancellationToken) => provider.Proxy.IsExperimentEnabledAsync(experimentName, cancellationToken), cancellationToken).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. using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Serialization; using Microsoft.ServiceHub.Framework; using Microsoft.VisualStudio.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote { internal sealed class SolutionAssetSource : IAssetSource { private readonly ServiceBrokerClient _client; public SolutionAssetSource(ServiceBrokerClient client) { _client = client; } public async ValueTask<ImmutableArray<(Checksum, object)>> GetAssetsAsync(int scopeId, ISet<Checksum> checksums, ISerializerService serializerService, CancellationToken cancellationToken) { // Make sure we are on the thread pool to avoid UI thread dependencies if external code uses ConfigureAwait(true) await TaskScheduler.Default; using var provider = await _client.GetProxyAsync<ISolutionAssetProvider>(SolutionAssetProvider.ServiceDescriptor, cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(provider.Proxy); return await new RemoteCallback<ISolutionAssetProvider>(provider.Proxy).InvokeAsync( (proxy, pipeWriter, cancellationToken) => proxy.GetAssetsAsync(pipeWriter, scopeId, checksums.ToArray(), cancellationToken), (pipeReader, cancellationToken) => RemoteHostAssetSerialization.ReadDataAsync(pipeReader, scopeId, checksums, serializerService, cancellationToken), cancellationToken).ConfigureAwait(false); } public async ValueTask<bool> IsExperimentEnabledAsync(string experimentName, CancellationToken cancellationToken) { // Make sure we are on the thread pool to avoid UI thread dependencies if external code uses ConfigureAwait(true) await TaskScheduler.Default; using var provider = await _client.GetProxyAsync<ISolutionAssetProvider>(SolutionAssetProvider.ServiceDescriptor, cancellationToken).ConfigureAwait(false); Contract.ThrowIfNull(provider.Proxy); return await new RemoteCallback<ISolutionAssetProvider>(provider.Proxy).InvokeAsync( (self, cancellationToken) => provider.Proxy.IsExperimentEnabledAsync(experimentName, cancellationToken), cancellationToken).ConfigureAwait(false); } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/Core/CodeAnalysisTest/Collections/List/SegmentedList.Generic.Tests.BinarySearch.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. // NOTE: This code is derived from an implementation originally in dotnet/runtime: // https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Collections/tests/Generic/List/List.Generic.Tests.BinarySearch.cs // // See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the // reference implementation. using System; using System.Linq; using Microsoft.CodeAnalysis.Collections; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { /// <summary> /// Contains tests that ensure the correctness of the List class. /// </summary> public abstract partial class SegmentedList_Generic_Tests<T> : IList_Generic_Tests<T> { [Theory] [MemberData(nameof(ValidCollectionSizes))] public void BinarySearch_ForEveryItemWithoutDuplicates(int count) { SegmentedList<T> list = GenericListFactory(count); foreach (T item in list) while (list.Count((value) => value.Equals(item)) > 1) list.Remove(item); list.Sort(); SegmentedList<T> beforeList = list.ToSegmentedList(); Assert.All(Enumerable.Range(0, list.Count), index => { Assert.Equal(index, list.BinarySearch(beforeList[index])); Assert.Equal(index, list.BinarySearch(beforeList[index], GetIComparer())); Assert.Equal(beforeList[index], list[index]); }); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void BinarySearch_ForEveryItemWithDuplicates(int count) { if (count > 0) { SegmentedList<T> list = GenericListFactory(count); list.Add(list[0]); list.Sort(); SegmentedList<T> beforeList = list.ToSegmentedList(); Assert.All(Enumerable.Range(0, list.Count), index => { Assert.True(list.BinarySearch(beforeList[index]) >= 0); Assert.True(list.BinarySearch(beforeList[index], GetIComparer()) >= 0); Assert.Equal(beforeList[index], list[index]); }); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void BinarySearch_Validations(int count) { SegmentedList<T> list = GenericListFactory(count); list.Sort(); T element = CreateT(3215); Assert.Throws<ArgumentException>(null, () => list.BinarySearch(0, count + 1, element, GetIComparer())); //"Finding items longer than array should throw ArgumentException" Assert.Throws<ArgumentOutOfRangeException>(() => list.BinarySearch(-1, count, element, GetIComparer())); //"ArgumentOutOfRangeException should be thrown on negative index." Assert.Throws<ArgumentOutOfRangeException>(() => list.BinarySearch(0, -1, element, GetIComparer())); //"ArgumentOutOfRangeException should be thrown on negative count." Assert.Throws<ArgumentException>(null, () => list.BinarySearch(count + 1, count, element, GetIComparer())); //"ArgumentException should be thrown on index greater than length of array." } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // NOTE: This code is derived from an implementation originally in dotnet/runtime: // https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Collections/tests/Generic/List/List.Generic.Tests.BinarySearch.cs // // See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the // reference implementation. using System; using System.Linq; using Microsoft.CodeAnalysis.Collections; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { /// <summary> /// Contains tests that ensure the correctness of the List class. /// </summary> public abstract partial class SegmentedList_Generic_Tests<T> : IList_Generic_Tests<T> { [Theory] [MemberData(nameof(ValidCollectionSizes))] public void BinarySearch_ForEveryItemWithoutDuplicates(int count) { SegmentedList<T> list = GenericListFactory(count); foreach (T item in list) while (list.Count((value) => value.Equals(item)) > 1) list.Remove(item); list.Sort(); SegmentedList<T> beforeList = list.ToSegmentedList(); Assert.All(Enumerable.Range(0, list.Count), index => { Assert.Equal(index, list.BinarySearch(beforeList[index])); Assert.Equal(index, list.BinarySearch(beforeList[index], GetIComparer())); Assert.Equal(beforeList[index], list[index]); }); } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void BinarySearch_ForEveryItemWithDuplicates(int count) { if (count > 0) { SegmentedList<T> list = GenericListFactory(count); list.Add(list[0]); list.Sort(); SegmentedList<T> beforeList = list.ToSegmentedList(); Assert.All(Enumerable.Range(0, list.Count), index => { Assert.True(list.BinarySearch(beforeList[index]) >= 0); Assert.True(list.BinarySearch(beforeList[index], GetIComparer()) >= 0); Assert.Equal(beforeList[index], list[index]); }); } } [Theory] [MemberData(nameof(ValidCollectionSizes))] public void BinarySearch_Validations(int count) { SegmentedList<T> list = GenericListFactory(count); list.Sort(); T element = CreateT(3215); Assert.Throws<ArgumentException>(null, () => list.BinarySearch(0, count + 1, element, GetIComparer())); //"Finding items longer than array should throw ArgumentException" Assert.Throws<ArgumentOutOfRangeException>(() => list.BinarySearch(-1, count, element, GetIComparer())); //"ArgumentOutOfRangeException should be thrown on negative index." Assert.Throws<ArgumentOutOfRangeException>(() => list.BinarySearch(0, -1, element, GetIComparer())); //"ArgumentOutOfRangeException should be thrown on negative count." Assert.Throws<ArgumentException>(null, () => list.BinarySearch(count + 1, count, element, GetIComparer())); //"ArgumentException should be thrown on index greater than length of array." } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/Test/Resources/Core/SymbolsTests/NoPia/Pia5.dll
MZ@ !L!This program cannot be run in DOS mode. $PEL/pmL! n$ @@ @$O@`  H.textt  `.rsrc@@@.reloc ` @BP$HP BSJB v4.0.30319l,#~8#Strings#US#GUID#BlobG %3-4^?u??? ?F; !")Q19QA".3..#.+C C'cUc ( <Module>mscorlibI5I6System.Collections.GenericList`1FooSystem.Runtime.InteropServicesInterfaceTypeAttributeComInterfaceType.ctorGuidAttributeComImportAttributeSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttributeImportedFromTypeLibAttributePia5Pia5.dll +\1Kœ%z\V4     )$27e3e649-994b-4f58-b3c6-f8089a5f2c05 )$27e3e649-994b-4f58-b3c6-f8089a5f2c06 TWrapNonExceptionThrows Pia5.dll)$f9c2d51d-4f44-45f0-9eda-c9d599b58259D$^$ P$_CorDllMainmscoree.dll% @0HX@<<4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfox000004b0,FileDescription 0FileVersion0.0.0.04 InternalNamePia5.dll(LegalCopyright < OriginalFilenamePia5.dll4ProductVersion0.0.0.08Assembly Version0.0.0.0 p4
MZ@ !L!This program cannot be run in DOS mode. $PEL/pmL! n$ @@ @$O@`  H.textt  `.rsrc@@@.reloc ` @BP$HP BSJB v4.0.30319l,#~8#Strings#US#GUID#BlobG %3-4^?u??? ?F; !")Q19QA".3..#.+C C'cUc ( <Module>mscorlibI5I6System.Collections.GenericList`1FooSystem.Runtime.InteropServicesInterfaceTypeAttributeComInterfaceType.ctorGuidAttributeComImportAttributeSystem.Runtime.CompilerServicesCompilationRelaxationsAttributeRuntimeCompatibilityAttributeImportedFromTypeLibAttributePia5Pia5.dll +\1Kœ%z\V4     )$27e3e649-994b-4f58-b3c6-f8089a5f2c05 )$27e3e649-994b-4f58-b3c6-f8089a5f2c06 TWrapNonExceptionThrows Pia5.dll)$f9c2d51d-4f44-45f0-9eda-c9d599b58259D$^$ P$_CorDllMainmscoree.dll% @0HX@<<4VS_VERSION_INFO?DVarFileInfo$TranslationStringFileInfox000004b0,FileDescription 0FileVersion0.0.0.04 InternalNamePia5.dll(LegalCopyright < OriginalFilenamePia5.dll4ProductVersion0.0.0.08Assembly Version0.0.0.0 p4
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/Core/CodeAnalysisTest/Diagnostics/SuppressMessageAttributeCompilerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Runtime.ExceptionServices; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.VisualBasic; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Diagnostics { public class SuppressMessageAttributeCompilerTests : SuppressMessageAttributeTests { protected override Task VerifyAsync(string source, string language, DiagnosticAnalyzer[] analyzers, DiagnosticDescription[] diagnostics, string rootNamespace = null) { Assert.True(analyzers != null && analyzers.Length > 0, "Must specify at least one diagnostic analyzer to test suppression"); var compilation = CreateCompilation(source, language, rootNamespace); compilation.VerifyAnalyzerDiagnostics(analyzers, expected: diagnostics); return Task.FromResult(false); } protected override bool ConsiderArgumentsForComparingDiagnostics => true; private static readonly Lazy<ImmutableArray<MetadataReference>> s_references = new Lazy<ImmutableArray<MetadataReference>>(() => { const string unconditionalSuppressMessageDef = @" namespace System.Diagnostics.CodeAnalysis { [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple=true, Inherited=false)] public sealed class UnconditionalSuppressMessageAttribute : System.Attribute { public UnconditionalSuppressMessageAttribute(string category, string checkId) { Category = category; CheckId = checkId; } public string Category { get; } public string CheckId { get; } public string Scope { get; set; } public string Target { get; set; } public string MessageId { get; set; } public string Justification { get; set; } } }"; var compRef = CSharpCompilation.Create("unconditionalsuppress", options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), syntaxTrees: new[] { CSharpSyntaxTree.ParseText(unconditionalSuppressMessageDef) }, references: new[] { TestBase.MscorlibRef }).EmitToImageReference(); return ImmutableArray.Create(TestBase.MscorlibRef, compRef, TestBase.ValueTupleRef); }, System.Threading.LazyThreadSafetyMode.PublicationOnly); private static Compilation CreateCompilation(string source, string language, string rootNamespace) { string fileName = language == LanguageNames.CSharp ? "Test.cs" : "Test.vb"; string projectName = "TestProject"; var references = s_references.Value; var syntaxTree = language == LanguageNames.CSharp ? CSharpSyntaxTree.ParseText(source, path: fileName) : VisualBasicSyntaxTree.ParseText(source, path: fileName); if (language == LanguageNames.CSharp) { return CSharpCompilation.Create( projectName, syntaxTrees: new[] { syntaxTree, }, references: references); } else { return VisualBasicCompilation.Create( projectName, syntaxTrees: new[] { syntaxTree }, references: references, options: new VisualBasicCompilationOptions( OutputKind.DynamicallyLinkedLibrary, rootNamespace: rootNamespace)); } } [Fact] public async Task AnalyzerExceptionDiagnosticsWithDifferentContext() { var exception = new Exception(); var baseDiagnostic = Diagnostic("AD0001", null).WithLocation(1, 1); var diagnosticC = baseDiagnostic .WithArguments( "Microsoft.CodeAnalysis.UnitTests.Diagnostics.SuppressMessageAttributeTests+ThrowExceptionForEachNamedTypeAnalyzer", "System.Exception", exception.Message, (IFormattable)$@"{string.Format(CodeAnalysisResources.ExceptionContext, $@"Compilation: TestProject ISymbol: C (NamedType)")} {new LazyToString(() => exception.ToString())} ----- {string.Format(CodeAnalysisResources.DisableAnalyzerDiagnosticsMessage, "ThrowException")}"); var diagnosticC1 = baseDiagnostic .WithArguments( "Microsoft.CodeAnalysis.UnitTests.Diagnostics.SuppressMessageAttributeTests+ThrowExceptionForEachNamedTypeAnalyzer", "System.Exception", exception.Message, (IFormattable)$@"{string.Format(CodeAnalysisResources.ExceptionContext, $@"Compilation: TestProject ISymbol: C1 (NamedType)")} {new LazyToString(() => exception.ToString())} ----- {string.Format(CodeAnalysisResources.DisableAnalyzerDiagnosticsMessage, "ThrowException")}"); var diagnosticC2 = baseDiagnostic .WithArguments( "Microsoft.CodeAnalysis.UnitTests.Diagnostics.SuppressMessageAttributeTests+ThrowExceptionForEachNamedTypeAnalyzer", "System.Exception", exception.Message, (IFormattable)$@"{string.Format(CodeAnalysisResources.ExceptionContext, $@"Compilation: TestProject ISymbol: C2 (NamedType)")} {new LazyToString(() => exception.ToString())} ----- {string.Format(CodeAnalysisResources.DisableAnalyzerDiagnosticsMessage, "ThrowException")}"); // expect 3 different diagnostics with 3 different contexts. await VerifyCSharpAsync(@" public class C { } public class C1 { } public class C2 { } ", new[] { new ThrowExceptionForEachNamedTypeAnalyzer(ExceptionDispatchInfo.Capture(exception)) }, diagnostics: new[] { diagnosticC, diagnosticC1, diagnosticC2 }); } [Fact] public async Task AnalyzerExceptionFromSupportedDiagnosticsCall() { var exception = new Exception(); var diagnostic = Diagnostic("AD0001", null) .WithArguments( "Microsoft.CodeAnalysis.UnitTests.Diagnostics.SuppressMessageAttributeTests+ThrowExceptionFromSupportedDiagnostics", "System.Exception", exception.Message, (IFormattable)$@"{new LazyToString(() => exception.ToString().Substring(0, exception.ToString().IndexOf("---")))}-----") .WithLocation(1, 1); await VerifyCSharpAsync("public class C { }", new[] { new ThrowExceptionFromSupportedDiagnostics(exception) }, diagnostics: new[] { diagnostic }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Runtime.ExceptionServices; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.VisualBasic; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Diagnostics { public class SuppressMessageAttributeCompilerTests : SuppressMessageAttributeTests { protected override Task VerifyAsync(string source, string language, DiagnosticAnalyzer[] analyzers, DiagnosticDescription[] diagnostics, string rootNamespace = null) { Assert.True(analyzers != null && analyzers.Length > 0, "Must specify at least one diagnostic analyzer to test suppression"); var compilation = CreateCompilation(source, language, rootNamespace); compilation.VerifyAnalyzerDiagnostics(analyzers, expected: diagnostics); return Task.FromResult(false); } protected override bool ConsiderArgumentsForComparingDiagnostics => true; private static readonly Lazy<ImmutableArray<MetadataReference>> s_references = new Lazy<ImmutableArray<MetadataReference>>(() => { const string unconditionalSuppressMessageDef = @" namespace System.Diagnostics.CodeAnalysis { [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple=true, Inherited=false)] public sealed class UnconditionalSuppressMessageAttribute : System.Attribute { public UnconditionalSuppressMessageAttribute(string category, string checkId) { Category = category; CheckId = checkId; } public string Category { get; } public string CheckId { get; } public string Scope { get; set; } public string Target { get; set; } public string MessageId { get; set; } public string Justification { get; set; } } }"; var compRef = CSharpCompilation.Create("unconditionalsuppress", options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary), syntaxTrees: new[] { CSharpSyntaxTree.ParseText(unconditionalSuppressMessageDef) }, references: new[] { TestBase.MscorlibRef }).EmitToImageReference(); return ImmutableArray.Create(TestBase.MscorlibRef, compRef, TestBase.ValueTupleRef); }, System.Threading.LazyThreadSafetyMode.PublicationOnly); private static Compilation CreateCompilation(string source, string language, string rootNamespace) { string fileName = language == LanguageNames.CSharp ? "Test.cs" : "Test.vb"; string projectName = "TestProject"; var references = s_references.Value; var syntaxTree = language == LanguageNames.CSharp ? CSharpSyntaxTree.ParseText(source, path: fileName) : VisualBasicSyntaxTree.ParseText(source, path: fileName); if (language == LanguageNames.CSharp) { return CSharpCompilation.Create( projectName, syntaxTrees: new[] { syntaxTree, }, references: references); } else { return VisualBasicCompilation.Create( projectName, syntaxTrees: new[] { syntaxTree }, references: references, options: new VisualBasicCompilationOptions( OutputKind.DynamicallyLinkedLibrary, rootNamespace: rootNamespace)); } } [Fact] public async Task AnalyzerExceptionDiagnosticsWithDifferentContext() { var exception = new Exception(); var baseDiagnostic = Diagnostic("AD0001", null).WithLocation(1, 1); var diagnosticC = baseDiagnostic .WithArguments( "Microsoft.CodeAnalysis.UnitTests.Diagnostics.SuppressMessageAttributeTests+ThrowExceptionForEachNamedTypeAnalyzer", "System.Exception", exception.Message, (IFormattable)$@"{string.Format(CodeAnalysisResources.ExceptionContext, $@"Compilation: TestProject ISymbol: C (NamedType)")} {new LazyToString(() => exception.ToString())} ----- {string.Format(CodeAnalysisResources.DisableAnalyzerDiagnosticsMessage, "ThrowException")}"); var diagnosticC1 = baseDiagnostic .WithArguments( "Microsoft.CodeAnalysis.UnitTests.Diagnostics.SuppressMessageAttributeTests+ThrowExceptionForEachNamedTypeAnalyzer", "System.Exception", exception.Message, (IFormattable)$@"{string.Format(CodeAnalysisResources.ExceptionContext, $@"Compilation: TestProject ISymbol: C1 (NamedType)")} {new LazyToString(() => exception.ToString())} ----- {string.Format(CodeAnalysisResources.DisableAnalyzerDiagnosticsMessage, "ThrowException")}"); var diagnosticC2 = baseDiagnostic .WithArguments( "Microsoft.CodeAnalysis.UnitTests.Diagnostics.SuppressMessageAttributeTests+ThrowExceptionForEachNamedTypeAnalyzer", "System.Exception", exception.Message, (IFormattable)$@"{string.Format(CodeAnalysisResources.ExceptionContext, $@"Compilation: TestProject ISymbol: C2 (NamedType)")} {new LazyToString(() => exception.ToString())} ----- {string.Format(CodeAnalysisResources.DisableAnalyzerDiagnosticsMessage, "ThrowException")}"); // expect 3 different diagnostics with 3 different contexts. await VerifyCSharpAsync(@" public class C { } public class C1 { } public class C2 { } ", new[] { new ThrowExceptionForEachNamedTypeAnalyzer(ExceptionDispatchInfo.Capture(exception)) }, diagnostics: new[] { diagnosticC, diagnosticC1, diagnosticC2 }); } [Fact] public async Task AnalyzerExceptionFromSupportedDiagnosticsCall() { var exception = new Exception(); var diagnostic = Diagnostic("AD0001", null) .WithArguments( "Microsoft.CodeAnalysis.UnitTests.Diagnostics.SuppressMessageAttributeTests+ThrowExceptionFromSupportedDiagnostics", "System.Exception", exception.Message, (IFormattable)$@"{new LazyToString(() => exception.ToString().Substring(0, exception.ToString().IndexOf("---")))}-----") .WithLocation(1, 1); await VerifyCSharpAsync("public class C { }", new[] { new ThrowExceptionFromSupportedDiagnostics(exception) }, diagnostics: new[] { diagnostic }); } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/CSharpTest/Semantics/SpeculationAnalyzerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Semantics; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Semantics { public class SpeculationAnalyzerTests : SpeculationAnalyzerTestsBase { [Fact] public void SpeculationAnalyzerDifferentOverloads() { Test(@" class Program { void Vain(int arg = 3) { } void Vain(string arg) { } void Main() { [|Vain(5)|]; } } ", "Vain(string.Empty)", true); } [Fact, WorkItem(672396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/672396")] public void SpeculationAnalyzerExtensionMethodExplicitInvocation() { Test(@" static class Program { public static void Vain(this int arg) { } static void Main() { [|5.Vain()|]; } } ", "Vain(5)", false); } [Fact] public void SpeculationAnalyzerImplicitBaseClassConversion() { Test(@" using System; class Program { void Main() { Exception ex = [|(Exception)new InvalidOperationException()|]; } } ", "new InvalidOperationException()", false); } [Fact] public void SpeculationAnalyzerImplicitNumericConversion() { Test(@" class Program { void Main() { long i = [|(long)5|]; } } ", "5", false); } [Fact] public void SpeculationAnalyzerImplicitUserConversion() { Test(@" class From { public static implicit operator To(From from) { return new To(); } } class To { } class Program { void Main() { To to = [|(To)new From()|]; } } ", "new From()", true); } [Fact] public void SpeculationAnalyzerExplicitConversion() { Test(@" using System; class Program { void Main() { Exception ex1 = new InvalidOperationException(); var ex2 = [|(InvalidOperationException)ex1|]; } } ", "ex1", true); } [Fact] public void SpeculationAnalyzerArrayImplementingNonGenericInterface() { Test(@" using System.Collections; class Program { void Main() { var a = new[] { 1, 2, 3 }; [|((IEnumerable)a).GetEnumerator()|]; } } ", "a.GetEnumerator()", false); } [Fact] public void SpeculationAnalyzerVirtualMethodWithBaseConversion() { Test(@" using System; using System.IO; class Program { void Main() { var s = new MemoryStream(); [|((Stream)s).Flush()|]; } } ", "s.Flush()", false); } [Fact] public void SpeculationAnalyzerNonVirtualMethodImplementingInterface() { Test(@" using System; class Class : IComparable { public int CompareTo(object other) { return 1; } } class Program { static void Main() { var c = new Class(); var d = new Class(); [|((IComparable)c).CompareTo(d)|]; } } ", "c.CompareTo(d)", true); } [Fact] public void SpeculationAnalyzerSealedClassImplementingInterface() { Test(@" using System; sealed class Class : IComparable { public int CompareTo(object other) { return 1; } } class Program { static void Main() { var c = new Class(); var d = new Class(); [|((IComparable)c).CompareTo(d)|]; } } ", "((IComparable)c).CompareTo(d)", semanticChanges: false); } [Fact] public void SpeculationAnalyzerValueTypeImplementingInterface() { Test(@" using System; class Program { void Main() { decimal d = 5; [|((IComparable<decimal>)d).CompareTo(6)|]; } } ", "d.CompareTo(6)", false); } [Fact] public void SpeculationAnalyzerBinaryExpressionIntVsLong() { Test(@" class Program { void Main() { var r = [|1+1L|]; } } ", "1+1", true); } [Fact] public void SpeculationAnalyzerQueryExpressionSelectType() { Test(@" using System.Linq; class Program { static void Main(string[] args) { var items = [|from i in Enumerable.Range(0, 3) select (long)i|]; } } ", "from i in Enumerable.Range(0, 3) select i", true); } [Fact] public void SpeculationAnalyzerQueryExpressionFromType() { Test(@" using System.Linq; class Program { static void Main(string[] args) { var items = [|from i in new long[0] select i|]; } } ", "from i in new int[0] select i", true); } [Fact] public void SpeculationAnalyzerQueryExpressionGroupByType() { Test(@" using System.Linq; class Program { static void Main(string[] args) { var items = [|from i in Enumerable.Range(0, 3) group (long)i by i|]; } } ", "from i in Enumerable.Range(0, 3) group i by i", true); } [Fact] public void SpeculationAnalyzerQueryExpressionOrderByType() { Test(@" using System.Linq; class Program { static void Main(string[] args) { var items = from i in Enumerable.Range(0, 3) orderby [|(long)i|] select i; } } ", "i", true); } [Fact] public void SpeculationAnalyzerDifferentAttributeConstructors() { Test(@" using System; class AnAttribute : Attribute { public AnAttribute(string a, long b) { } public AnAttribute(int a, int b) { } } class Program { [An([|""5""|], 6)] static void Main() { } } ", "5", false, "6"); // Note: the answer should have been that the replacement does change semantics (true), // however to have enough context one must analyze AttributeSyntax instead of separate ExpressionSyntaxes it contains, // which is not supported in SpeculationAnalyzer, but possible with GetSpeculativeSemanticModel API } [Fact] public void SpeculationAnalyzerCollectionInitializers() { Test(@" using System.Collections; class Collection : IEnumerable { public IEnumerator GetEnumerator() { throw new System.NotImplementedException(); } public void Add(string s) { } public void Add(int i) { } void Main() { var c = new Collection { [|""5""|] }; } } ", "5", true); } [Fact, WorkItem(1088815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1088815")] public void SpeculationAnalyzerBrokenCode() { Test(@" public interface IRogueAction { public string Name { get; private set; } protected IRogueAction(string name) { [|this.Name|] = name; } } ", "Name", semanticChanges: false, isBrokenCode: true); } [Fact, WorkItem(8111, "https://github.com/dotnet/roslyn/issues/8111")] public void SpeculationAnalyzerAnonymousObjectMemberDeclaredWithNeededCast() { Test(@" class Program { static void Main(string[] args) { object thing = new { shouldBeAnInt = [|(int)Directions.South|] }; } public enum Directions { North, East, South, West } } ", "Directions.South", semanticChanges: true); } [Fact, WorkItem(8111, "https://github.com/dotnet/roslyn/issues/8111")] public void SpeculationAnalyzerAnonymousObjectMemberDeclaredWithUnneededCast() { Test(@" class Program { static void Main(string[] args) { object thing = new { shouldBeAnInt = [|(Directions)Directions.South|] }; } public enum Directions { North, East, South, West } } ", "Directions.South", semanticChanges: false); } [Fact, WorkItem(19987, "https://github.com/dotnet/roslyn/issues/19987")] public void SpeculationAnalyzerSwitchCaseWithRedundantCast() { Test(@" class Program { static void Main(string[] arts) { var x = 1f; switch (x) { case [|(float) 1|]: System.Console.WriteLine(""one""); break; default: System.Console.WriteLine(""not one""); break; } } } ", "1", semanticChanges: false); } [Fact, WorkItem(19987, "https://github.com/dotnet/roslyn/issues/19987")] public void SpeculationAnalyzerSwitchCaseWithRequiredCast() { Test(@" class Program { static void Main(string[] arts) { object x = 1f; switch (x) { case [|(float) 1|]: // without the case, object x does not match int 1 System.Console.WriteLine(""one""); break; default: System.Console.WriteLine(""not one""); break; } } } ", "1", semanticChanges: true); } [Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")] public void SpeculationAnalyzerIndexerPropertyWithRedundantCast() { Test(code: @" class Indexer { public int this[int x] { get { return x; } } } class A { public Indexer Foo { get; } = new Indexer(); } class B : A { } class Program { static void Main(string[] args) { var b = new B(); var y = ([|(A)b|]).Foo[1]; } } ", replacementExpression: "b", semanticChanges: false); } [Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")] public void SpeculationAnalyzerIndexerPropertyWithRequiredCast() { Test(code: @" class Indexer { public int this[int x] { get { return x; } } } class A { public Indexer Foo { get; } = new Indexer(); } class B : A { public new Indexer Foo { get; } = new Indexer(); } class Program { static void Main(string[] args) { var b = new B(); var y = ([|(A)b|]).Foo[1]; } } ", replacementExpression: "b", semanticChanges: true); } [Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")] public void SpeculationAnalyzerDelegatePropertyWithRedundantCast() { Test(code: @" public delegate void MyDelegate(); class A { public MyDelegate Foo { get; } } class B : A { } class Program { static void Main(string[] args) { var b = new B(); ([|(A)b|]).Foo(); } } ", replacementExpression: "b", semanticChanges: false); } [Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")] public void SpeculationAnalyzerDelegatePropertyWithRequiredCast() { Test(code: @" public delegate void MyDelegate(); class A { public MyDelegate Foo { get; } } class B : A { public new MyDelegate Foo { get; } } class Program { static void Main(string[] args) { var b = new B(); ([|(A)b|]).Foo(); } } ", replacementExpression: "b", semanticChanges: true); } protected override SyntaxTree Parse(string text) => SyntaxFactory.ParseSyntaxTree(text); protected override bool IsExpressionNode(SyntaxNode node) => node is ExpressionSyntax; protected override Compilation CreateCompilation(SyntaxTree tree) { return CSharpCompilation.Create( CompilationName, new[] { tree }, References, TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(new[] { KeyValuePairUtil.Create("CS0219", ReportDiagnostic.Suppress) })); } protected override bool CompilationSucceeded(Compilation compilation, Stream temporaryStream) { var langCompilation = compilation; static bool isProblem(Diagnostic d) => d.Severity >= DiagnosticSeverity.Warning; return !langCompilation.GetDiagnostics().Any(isProblem) && !langCompilation.Emit(temporaryStream).Diagnostics.Any(isProblem); } protected override bool ReplacementChangesSemantics(SyntaxNode initialNode, SyntaxNode replacementNode, SemanticModel initialModel) => new SpeculationAnalyzer((ExpressionSyntax)initialNode, (ExpressionSyntax)replacementNode, initialModel, CancellationToken.None).ReplacementChangesSemantics(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Semantics; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Semantics { public class SpeculationAnalyzerTests : SpeculationAnalyzerTestsBase { [Fact] public void SpeculationAnalyzerDifferentOverloads() { Test(@" class Program { void Vain(int arg = 3) { } void Vain(string arg) { } void Main() { [|Vain(5)|]; } } ", "Vain(string.Empty)", true); } [Fact, WorkItem(672396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/672396")] public void SpeculationAnalyzerExtensionMethodExplicitInvocation() { Test(@" static class Program { public static void Vain(this int arg) { } static void Main() { [|5.Vain()|]; } } ", "Vain(5)", false); } [Fact] public void SpeculationAnalyzerImplicitBaseClassConversion() { Test(@" using System; class Program { void Main() { Exception ex = [|(Exception)new InvalidOperationException()|]; } } ", "new InvalidOperationException()", false); } [Fact] public void SpeculationAnalyzerImplicitNumericConversion() { Test(@" class Program { void Main() { long i = [|(long)5|]; } } ", "5", false); } [Fact] public void SpeculationAnalyzerImplicitUserConversion() { Test(@" class From { public static implicit operator To(From from) { return new To(); } } class To { } class Program { void Main() { To to = [|(To)new From()|]; } } ", "new From()", true); } [Fact] public void SpeculationAnalyzerExplicitConversion() { Test(@" using System; class Program { void Main() { Exception ex1 = new InvalidOperationException(); var ex2 = [|(InvalidOperationException)ex1|]; } } ", "ex1", true); } [Fact] public void SpeculationAnalyzerArrayImplementingNonGenericInterface() { Test(@" using System.Collections; class Program { void Main() { var a = new[] { 1, 2, 3 }; [|((IEnumerable)a).GetEnumerator()|]; } } ", "a.GetEnumerator()", false); } [Fact] public void SpeculationAnalyzerVirtualMethodWithBaseConversion() { Test(@" using System; using System.IO; class Program { void Main() { var s = new MemoryStream(); [|((Stream)s).Flush()|]; } } ", "s.Flush()", false); } [Fact] public void SpeculationAnalyzerNonVirtualMethodImplementingInterface() { Test(@" using System; class Class : IComparable { public int CompareTo(object other) { return 1; } } class Program { static void Main() { var c = new Class(); var d = new Class(); [|((IComparable)c).CompareTo(d)|]; } } ", "c.CompareTo(d)", true); } [Fact] public void SpeculationAnalyzerSealedClassImplementingInterface() { Test(@" using System; sealed class Class : IComparable { public int CompareTo(object other) { return 1; } } class Program { static void Main() { var c = new Class(); var d = new Class(); [|((IComparable)c).CompareTo(d)|]; } } ", "((IComparable)c).CompareTo(d)", semanticChanges: false); } [Fact] public void SpeculationAnalyzerValueTypeImplementingInterface() { Test(@" using System; class Program { void Main() { decimal d = 5; [|((IComparable<decimal>)d).CompareTo(6)|]; } } ", "d.CompareTo(6)", false); } [Fact] public void SpeculationAnalyzerBinaryExpressionIntVsLong() { Test(@" class Program { void Main() { var r = [|1+1L|]; } } ", "1+1", true); } [Fact] public void SpeculationAnalyzerQueryExpressionSelectType() { Test(@" using System.Linq; class Program { static void Main(string[] args) { var items = [|from i in Enumerable.Range(0, 3) select (long)i|]; } } ", "from i in Enumerable.Range(0, 3) select i", true); } [Fact] public void SpeculationAnalyzerQueryExpressionFromType() { Test(@" using System.Linq; class Program { static void Main(string[] args) { var items = [|from i in new long[0] select i|]; } } ", "from i in new int[0] select i", true); } [Fact] public void SpeculationAnalyzerQueryExpressionGroupByType() { Test(@" using System.Linq; class Program { static void Main(string[] args) { var items = [|from i in Enumerable.Range(0, 3) group (long)i by i|]; } } ", "from i in Enumerable.Range(0, 3) group i by i", true); } [Fact] public void SpeculationAnalyzerQueryExpressionOrderByType() { Test(@" using System.Linq; class Program { static void Main(string[] args) { var items = from i in Enumerable.Range(0, 3) orderby [|(long)i|] select i; } } ", "i", true); } [Fact] public void SpeculationAnalyzerDifferentAttributeConstructors() { Test(@" using System; class AnAttribute : Attribute { public AnAttribute(string a, long b) { } public AnAttribute(int a, int b) { } } class Program { [An([|""5""|], 6)] static void Main() { } } ", "5", false, "6"); // Note: the answer should have been that the replacement does change semantics (true), // however to have enough context one must analyze AttributeSyntax instead of separate ExpressionSyntaxes it contains, // which is not supported in SpeculationAnalyzer, but possible with GetSpeculativeSemanticModel API } [Fact] public void SpeculationAnalyzerCollectionInitializers() { Test(@" using System.Collections; class Collection : IEnumerable { public IEnumerator GetEnumerator() { throw new System.NotImplementedException(); } public void Add(string s) { } public void Add(int i) { } void Main() { var c = new Collection { [|""5""|] }; } } ", "5", true); } [Fact, WorkItem(1088815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1088815")] public void SpeculationAnalyzerBrokenCode() { Test(@" public interface IRogueAction { public string Name { get; private set; } protected IRogueAction(string name) { [|this.Name|] = name; } } ", "Name", semanticChanges: false, isBrokenCode: true); } [Fact, WorkItem(8111, "https://github.com/dotnet/roslyn/issues/8111")] public void SpeculationAnalyzerAnonymousObjectMemberDeclaredWithNeededCast() { Test(@" class Program { static void Main(string[] args) { object thing = new { shouldBeAnInt = [|(int)Directions.South|] }; } public enum Directions { North, East, South, West } } ", "Directions.South", semanticChanges: true); } [Fact, WorkItem(8111, "https://github.com/dotnet/roslyn/issues/8111")] public void SpeculationAnalyzerAnonymousObjectMemberDeclaredWithUnneededCast() { Test(@" class Program { static void Main(string[] args) { object thing = new { shouldBeAnInt = [|(Directions)Directions.South|] }; } public enum Directions { North, East, South, West } } ", "Directions.South", semanticChanges: false); } [Fact, WorkItem(19987, "https://github.com/dotnet/roslyn/issues/19987")] public void SpeculationAnalyzerSwitchCaseWithRedundantCast() { Test(@" class Program { static void Main(string[] arts) { var x = 1f; switch (x) { case [|(float) 1|]: System.Console.WriteLine(""one""); break; default: System.Console.WriteLine(""not one""); break; } } } ", "1", semanticChanges: false); } [Fact, WorkItem(19987, "https://github.com/dotnet/roslyn/issues/19987")] public void SpeculationAnalyzerSwitchCaseWithRequiredCast() { Test(@" class Program { static void Main(string[] arts) { object x = 1f; switch (x) { case [|(float) 1|]: // without the case, object x does not match int 1 System.Console.WriteLine(""one""); break; default: System.Console.WriteLine(""not one""); break; } } } ", "1", semanticChanges: true); } [Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")] public void SpeculationAnalyzerIndexerPropertyWithRedundantCast() { Test(code: @" class Indexer { public int this[int x] { get { return x; } } } class A { public Indexer Foo { get; } = new Indexer(); } class B : A { } class Program { static void Main(string[] args) { var b = new B(); var y = ([|(A)b|]).Foo[1]; } } ", replacementExpression: "b", semanticChanges: false); } [Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")] public void SpeculationAnalyzerIndexerPropertyWithRequiredCast() { Test(code: @" class Indexer { public int this[int x] { get { return x; } } } class A { public Indexer Foo { get; } = new Indexer(); } class B : A { public new Indexer Foo { get; } = new Indexer(); } class Program { static void Main(string[] args) { var b = new B(); var y = ([|(A)b|]).Foo[1]; } } ", replacementExpression: "b", semanticChanges: true); } [Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")] public void SpeculationAnalyzerDelegatePropertyWithRedundantCast() { Test(code: @" public delegate void MyDelegate(); class A { public MyDelegate Foo { get; } } class B : A { } class Program { static void Main(string[] args) { var b = new B(); ([|(A)b|]).Foo(); } } ", replacementExpression: "b", semanticChanges: false); } [Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")] public void SpeculationAnalyzerDelegatePropertyWithRequiredCast() { Test(code: @" public delegate void MyDelegate(); class A { public MyDelegate Foo { get; } } class B : A { public new MyDelegate Foo { get; } } class Program { static void Main(string[] args) { var b = new B(); ([|(A)b|]).Foo(); } } ", replacementExpression: "b", semanticChanges: true); } protected override SyntaxTree Parse(string text) => SyntaxFactory.ParseSyntaxTree(text); protected override bool IsExpressionNode(SyntaxNode node) => node is ExpressionSyntax; protected override Compilation CreateCompilation(SyntaxTree tree) { return CSharpCompilation.Create( CompilationName, new[] { tree }, References, TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(new[] { KeyValuePairUtil.Create("CS0219", ReportDiagnostic.Suppress) })); } protected override bool CompilationSucceeded(Compilation compilation, Stream temporaryStream) { var langCompilation = compilation; static bool isProblem(Diagnostic d) => d.Severity >= DiagnosticSeverity.Warning; return !langCompilation.GetDiagnostics().Any(isProblem) && !langCompilation.Emit(temporaryStream).Diagnostics.Any(isProblem); } protected override bool ReplacementChangesSemantics(SyntaxNode initialNode, SyntaxNode replacementNode, SemanticModel initialModel) => new SpeculationAnalyzer((ExpressionSyntax)initialNode, (ExpressionSyntax)replacementNode, initialModel, CancellationToken.None).ReplacementChangesSemantics(); } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/Core.Wpf/Preview/PreviewConflictViewTaggerProvider.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.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor.Shared.Preview; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview { [Export(typeof(ITaggerProvider))] [TagType(typeof(ConflictTag))] [ContentType(ContentTypeNames.RoslynContentType)] [ContentType(ContentTypeNames.XamlContentType)] [TextViewRole(TextViewRoles.PreviewRole)] internal class PreviewConflictTaggerProvider : AbstractPreviewTaggerProvider<ConflictTag> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PreviewConflictTaggerProvider() : base(PredefinedPreviewTaggerKeys.ConflictSpansKey, ConflictTag.Instance) { } } }
// Licensed to the .NET Foundation under one or more 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.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor.Shared.Preview; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.Preview { [Export(typeof(ITaggerProvider))] [TagType(typeof(ConflictTag))] [ContentType(ContentTypeNames.RoslynContentType)] [ContentType(ContentTypeNames.XamlContentType)] [TextViewRole(TextViewRoles.PreviewRole)] internal class PreviewConflictTaggerProvider : AbstractPreviewTaggerProvider<ConflictTag> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public PreviewConflictTaggerProvider() : base(PredefinedPreviewTaggerKeys.ConflictSpansKey, ConflictTag.Instance) { } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/Core/Portable/Compilation/SubsystemVersion.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.Globalization; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents subsystem version, see /subsystemversion command line /// option for details and valid values. /// /// The following table lists common subsystem versions of Windows. /// /// Windows version Subsystem version /// - Windows 2000 5.00 /// - Windows XP 5.01 /// - Windows Vista 6.00 /// - Windows 7 6.01 /// - Windows 8 Release Preview 6.02 /// </summary> public struct SubsystemVersion : IEquatable<SubsystemVersion> { /// <summary> /// Major subsystem version /// </summary> public int Major { get; } /// <summary> /// Minor subsystem version /// </summary> public int Minor { get; } /// <summary> /// Subsystem version not specified /// </summary> public static SubsystemVersion None => new SubsystemVersion(); /// <summary> /// Subsystem version: Windows 2000 /// </summary> public static SubsystemVersion Windows2000 => new SubsystemVersion(5, 0); /// <summary> /// Subsystem version: Windows XP /// </summary> public static SubsystemVersion WindowsXP => new SubsystemVersion(5, 1); /// <summary> /// Subsystem version: Windows Vista /// </summary> public static SubsystemVersion WindowsVista => new SubsystemVersion(6, 0); /// <summary> /// Subsystem version: Windows 7 /// </summary> public static SubsystemVersion Windows7 => new SubsystemVersion(6, 1); /// <summary> /// Subsystem version: Windows 8 /// </summary> public static SubsystemVersion Windows8 => new SubsystemVersion(6, 2); private SubsystemVersion(int major, int minor) { this.Major = major; this.Minor = minor; } /// <summary> /// Try parse subsystem version in "x.y" format. Note, no spaces are allowed in string representation. /// </summary> /// <param name="str">String to parse</param> /// <param name="version">the value if successfully parsed or None otherwise</param> /// <returns>true if parsed successfully, false otherwise</returns> public static bool TryParse(string str, out SubsystemVersion version) { version = SubsystemVersion.None; if (!string.IsNullOrWhiteSpace(str)) { string major; string? minor; int index = str.IndexOf('.'); //found a dot if (index >= 0) { //if there's a dot and no following digits, it's an error in the native compiler. if (str.Length == index + 1) return false; major = str.Substring(0, index); minor = str.Substring(index + 1); } else { major = str; minor = null; } int majorValue; if (major != major.Trim() || !int.TryParse(major, NumberStyles.None, CultureInfo.InvariantCulture, out majorValue) || majorValue >= 65356 || majorValue < 0) { return false; } int minorValue = 0; //it's fine to have just a single number specified for the subsystem. if (minor != null) { if (minor != minor.Trim() || !int.TryParse(minor, NumberStyles.None, CultureInfo.InvariantCulture, out minorValue) || minorValue >= 65356 || minorValue < 0) { return false; } } version = new SubsystemVersion(majorValue, minorValue); return true; } return false; } /// <summary> /// Create a new instance of subsystem version with specified major and minor values. /// </summary> /// <param name="major">major subsystem version</param> /// <param name="minor">minor subsystem version</param> /// <returns>subsystem version with provided major and minor</returns> public static SubsystemVersion Create(int major, int minor) { return new SubsystemVersion(major, minor); } /// <summary> /// Subsystem version default for the specified output kind and platform combination /// </summary> /// <param name="outputKind">Output kind</param> /// <param name="platform">Platform</param> /// <returns>Subsystem version</returns> internal static SubsystemVersion Default(OutputKind outputKind, Platform platform) { if (platform == Platform.Arm) return Windows8; switch (outputKind) { case OutputKind.ConsoleApplication: case OutputKind.DynamicallyLinkedLibrary: case OutputKind.NetModule: case OutputKind.WindowsApplication: return new SubsystemVersion(4, 0); case OutputKind.WindowsRuntimeApplication: case OutputKind.WindowsRuntimeMetadata: return Windows8; default: throw new ArgumentOutOfRangeException(CodeAnalysisResources.OutputKindNotSupported, "outputKind"); } } /// <summary> /// True if the subsystem version has a valid value /// </summary> public bool IsValid { get { return this.Major >= 0 && this.Minor >= 0 && this.Major < 65536 && this.Minor < 65536; } } public override bool Equals(object? obj) { return obj is SubsystemVersion && Equals((SubsystemVersion)obj); } public override int GetHashCode() { return Hash.Combine(this.Minor.GetHashCode(), this.Major.GetHashCode()); } public bool Equals(SubsystemVersion other) { return this.Major == other.Major && this.Minor == other.Minor; } public override string ToString() { return string.Format("{0}.{1:00}", this.Major, this.Minor); } } }
// Licensed to the .NET Foundation under one or more 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.Globalization; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents subsystem version, see /subsystemversion command line /// option for details and valid values. /// /// The following table lists common subsystem versions of Windows. /// /// Windows version Subsystem version /// - Windows 2000 5.00 /// - Windows XP 5.01 /// - Windows Vista 6.00 /// - Windows 7 6.01 /// - Windows 8 Release Preview 6.02 /// </summary> public struct SubsystemVersion : IEquatable<SubsystemVersion> { /// <summary> /// Major subsystem version /// </summary> public int Major { get; } /// <summary> /// Minor subsystem version /// </summary> public int Minor { get; } /// <summary> /// Subsystem version not specified /// </summary> public static SubsystemVersion None => new SubsystemVersion(); /// <summary> /// Subsystem version: Windows 2000 /// </summary> public static SubsystemVersion Windows2000 => new SubsystemVersion(5, 0); /// <summary> /// Subsystem version: Windows XP /// </summary> public static SubsystemVersion WindowsXP => new SubsystemVersion(5, 1); /// <summary> /// Subsystem version: Windows Vista /// </summary> public static SubsystemVersion WindowsVista => new SubsystemVersion(6, 0); /// <summary> /// Subsystem version: Windows 7 /// </summary> public static SubsystemVersion Windows7 => new SubsystemVersion(6, 1); /// <summary> /// Subsystem version: Windows 8 /// </summary> public static SubsystemVersion Windows8 => new SubsystemVersion(6, 2); private SubsystemVersion(int major, int minor) { this.Major = major; this.Minor = minor; } /// <summary> /// Try parse subsystem version in "x.y" format. Note, no spaces are allowed in string representation. /// </summary> /// <param name="str">String to parse</param> /// <param name="version">the value if successfully parsed or None otherwise</param> /// <returns>true if parsed successfully, false otherwise</returns> public static bool TryParse(string str, out SubsystemVersion version) { version = SubsystemVersion.None; if (!string.IsNullOrWhiteSpace(str)) { string major; string? minor; int index = str.IndexOf('.'); //found a dot if (index >= 0) { //if there's a dot and no following digits, it's an error in the native compiler. if (str.Length == index + 1) return false; major = str.Substring(0, index); minor = str.Substring(index + 1); } else { major = str; minor = null; } int majorValue; if (major != major.Trim() || !int.TryParse(major, NumberStyles.None, CultureInfo.InvariantCulture, out majorValue) || majorValue >= 65356 || majorValue < 0) { return false; } int minorValue = 0; //it's fine to have just a single number specified for the subsystem. if (minor != null) { if (minor != minor.Trim() || !int.TryParse(minor, NumberStyles.None, CultureInfo.InvariantCulture, out minorValue) || minorValue >= 65356 || minorValue < 0) { return false; } } version = new SubsystemVersion(majorValue, minorValue); return true; } return false; } /// <summary> /// Create a new instance of subsystem version with specified major and minor values. /// </summary> /// <param name="major">major subsystem version</param> /// <param name="minor">minor subsystem version</param> /// <returns>subsystem version with provided major and minor</returns> public static SubsystemVersion Create(int major, int minor) { return new SubsystemVersion(major, minor); } /// <summary> /// Subsystem version default for the specified output kind and platform combination /// </summary> /// <param name="outputKind">Output kind</param> /// <param name="platform">Platform</param> /// <returns>Subsystem version</returns> internal static SubsystemVersion Default(OutputKind outputKind, Platform platform) { if (platform == Platform.Arm) return Windows8; switch (outputKind) { case OutputKind.ConsoleApplication: case OutputKind.DynamicallyLinkedLibrary: case OutputKind.NetModule: case OutputKind.WindowsApplication: return new SubsystemVersion(4, 0); case OutputKind.WindowsRuntimeApplication: case OutputKind.WindowsRuntimeMetadata: return Windows8; default: throw new ArgumentOutOfRangeException(CodeAnalysisResources.OutputKindNotSupported, "outputKind"); } } /// <summary> /// True if the subsystem version has a valid value /// </summary> public bool IsValid { get { return this.Major >= 0 && this.Minor >= 0 && this.Major < 65536 && this.Minor < 65536; } } public override bool Equals(object? obj) { return obj is SubsystemVersion && Equals((SubsystemVersion)obj); } public override int GetHashCode() { return Hash.Combine(this.Minor.GetHashCode(), this.Major.GetHashCode()); } public bool Equals(SubsystemVersion other) { return this.Major == other.Major && this.Minor == other.Minor; } public override string ToString() { return string.Format("{0}.{1:00}", this.Major, this.Minor); } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/Test/Core/Compilation/MetadataReferenceExtensions.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.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using Roslyn.Test.Utilities; namespace Microsoft.CodeAnalysis.Test.Utilities { public static class MetadataReferenceExtensions { public static Guid GetModuleVersionId(this MetadataReference metadataReference) => GetManifestModuleMetadata(metadataReference).GetModuleVersionId(); public static AssemblyIdentity GetAssemblyIdentity(this MetadataReference reference) => reference.GetManifestModuleMetadata().MetadataReader.ReadAssemblyIdentityOrThrow(); public static ModuleMetadata GetManifestModuleMetadata(this MetadataReference reference) => reference is PortableExecutableReference peReference ? peReference.GetManifestModuleMetadata() : throw new InvalidOperationException(); public static ModuleMetadata GetManifestModuleMetadata(this PortableExecutableReference peReference) { switch (peReference.GetMetadata()) { case AssemblyMetadata assemblyMetadata: { if (assemblyMetadata.GetModules() is { Length: 1 } modules) { return modules[0]; } } break; case ModuleMetadata moduleMetadata: return moduleMetadata; } throw new InvalidOperationException(); } } }
// Licensed to the .NET Foundation under one or more 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.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using Roslyn.Test.Utilities; namespace Microsoft.CodeAnalysis.Test.Utilities { public static class MetadataReferenceExtensions { public static Guid GetModuleVersionId(this MetadataReference metadataReference) => GetManifestModuleMetadata(metadataReference).GetModuleVersionId(); public static AssemblyIdentity GetAssemblyIdentity(this MetadataReference reference) => reference.GetManifestModuleMetadata().MetadataReader.ReadAssemblyIdentityOrThrow(); public static ModuleMetadata GetManifestModuleMetadata(this MetadataReference reference) => reference is PortableExecutableReference peReference ? peReference.GetManifestModuleMetadata() : throw new InvalidOperationException(); public static ModuleMetadata GetManifestModuleMetadata(this PortableExecutableReference peReference) { switch (peReference.GetMetadata()) { case AssemblyMetadata assemblyMetadata: { if (assemblyMetadata.GetModules() is { Length: 1 } modules) { return modules[0]; } } break; case ModuleMetadata moduleMetadata: return moduleMetadata; } throw new InvalidOperationException(); } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/Core/Implementation/SplitComment/ISplitCommentService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.Editor.Implementation.SplitComment { internal interface ISplitCommentService : ILanguageService { string CommentStart { get; } bool IsAllowed(SyntaxNode root, SyntaxTrivia trivia); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.Editor.Implementation.SplitComment { internal interface ISplitCommentService : ILanguageService { string CommentStart { get; } bool IsAllowed(SyntaxNode root, SyntaxTrivia trivia); } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/Core/Portable/Log/AggregateLogger.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Internal.Log { /// <summary> /// a logger that aggregate multiple loggers /// </summary> internal sealed class AggregateLogger : ILogger { private readonly ImmutableArray<ILogger> _loggers; public static AggregateLogger Create(params ILogger[] loggers) { var set = new HashSet<ILogger>(); // flatten loggers foreach (var logger in loggers.WhereNotNull()) { if (logger is AggregateLogger aggregateLogger) { set.UnionWith(aggregateLogger._loggers); continue; } set.Add(logger); } return new AggregateLogger(set.ToImmutableArray()); } public static ILogger AddOrReplace(ILogger newLogger, ILogger oldLogger, Func<ILogger, bool> predicate) { if (newLogger == null) { return oldLogger; } if (oldLogger == null) { return newLogger; } var aggregateLogger = oldLogger as AggregateLogger; if (aggregateLogger == null) { // replace old logger with new logger if (predicate(oldLogger)) { // this might not aggregate logger return newLogger; } // merge two return new AggregateLogger(ImmutableArray.Create(newLogger, oldLogger)); } var set = new HashSet<ILogger>(); foreach (var logger in aggregateLogger._loggers) { // replace this logger with new logger if (predicate(logger)) { set.Add(newLogger); continue; } // add old one back set.Add(logger); } // add new logger. if we already added one, this will be ignored. set.Add(newLogger); return new AggregateLogger(set.ToImmutableArray()); } public static ILogger Remove(ILogger logger, Func<ILogger, bool> predicate) { var aggregateLogger = logger as AggregateLogger; if (aggregateLogger == null) { // remove the logger if (predicate(logger)) { return null; } return logger; } // filter out loggers var set = aggregateLogger._loggers.Where(l => !predicate(l)).ToSet(); if (set.Count == 1) { return set.Single(); } return new AggregateLogger(set.ToImmutableArray()); } private AggregateLogger(ImmutableArray<ILogger> loggers) => _loggers = loggers; public bool IsEnabled(FunctionId functionId) => true; public void Log(FunctionId functionId, LogMessage logMessage) { for (var i = 0; i < _loggers.Length; i++) { var logger = _loggers[i]; if (!logger.IsEnabled(functionId)) { continue; } logger.Log(functionId, logMessage); } } public void LogBlockStart(FunctionId functionId, LogMessage logMessage, int uniquePairId, CancellationToken cancellationToken) { for (var i = 0; i < _loggers.Length; i++) { var logger = _loggers[i]; if (!logger.IsEnabled(functionId)) { continue; } logger.LogBlockStart(functionId, logMessage, uniquePairId, cancellationToken); } } public void LogBlockEnd(FunctionId functionId, LogMessage logMessage, int uniquePairId, int delta, CancellationToken cancellationToken) { for (var i = 0; i < _loggers.Length; i++) { var logger = _loggers[i]; if (!logger.IsEnabled(functionId)) { continue; } logger.LogBlockEnd(functionId, logMessage, uniquePairId, delta, cancellationToken); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Internal.Log { /// <summary> /// a logger that aggregate multiple loggers /// </summary> internal sealed class AggregateLogger : ILogger { private readonly ImmutableArray<ILogger> _loggers; public static AggregateLogger Create(params ILogger[] loggers) { var set = new HashSet<ILogger>(); // flatten loggers foreach (var logger in loggers.WhereNotNull()) { if (logger is AggregateLogger aggregateLogger) { set.UnionWith(aggregateLogger._loggers); continue; } set.Add(logger); } return new AggregateLogger(set.ToImmutableArray()); } public static ILogger AddOrReplace(ILogger newLogger, ILogger oldLogger, Func<ILogger, bool> predicate) { if (newLogger == null) { return oldLogger; } if (oldLogger == null) { return newLogger; } var aggregateLogger = oldLogger as AggregateLogger; if (aggregateLogger == null) { // replace old logger with new logger if (predicate(oldLogger)) { // this might not aggregate logger return newLogger; } // merge two return new AggregateLogger(ImmutableArray.Create(newLogger, oldLogger)); } var set = new HashSet<ILogger>(); foreach (var logger in aggregateLogger._loggers) { // replace this logger with new logger if (predicate(logger)) { set.Add(newLogger); continue; } // add old one back set.Add(logger); } // add new logger. if we already added one, this will be ignored. set.Add(newLogger); return new AggregateLogger(set.ToImmutableArray()); } public static ILogger Remove(ILogger logger, Func<ILogger, bool> predicate) { var aggregateLogger = logger as AggregateLogger; if (aggregateLogger == null) { // remove the logger if (predicate(logger)) { return null; } return logger; } // filter out loggers var set = aggregateLogger._loggers.Where(l => !predicate(l)).ToSet(); if (set.Count == 1) { return set.Single(); } return new AggregateLogger(set.ToImmutableArray()); } private AggregateLogger(ImmutableArray<ILogger> loggers) => _loggers = loggers; public bool IsEnabled(FunctionId functionId) => true; public void Log(FunctionId functionId, LogMessage logMessage) { for (var i = 0; i < _loggers.Length; i++) { var logger = _loggers[i]; if (!logger.IsEnabled(functionId)) { continue; } logger.Log(functionId, logMessage); } } public void LogBlockStart(FunctionId functionId, LogMessage logMessage, int uniquePairId, CancellationToken cancellationToken) { for (var i = 0; i < _loggers.Length; i++) { var logger = _loggers[i]; if (!logger.IsEnabled(functionId)) { continue; } logger.LogBlockStart(functionId, logMessage, uniquePairId, cancellationToken); } } public void LogBlockEnd(FunctionId functionId, LogMessage logMessage, int uniquePairId, int delta, CancellationToken cancellationToken) { for (var i = 0; i < _loggers.Length; i++) { var logger = _loggers[i]; if (!logger.IsEnabled(functionId)) { continue; } logger.LogBlockEnd(functionId, logMessage, uniquePairId, delta, cancellationToken); } } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/VisualStudio/CSharp/Test/PersistentStorage/SQLiteV2PersistentStorageTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SQLite.v2; using Microsoft.CodeAnalysis.Storage; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.WorkspaceServices { /// <remarks> /// Tests are inherited from <see cref="AbstractPersistentStorageTests"/>. That way we can /// write tests once and have them run against all <see cref="IPersistentStorageService"/> /// implementations. /// </remarks> public class SQLiteV2PersistentStorageTests : AbstractPersistentStorageTests { internal override AbstractPersistentStorageService GetStorageService(OptionSet options, IMefHostExportProvider exportProvider, IPersistentStorageLocationService locationService, IPersistentStorageFaultInjector? faultInjector, string relativePathBase) => new SQLitePersistentStorageService( options, exportProvider.GetExports<SQLiteConnectionPoolService>().Single().Value, locationService, exportProvider.GetExports<IAsynchronousOperationListenerProvider>().Single().Value.GetListener(FeatureAttribute.PersistentStorage), faultInjector); [Fact] public async Task TestCrashInNewConnection() { var solution = CreateOrOpenSolution(nullPaths: true); var hitInjector = false; var faultInjector = new PersistentStorageFaultInjector( onNewConnection: () => { hitInjector = true; throw new Exception(); }, onFatalError: e => throw e); // Because instantiating the connection will fail, we will not get back // a working persistent storage. await using (var storage = await GetStorageAsync(solution, faultInjector)) using (var memStream = new MemoryStream()) using (var streamWriter = new StreamWriter(memStream)) { streamWriter.WriteLine("contents"); streamWriter.Flush(); memStream.Position = 0; await storage.WriteStreamAsync("temp", memStream); var readStream = await storage.ReadStreamAsync("temp"); // Because we don't have a real storage service, we should get back // null even when trying to read something we just wrote. Assert.Null(readStream); } Assert.True(hitInjector); // Ensure we don't get a crash due to SqlConnection's finalizer running. for (var i = 0; i < 10; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); } } private class PersistentStorageFaultInjector : IPersistentStorageFaultInjector { private readonly Action? _onNewConnection; private readonly Action<Exception>? _onFatalError; public PersistentStorageFaultInjector( Action? onNewConnection = null, Action<Exception>? onFatalError = null) { _onNewConnection = onNewConnection; _onFatalError = onFatalError; } public void OnNewConnection() => _onNewConnection?.Invoke(); public void OnFatalError(Exception ex) => _onFatalError?.Invoke(ex); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SQLite.v2; using Microsoft.CodeAnalysis.Storage; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.WorkspaceServices { /// <remarks> /// Tests are inherited from <see cref="AbstractPersistentStorageTests"/>. That way we can /// write tests once and have them run against all <see cref="IPersistentStorageService"/> /// implementations. /// </remarks> public class SQLiteV2PersistentStorageTests : AbstractPersistentStorageTests { internal override AbstractPersistentStorageService GetStorageService(OptionSet options, IMefHostExportProvider exportProvider, IPersistentStorageLocationService locationService, IPersistentStorageFaultInjector? faultInjector, string relativePathBase) => new SQLitePersistentStorageService( options, exportProvider.GetExports<SQLiteConnectionPoolService>().Single().Value, locationService, exportProvider.GetExports<IAsynchronousOperationListenerProvider>().Single().Value.GetListener(FeatureAttribute.PersistentStorage), faultInjector); [Fact] public async Task TestCrashInNewConnection() { var solution = CreateOrOpenSolution(nullPaths: true); var hitInjector = false; var faultInjector = new PersistentStorageFaultInjector( onNewConnection: () => { hitInjector = true; throw new Exception(); }, onFatalError: e => throw e); // Because instantiating the connection will fail, we will not get back // a working persistent storage. await using (var storage = await GetStorageAsync(solution, faultInjector)) using (var memStream = new MemoryStream()) using (var streamWriter = new StreamWriter(memStream)) { streamWriter.WriteLine("contents"); streamWriter.Flush(); memStream.Position = 0; await storage.WriteStreamAsync("temp", memStream); var readStream = await storage.ReadStreamAsync("temp"); // Because we don't have a real storage service, we should get back // null even when trying to read something we just wrote. Assert.Null(readStream); } Assert.True(hitInjector); // Ensure we don't get a crash due to SqlConnection's finalizer running. for (var i = 0; i < 10; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); } } private class PersistentStorageFaultInjector : IPersistentStorageFaultInjector { private readonly Action? _onNewConnection; private readonly Action<Exception>? _onFatalError; public PersistentStorageFaultInjector( Action? onNewConnection = null, Action<Exception>? onFatalError = null) { _onNewConnection = onNewConnection; _onFatalError = onFatalError; } public void OnNewConnection() => _onNewConnection?.Invoke(); public void OnFatalError(Exception ex) => _onFatalError?.Invoke(ex); } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/CSharp/Portable/Errors/MessageProvider.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.Globalization; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class MessageProvider : CommonMessageProvider, IObjectWritable { public static readonly MessageProvider Instance = new MessageProvider(); static MessageProvider() { ObjectBinder.RegisterTypeReader(typeof(MessageProvider), r => Instance); } private MessageProvider() { } bool IObjectWritable.ShouldReuseInSerialization => true; void IObjectWritable.WriteTo(ObjectWriter writer) { // write nothing, always read/deserialized as global Instance } public override DiagnosticSeverity GetSeverity(int code) { return ErrorFacts.GetSeverity((ErrorCode)code); } public override string LoadMessage(int code, CultureInfo language) { return ErrorFacts.GetMessage((ErrorCode)code, language); } public override LocalizableString GetMessageFormat(int code) { return ErrorFacts.GetMessageFormat((ErrorCode)code); } public override LocalizableString GetDescription(int code) { return ErrorFacts.GetDescription((ErrorCode)code); } public override LocalizableString GetTitle(int code) { return ErrorFacts.GetTitle((ErrorCode)code); } public override string GetHelpLink(int code) { return ErrorFacts.GetHelpLink((ErrorCode)code); } public override string GetCategory(int code) { return ErrorFacts.GetCategory((ErrorCode)code); } public override string CodePrefix { get { return "CS"; } } // Given a message identifier (e.g., CS0219), severity, warning as error and a culture, // get the entire prefix (e.g., "error CS0219:" for C#) used on error messages. public override string GetMessagePrefix(string id, DiagnosticSeverity severity, bool isWarningAsError, CultureInfo culture) { return String.Format(culture, "{0} {1}", severity == DiagnosticSeverity.Error || isWarningAsError ? "error" : "warning", id); } public override int GetWarningLevel(int code) { return ErrorFacts.GetWarningLevel((ErrorCode)code); } public override Type ErrorCodeType { get { return typeof(ErrorCode); } } public override Diagnostic CreateDiagnostic(int code, Location location, params object[] args) { var info = new CSDiagnosticInfo((ErrorCode)code, args, ImmutableArray<Symbol>.Empty, ImmutableArray<Location>.Empty); return new CSDiagnostic(info, location); } public override Diagnostic CreateDiagnostic(DiagnosticInfo info) { return new CSDiagnostic(info, Location.None); } public override string GetErrorDisplayString(ISymbol symbol) { // show extra info for assembly if possible such as version, public key token etc. if (symbol.Kind == SymbolKind.Assembly || symbol.Kind == SymbolKind.Namespace) { return symbol.ToString(); } return SymbolDisplay.ToDisplayString(symbol, SymbolDisplayFormat.CSharpShortErrorMessageFormat); } public override ReportDiagnostic GetDiagnosticReport(DiagnosticInfo diagnosticInfo, CompilationOptions options) { bool hasPragmaSuppression; return CSharpDiagnosticFilter.GetDiagnosticReport(diagnosticInfo.Severity, true, diagnosticInfo.MessageIdentifier, diagnosticInfo.WarningLevel, Location.None, diagnosticInfo.Category, options.WarningLevel, ((CSharpCompilationOptions)options).NullableContextOptions, options.GeneralDiagnosticOption, options.SpecificDiagnosticOptions, options.SyntaxTreeOptionsProvider, CancellationToken.None, // We don't have a tree so there's no need to pass cancellation to the SyntaxTreeOptionsProvider out hasPragmaSuppression); } public override int ERR_FailedToCreateTempFile => (int)ErrorCode.ERR_CantMakeTempFile; public override int ERR_MultipleAnalyzerConfigsInSameDir => (int)ErrorCode.ERR_MultipleAnalyzerConfigsInSameDir; // command line: public override int ERR_ExpectedSingleScript => (int)ErrorCode.ERR_ExpectedSingleScript; public override int ERR_OpenResponseFile => (int)ErrorCode.ERR_OpenResponseFile; public override int ERR_InvalidPathMap => (int)ErrorCode.ERR_InvalidPathMap; public override int FTL_InvalidInputFileName => (int)ErrorCode.FTL_InvalidInputFileName; public override int ERR_FileNotFound => (int)ErrorCode.ERR_FileNotFound; public override int ERR_NoSourceFile => (int)ErrorCode.ERR_NoSourceFile; public override int ERR_CantOpenFileWrite => (int)ErrorCode.ERR_CantOpenFileWrite; public override int ERR_OutputWriteFailed => (int)ErrorCode.ERR_OutputWriteFailed; public override int WRN_NoConfigNotOnCommandLine => (int)ErrorCode.WRN_NoConfigNotOnCommandLine; public override int ERR_BinaryFile => (int)ErrorCode.ERR_BinaryFile; public override int WRN_AnalyzerCannotBeCreated => (int)ErrorCode.WRN_AnalyzerCannotBeCreated; public override int WRN_NoAnalyzerInAssembly => (int)ErrorCode.WRN_NoAnalyzerInAssembly; public override int WRN_UnableToLoadAnalyzer => (int)ErrorCode.WRN_UnableToLoadAnalyzer; public override int WRN_AnalyzerReferencesFramework => (int)ErrorCode.WRN_AnalyzerReferencesFramework; public override int INF_UnableToLoadSomeTypesInAnalyzer => (int)ErrorCode.INF_UnableToLoadSomeTypesInAnalyzer; public override int ERR_CantReadRulesetFile => (int)ErrorCode.ERR_CantReadRulesetFile; public override int ERR_CompileCancelled => (int)ErrorCode.ERR_CompileCancelled; // parse options: public override int ERR_BadSourceCodeKind => (int)ErrorCode.ERR_BadSourceCodeKind; public override int ERR_BadDocumentationMode => (int)ErrorCode.ERR_BadDocumentationMode; // compilation options: public override int ERR_BadCompilationOptionValue => (int)ErrorCode.ERR_BadCompilationOptionValue; public override int ERR_MutuallyExclusiveOptions => (int)ErrorCode.ERR_MutuallyExclusiveOptions; // emit options: public override int ERR_InvalidDebugInformationFormat => (int)ErrorCode.ERR_InvalidDebugInformationFormat; public override int ERR_InvalidOutputName => (int)ErrorCode.ERR_InvalidOutputName; public override int ERR_InvalidFileAlignment => (int)ErrorCode.ERR_InvalidFileAlignment; public override int ERR_InvalidSubsystemVersion => (int)ErrorCode.ERR_InvalidSubsystemVersion; public override int ERR_InvalidInstrumentationKind => (int)ErrorCode.ERR_InvalidInstrumentationKind; public override int ERR_InvalidHashAlgorithmName => (int)ErrorCode.ERR_InvalidHashAlgorithmName; // reference manager: public override int ERR_MetadataFileNotAssembly => (int)ErrorCode.ERR_ImportNonAssembly; public override int ERR_MetadataFileNotModule => (int)ErrorCode.ERR_AddModuleAssembly; public override int ERR_InvalidAssemblyMetadata => (int)ErrorCode.FTL_MetadataCantOpenFile; public override int ERR_InvalidModuleMetadata => (int)ErrorCode.FTL_MetadataCantOpenFile; public override int ERR_ErrorOpeningAssemblyFile => (int)ErrorCode.FTL_MetadataCantOpenFile; public override int ERR_ErrorOpeningModuleFile => (int)ErrorCode.FTL_MetadataCantOpenFile; public override int ERR_MetadataFileNotFound => (int)ErrorCode.ERR_NoMetadataFile; public override int ERR_MetadataReferencesNotSupported => (int)ErrorCode.ERR_MetadataReferencesNotSupported; public override int ERR_LinkedNetmoduleMetadataMustProvideFullPEImage => (int)ErrorCode.ERR_LinkedNetmoduleMetadataMustProvideFullPEImage; public override void ReportDuplicateMetadataReferenceStrong(DiagnosticBag diagnostics, Location location, MetadataReference reference, AssemblyIdentity identity, MetadataReference equivalentReference, AssemblyIdentity equivalentIdentity) { diagnostics.Add(ErrorCode.ERR_DuplicateImport, location, reference.Display ?? identity.GetDisplayName(), equivalentReference.Display ?? equivalentIdentity.GetDisplayName()); } public override void ReportDuplicateMetadataReferenceWeak(DiagnosticBag diagnostics, Location location, MetadataReference reference, AssemblyIdentity identity, MetadataReference equivalentReference, AssemblyIdentity equivalentIdentity) { diagnostics.Add(ErrorCode.ERR_DuplicateImportSimple, location, identity.Name, reference.Display ?? identity.GetDisplayName()); } // signing: public override int ERR_PublicKeyFileFailure => (int)ErrorCode.ERR_PublicKeyFileFailure; public override int ERR_PublicKeyContainerFailure => (int)ErrorCode.ERR_PublicKeyContainerFailure; public override int ERR_OptionMustBeAbsolutePath => (int)ErrorCode.ERR_OptionMustBeAbsolutePath; // resources: public override int ERR_CantReadResource => (int)ErrorCode.ERR_CantReadResource; public override int ERR_CantOpenWin32Resource => (int)ErrorCode.ERR_CantOpenWin32Res; public override int ERR_CantOpenWin32Manifest => (int)ErrorCode.ERR_CantOpenWin32Manifest; public override int ERR_CantOpenWin32Icon => (int)ErrorCode.ERR_CantOpenIcon; public override int ERR_ErrorBuildingWin32Resource => (int)ErrorCode.ERR_ErrorBuildingWin32Resources; public override int ERR_BadWin32Resource => (int)ErrorCode.ERR_BadWin32Res; public override int ERR_ResourceFileNameNotUnique => (int)ErrorCode.ERR_ResourceFileNameNotUnique; public override int ERR_ResourceNotUnique => (int)ErrorCode.ERR_ResourceNotUnique; public override int ERR_ResourceInModule => (int)ErrorCode.ERR_CantRefResource; // pseudo-custom attributes: public override int ERR_PermissionSetAttributeFileReadError => (int)ErrorCode.ERR_PermissionSetAttributeFileReadError; // PDB Writer: public override int ERR_EncodinglessSyntaxTree => (int)ErrorCode.ERR_EncodinglessSyntaxTree; public override int WRN_PdbUsingNameTooLong => (int)ErrorCode.WRN_DebugFullNameTooLong; public override int WRN_PdbLocalNameTooLong => (int)ErrorCode.WRN_PdbLocalNameTooLong; public override int ERR_PdbWritingFailed => (int)ErrorCode.FTL_DebugEmitFailure; // PE Writer: public override int ERR_MetadataNameTooLong => (int)ErrorCode.ERR_MetadataNameTooLong; public override int ERR_EncReferenceToAddedMember => (int)ErrorCode.ERR_EncReferenceToAddedMember; public override int ERR_TooManyUserStrings => (int)ErrorCode.ERR_TooManyUserStrings; public override int ERR_PeWritingFailure => (int)ErrorCode.ERR_PeWritingFailure; public override int ERR_ModuleEmitFailure => (int)ErrorCode.ERR_ModuleEmitFailure; public override int ERR_EncUpdateFailedMissingAttribute => (int)ErrorCode.ERR_EncUpdateFailedMissingAttribute; public override int ERR_InvalidDebugInfo => (int)ErrorCode.ERR_InvalidDebugInfo; // Generators: public override int WRN_GeneratorFailedDuringInitialization => (int)ErrorCode.WRN_GeneratorFailedDuringInitialization; public override int WRN_GeneratorFailedDuringGeneration => (int)ErrorCode.WRN_GeneratorFailedDuringGeneration; protected override void ReportInvalidAttributeArgument(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, AttributeData attribute) { var node = (AttributeSyntax)attributeSyntax; CSharpSyntaxNode attributeArgumentSyntax = attribute.GetAttributeArgumentSyntax(parameterIndex, node); diagnostics.Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntax.Location, node.GetErrorDisplayName()); } protected override void ReportInvalidNamedArgument(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int namedArgumentIndex, ITypeSymbol attributeClass, string parameterName) { var node = (AttributeSyntax)attributeSyntax; diagnostics.Add(ErrorCode.ERR_InvalidNamedArgument, node.ArgumentList.Arguments[namedArgumentIndex].Location, parameterName); } protected override void ReportParameterNotValidForType(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int namedArgumentIndex) { var node = (AttributeSyntax)attributeSyntax; diagnostics.Add(ErrorCode.ERR_ParameterNotValidForType, node.ArgumentList.Arguments[namedArgumentIndex].Location); } protected override void ReportMarshalUnmanagedTypeNotValidForFields(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, string unmanagedTypeName, AttributeData attribute) { var node = (AttributeSyntax)attributeSyntax; CSharpSyntaxNode attributeArgumentSyntax = attribute.GetAttributeArgumentSyntax(parameterIndex, node); diagnostics.Add(ErrorCode.ERR_MarshalUnmanagedTypeNotValidForFields, attributeArgumentSyntax.Location, unmanagedTypeName); } protected override void ReportMarshalUnmanagedTypeOnlyValidForFields(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, string unmanagedTypeName, AttributeData attribute) { var node = (AttributeSyntax)attributeSyntax; CSharpSyntaxNode attributeArgumentSyntax = attribute.GetAttributeArgumentSyntax(parameterIndex, node); diagnostics.Add(ErrorCode.ERR_MarshalUnmanagedTypeOnlyValidForFields, attributeArgumentSyntax.Location, unmanagedTypeName); } protected override void ReportAttributeParameterRequired(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, string parameterName) { var node = (AttributeSyntax)attributeSyntax; diagnostics.Add(ErrorCode.ERR_AttributeParameterRequired1, node.Name.Location, parameterName); } protected override void ReportAttributeParameterRequired(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, string parameterName1, string parameterName2) { var node = (AttributeSyntax)attributeSyntax; diagnostics.Add(ErrorCode.ERR_AttributeParameterRequired2, node.Name.Location, parameterName1, parameterName2); } public override int ERR_BadAssemblyName => (int)ErrorCode.ERR_BadAssemblyName; } }
// Licensed to the .NET Foundation under one or more 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.Globalization; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal sealed class MessageProvider : CommonMessageProvider, IObjectWritable { public static readonly MessageProvider Instance = new MessageProvider(); static MessageProvider() { ObjectBinder.RegisterTypeReader(typeof(MessageProvider), r => Instance); } private MessageProvider() { } bool IObjectWritable.ShouldReuseInSerialization => true; void IObjectWritable.WriteTo(ObjectWriter writer) { // write nothing, always read/deserialized as global Instance } public override DiagnosticSeverity GetSeverity(int code) { return ErrorFacts.GetSeverity((ErrorCode)code); } public override string LoadMessage(int code, CultureInfo language) { return ErrorFacts.GetMessage((ErrorCode)code, language); } public override LocalizableString GetMessageFormat(int code) { return ErrorFacts.GetMessageFormat((ErrorCode)code); } public override LocalizableString GetDescription(int code) { return ErrorFacts.GetDescription((ErrorCode)code); } public override LocalizableString GetTitle(int code) { return ErrorFacts.GetTitle((ErrorCode)code); } public override string GetHelpLink(int code) { return ErrorFacts.GetHelpLink((ErrorCode)code); } public override string GetCategory(int code) { return ErrorFacts.GetCategory((ErrorCode)code); } public override string CodePrefix { get { return "CS"; } } // Given a message identifier (e.g., CS0219), severity, warning as error and a culture, // get the entire prefix (e.g., "error CS0219:" for C#) used on error messages. public override string GetMessagePrefix(string id, DiagnosticSeverity severity, bool isWarningAsError, CultureInfo culture) { return String.Format(culture, "{0} {1}", severity == DiagnosticSeverity.Error || isWarningAsError ? "error" : "warning", id); } public override int GetWarningLevel(int code) { return ErrorFacts.GetWarningLevel((ErrorCode)code); } public override Type ErrorCodeType { get { return typeof(ErrorCode); } } public override Diagnostic CreateDiagnostic(int code, Location location, params object[] args) { var info = new CSDiagnosticInfo((ErrorCode)code, args, ImmutableArray<Symbol>.Empty, ImmutableArray<Location>.Empty); return new CSDiagnostic(info, location); } public override Diagnostic CreateDiagnostic(DiagnosticInfo info) { return new CSDiagnostic(info, Location.None); } public override string GetErrorDisplayString(ISymbol symbol) { // show extra info for assembly if possible such as version, public key token etc. if (symbol.Kind == SymbolKind.Assembly || symbol.Kind == SymbolKind.Namespace) { return symbol.ToString(); } return SymbolDisplay.ToDisplayString(symbol, SymbolDisplayFormat.CSharpShortErrorMessageFormat); } public override ReportDiagnostic GetDiagnosticReport(DiagnosticInfo diagnosticInfo, CompilationOptions options) { bool hasPragmaSuppression; return CSharpDiagnosticFilter.GetDiagnosticReport(diagnosticInfo.Severity, true, diagnosticInfo.MessageIdentifier, diagnosticInfo.WarningLevel, Location.None, diagnosticInfo.Category, options.WarningLevel, ((CSharpCompilationOptions)options).NullableContextOptions, options.GeneralDiagnosticOption, options.SpecificDiagnosticOptions, options.SyntaxTreeOptionsProvider, CancellationToken.None, // We don't have a tree so there's no need to pass cancellation to the SyntaxTreeOptionsProvider out hasPragmaSuppression); } public override int ERR_FailedToCreateTempFile => (int)ErrorCode.ERR_CantMakeTempFile; public override int ERR_MultipleAnalyzerConfigsInSameDir => (int)ErrorCode.ERR_MultipleAnalyzerConfigsInSameDir; // command line: public override int ERR_ExpectedSingleScript => (int)ErrorCode.ERR_ExpectedSingleScript; public override int ERR_OpenResponseFile => (int)ErrorCode.ERR_OpenResponseFile; public override int ERR_InvalidPathMap => (int)ErrorCode.ERR_InvalidPathMap; public override int FTL_InvalidInputFileName => (int)ErrorCode.FTL_InvalidInputFileName; public override int ERR_FileNotFound => (int)ErrorCode.ERR_FileNotFound; public override int ERR_NoSourceFile => (int)ErrorCode.ERR_NoSourceFile; public override int ERR_CantOpenFileWrite => (int)ErrorCode.ERR_CantOpenFileWrite; public override int ERR_OutputWriteFailed => (int)ErrorCode.ERR_OutputWriteFailed; public override int WRN_NoConfigNotOnCommandLine => (int)ErrorCode.WRN_NoConfigNotOnCommandLine; public override int ERR_BinaryFile => (int)ErrorCode.ERR_BinaryFile; public override int WRN_AnalyzerCannotBeCreated => (int)ErrorCode.WRN_AnalyzerCannotBeCreated; public override int WRN_NoAnalyzerInAssembly => (int)ErrorCode.WRN_NoAnalyzerInAssembly; public override int WRN_UnableToLoadAnalyzer => (int)ErrorCode.WRN_UnableToLoadAnalyzer; public override int WRN_AnalyzerReferencesFramework => (int)ErrorCode.WRN_AnalyzerReferencesFramework; public override int INF_UnableToLoadSomeTypesInAnalyzer => (int)ErrorCode.INF_UnableToLoadSomeTypesInAnalyzer; public override int ERR_CantReadRulesetFile => (int)ErrorCode.ERR_CantReadRulesetFile; public override int ERR_CompileCancelled => (int)ErrorCode.ERR_CompileCancelled; // parse options: public override int ERR_BadSourceCodeKind => (int)ErrorCode.ERR_BadSourceCodeKind; public override int ERR_BadDocumentationMode => (int)ErrorCode.ERR_BadDocumentationMode; // compilation options: public override int ERR_BadCompilationOptionValue => (int)ErrorCode.ERR_BadCompilationOptionValue; public override int ERR_MutuallyExclusiveOptions => (int)ErrorCode.ERR_MutuallyExclusiveOptions; // emit options: public override int ERR_InvalidDebugInformationFormat => (int)ErrorCode.ERR_InvalidDebugInformationFormat; public override int ERR_InvalidOutputName => (int)ErrorCode.ERR_InvalidOutputName; public override int ERR_InvalidFileAlignment => (int)ErrorCode.ERR_InvalidFileAlignment; public override int ERR_InvalidSubsystemVersion => (int)ErrorCode.ERR_InvalidSubsystemVersion; public override int ERR_InvalidInstrumentationKind => (int)ErrorCode.ERR_InvalidInstrumentationKind; public override int ERR_InvalidHashAlgorithmName => (int)ErrorCode.ERR_InvalidHashAlgorithmName; // reference manager: public override int ERR_MetadataFileNotAssembly => (int)ErrorCode.ERR_ImportNonAssembly; public override int ERR_MetadataFileNotModule => (int)ErrorCode.ERR_AddModuleAssembly; public override int ERR_InvalidAssemblyMetadata => (int)ErrorCode.FTL_MetadataCantOpenFile; public override int ERR_InvalidModuleMetadata => (int)ErrorCode.FTL_MetadataCantOpenFile; public override int ERR_ErrorOpeningAssemblyFile => (int)ErrorCode.FTL_MetadataCantOpenFile; public override int ERR_ErrorOpeningModuleFile => (int)ErrorCode.FTL_MetadataCantOpenFile; public override int ERR_MetadataFileNotFound => (int)ErrorCode.ERR_NoMetadataFile; public override int ERR_MetadataReferencesNotSupported => (int)ErrorCode.ERR_MetadataReferencesNotSupported; public override int ERR_LinkedNetmoduleMetadataMustProvideFullPEImage => (int)ErrorCode.ERR_LinkedNetmoduleMetadataMustProvideFullPEImage; public override void ReportDuplicateMetadataReferenceStrong(DiagnosticBag diagnostics, Location location, MetadataReference reference, AssemblyIdentity identity, MetadataReference equivalentReference, AssemblyIdentity equivalentIdentity) { diagnostics.Add(ErrorCode.ERR_DuplicateImport, location, reference.Display ?? identity.GetDisplayName(), equivalentReference.Display ?? equivalentIdentity.GetDisplayName()); } public override void ReportDuplicateMetadataReferenceWeak(DiagnosticBag diagnostics, Location location, MetadataReference reference, AssemblyIdentity identity, MetadataReference equivalentReference, AssemblyIdentity equivalentIdentity) { diagnostics.Add(ErrorCode.ERR_DuplicateImportSimple, location, identity.Name, reference.Display ?? identity.GetDisplayName()); } // signing: public override int ERR_PublicKeyFileFailure => (int)ErrorCode.ERR_PublicKeyFileFailure; public override int ERR_PublicKeyContainerFailure => (int)ErrorCode.ERR_PublicKeyContainerFailure; public override int ERR_OptionMustBeAbsolutePath => (int)ErrorCode.ERR_OptionMustBeAbsolutePath; // resources: public override int ERR_CantReadResource => (int)ErrorCode.ERR_CantReadResource; public override int ERR_CantOpenWin32Resource => (int)ErrorCode.ERR_CantOpenWin32Res; public override int ERR_CantOpenWin32Manifest => (int)ErrorCode.ERR_CantOpenWin32Manifest; public override int ERR_CantOpenWin32Icon => (int)ErrorCode.ERR_CantOpenIcon; public override int ERR_ErrorBuildingWin32Resource => (int)ErrorCode.ERR_ErrorBuildingWin32Resources; public override int ERR_BadWin32Resource => (int)ErrorCode.ERR_BadWin32Res; public override int ERR_ResourceFileNameNotUnique => (int)ErrorCode.ERR_ResourceFileNameNotUnique; public override int ERR_ResourceNotUnique => (int)ErrorCode.ERR_ResourceNotUnique; public override int ERR_ResourceInModule => (int)ErrorCode.ERR_CantRefResource; // pseudo-custom attributes: public override int ERR_PermissionSetAttributeFileReadError => (int)ErrorCode.ERR_PermissionSetAttributeFileReadError; // PDB Writer: public override int ERR_EncodinglessSyntaxTree => (int)ErrorCode.ERR_EncodinglessSyntaxTree; public override int WRN_PdbUsingNameTooLong => (int)ErrorCode.WRN_DebugFullNameTooLong; public override int WRN_PdbLocalNameTooLong => (int)ErrorCode.WRN_PdbLocalNameTooLong; public override int ERR_PdbWritingFailed => (int)ErrorCode.FTL_DebugEmitFailure; // PE Writer: public override int ERR_MetadataNameTooLong => (int)ErrorCode.ERR_MetadataNameTooLong; public override int ERR_EncReferenceToAddedMember => (int)ErrorCode.ERR_EncReferenceToAddedMember; public override int ERR_TooManyUserStrings => (int)ErrorCode.ERR_TooManyUserStrings; public override int ERR_PeWritingFailure => (int)ErrorCode.ERR_PeWritingFailure; public override int ERR_ModuleEmitFailure => (int)ErrorCode.ERR_ModuleEmitFailure; public override int ERR_EncUpdateFailedMissingAttribute => (int)ErrorCode.ERR_EncUpdateFailedMissingAttribute; public override int ERR_InvalidDebugInfo => (int)ErrorCode.ERR_InvalidDebugInfo; // Generators: public override int WRN_GeneratorFailedDuringInitialization => (int)ErrorCode.WRN_GeneratorFailedDuringInitialization; public override int WRN_GeneratorFailedDuringGeneration => (int)ErrorCode.WRN_GeneratorFailedDuringGeneration; protected override void ReportInvalidAttributeArgument(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, AttributeData attribute) { var node = (AttributeSyntax)attributeSyntax; CSharpSyntaxNode attributeArgumentSyntax = attribute.GetAttributeArgumentSyntax(parameterIndex, node); diagnostics.Add(ErrorCode.ERR_InvalidAttributeArgument, attributeArgumentSyntax.Location, node.GetErrorDisplayName()); } protected override void ReportInvalidNamedArgument(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int namedArgumentIndex, ITypeSymbol attributeClass, string parameterName) { var node = (AttributeSyntax)attributeSyntax; diagnostics.Add(ErrorCode.ERR_InvalidNamedArgument, node.ArgumentList.Arguments[namedArgumentIndex].Location, parameterName); } protected override void ReportParameterNotValidForType(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int namedArgumentIndex) { var node = (AttributeSyntax)attributeSyntax; diagnostics.Add(ErrorCode.ERR_ParameterNotValidForType, node.ArgumentList.Arguments[namedArgumentIndex].Location); } protected override void ReportMarshalUnmanagedTypeNotValidForFields(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, string unmanagedTypeName, AttributeData attribute) { var node = (AttributeSyntax)attributeSyntax; CSharpSyntaxNode attributeArgumentSyntax = attribute.GetAttributeArgumentSyntax(parameterIndex, node); diagnostics.Add(ErrorCode.ERR_MarshalUnmanagedTypeNotValidForFields, attributeArgumentSyntax.Location, unmanagedTypeName); } protected override void ReportMarshalUnmanagedTypeOnlyValidForFields(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, int parameterIndex, string unmanagedTypeName, AttributeData attribute) { var node = (AttributeSyntax)attributeSyntax; CSharpSyntaxNode attributeArgumentSyntax = attribute.GetAttributeArgumentSyntax(parameterIndex, node); diagnostics.Add(ErrorCode.ERR_MarshalUnmanagedTypeOnlyValidForFields, attributeArgumentSyntax.Location, unmanagedTypeName); } protected override void ReportAttributeParameterRequired(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, string parameterName) { var node = (AttributeSyntax)attributeSyntax; diagnostics.Add(ErrorCode.ERR_AttributeParameterRequired1, node.Name.Location, parameterName); } protected override void ReportAttributeParameterRequired(DiagnosticBag diagnostics, SyntaxNode attributeSyntax, string parameterName1, string parameterName2) { var node = (AttributeSyntax)attributeSyntax; diagnostics.Add(ErrorCode.ERR_AttributeParameterRequired2, node.Name.Location, parameterName1, parameterName2); } public override int ERR_BadAssemblyName => (int)ErrorCode.ERR_BadAssemblyName; } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Features/VisualBasic/Portable/InvertIf/VisualBasicInvertIfCodeRefactoringProvider.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.InvertIf Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.InvertIf Friend MustInherit Class VisualBasicInvertIfCodeRefactoringProvider(Of TIfStatementSyntax As ExecutableStatementSyntax) Inherits AbstractInvertIfCodeRefactoringProvider(Of TIfStatementSyntax, StatementSyntax, SyntaxList(Of StatementSyntax)) Protected NotOverridable Overrides Function GetTitle() As String Return VBFeaturesResources.Invert_If End Function Protected NotOverridable Overrides Function GetIfBodyStatementRange(ifNode As TIfStatementSyntax) As StatementRange Dim statements = ifNode.GetStatements() Return If(statements.Count = 0, Nothing, New StatementRange(statements.First(), statements.Last())) End Function Protected NotOverridable Overrides Function CanControlFlowOut(node As SyntaxNode) As Boolean Return TypeOf node IsNot MethodBlockBaseSyntax AndAlso TypeOf node IsNot CaseBlockSyntax AndAlso TypeOf node IsNot DoLoopBlockSyntax AndAlso TypeOf node IsNot ForOrForEachBlockSyntax AndAlso TypeOf node IsNot LambdaExpressionSyntax AndAlso TypeOf node IsNot WhileBlockSyntax End Function Protected NotOverridable Overrides Function GetJumpStatementRawKind(node As SyntaxNode) As Integer If TypeOf node Is MethodBlockBaseSyntax OrElse TypeOf node Is LambdaExpressionSyntax Then Return SyntaxKind.ReturnStatement End If If TypeOf node Is CaseBlockSyntax Then Return SyntaxKind.ExitSelectStatement End If If TypeOf node Is DoLoopBlockSyntax Then Return SyntaxKind.ContinueDoStatement End If If TypeOf node Is ForOrForEachBlockSyntax Then Return SyntaxKind.ContinueForStatement End If If TypeOf node Is WhileBlockSyntax Then Return SyntaxKind.ContinueWhileStatement End If Return -1 End Function Protected NotOverridable Overrides Function IsStatementContainer(node As SyntaxNode) As Boolean Return node.IsStatementContainerNode() End Function Protected NotOverridable Overrides Function GetStatements(node As SyntaxNode) As SyntaxList(Of StatementSyntax) Return node.GetStatements() End Function Protected NotOverridable Overrides Function GetNextStatement(node As StatementSyntax) As StatementSyntax Dim parent = node.Parent Dim statements = parent.GetStatements Dim nextIndex = 1 + statements.IndexOf(node) If nextIndex < statements.Count Then Return statements(nextIndex) End If Return Nothing End Function Protected NotOverridable Overrides Function GetJumpStatement(rawKind As Integer) As StatementSyntax Select Case rawKind Case SyntaxKind.ReturnStatement Return SyntaxFactory.ReturnStatement Case SyntaxKind.ExitSelectStatement Return SyntaxFactory.ExitSelectStatement Case SyntaxKind.ContinueDoStatement Return SyntaxFactory.ContinueDoStatement Case SyntaxKind.ContinueForStatement Return SyntaxFactory.ContinueForStatement Case SyntaxKind.ContinueWhileStatement Return SyntaxFactory.ContinueWhileStatement Case Else Throw ExceptionUtilities.UnexpectedValue(rawKind) End Select End Function Protected NotOverridable Overrides Function IsNoOpSyntaxNode(node As SyntaxNode) As Boolean Return node.IsKind(SyntaxKind.EmptyStatement) End Function Protected NotOverridable Overrides Function IsExecutableStatement(node As SyntaxNode) As Boolean Return TypeOf node Is ExecutableStatementSyntax End Function Protected NotOverridable Overrides Function UnwrapBlock(ifBody As SyntaxList(Of StatementSyntax)) As IEnumerable(Of StatementSyntax) Return ifBody End Function Protected NotOverridable Overrides Function GetEmptyEmbeddedStatement() As SyntaxList(Of StatementSyntax) Return SyntaxFactory.List(Of StatementSyntax) End Function Protected NotOverridable Overrides Function AsEmbeddedStatement(statements As IEnumerable(Of StatementSyntax), original As SyntaxList(Of StatementSyntax)) As SyntaxList(Of StatementSyntax) Return SyntaxFactory.List(statements) End Function Protected NotOverridable Overrides Function WithStatements(node As SyntaxNode, statements As IEnumerable(Of StatementSyntax)) As SyntaxNode Return node.ReplaceStatements(SyntaxFactory.List(statements)) End Function Protected NotOverridable Overrides Function IsSingleStatementStatementRange(statementRange As StatementRange) As Boolean Return Not statementRange.IsEmpty AndAlso statementRange.FirstStatement Is statementRange.LastStatement 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.InvertIf Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.InvertIf Friend MustInherit Class VisualBasicInvertIfCodeRefactoringProvider(Of TIfStatementSyntax As ExecutableStatementSyntax) Inherits AbstractInvertIfCodeRefactoringProvider(Of TIfStatementSyntax, StatementSyntax, SyntaxList(Of StatementSyntax)) Protected NotOverridable Overrides Function GetTitle() As String Return VBFeaturesResources.Invert_If End Function Protected NotOverridable Overrides Function GetIfBodyStatementRange(ifNode As TIfStatementSyntax) As StatementRange Dim statements = ifNode.GetStatements() Return If(statements.Count = 0, Nothing, New StatementRange(statements.First(), statements.Last())) End Function Protected NotOverridable Overrides Function CanControlFlowOut(node As SyntaxNode) As Boolean Return TypeOf node IsNot MethodBlockBaseSyntax AndAlso TypeOf node IsNot CaseBlockSyntax AndAlso TypeOf node IsNot DoLoopBlockSyntax AndAlso TypeOf node IsNot ForOrForEachBlockSyntax AndAlso TypeOf node IsNot LambdaExpressionSyntax AndAlso TypeOf node IsNot WhileBlockSyntax End Function Protected NotOverridable Overrides Function GetJumpStatementRawKind(node As SyntaxNode) As Integer If TypeOf node Is MethodBlockBaseSyntax OrElse TypeOf node Is LambdaExpressionSyntax Then Return SyntaxKind.ReturnStatement End If If TypeOf node Is CaseBlockSyntax Then Return SyntaxKind.ExitSelectStatement End If If TypeOf node Is DoLoopBlockSyntax Then Return SyntaxKind.ContinueDoStatement End If If TypeOf node Is ForOrForEachBlockSyntax Then Return SyntaxKind.ContinueForStatement End If If TypeOf node Is WhileBlockSyntax Then Return SyntaxKind.ContinueWhileStatement End If Return -1 End Function Protected NotOverridable Overrides Function IsStatementContainer(node As SyntaxNode) As Boolean Return node.IsStatementContainerNode() End Function Protected NotOverridable Overrides Function GetStatements(node As SyntaxNode) As SyntaxList(Of StatementSyntax) Return node.GetStatements() End Function Protected NotOverridable Overrides Function GetNextStatement(node As StatementSyntax) As StatementSyntax Dim parent = node.Parent Dim statements = parent.GetStatements Dim nextIndex = 1 + statements.IndexOf(node) If nextIndex < statements.Count Then Return statements(nextIndex) End If Return Nothing End Function Protected NotOverridable Overrides Function GetJumpStatement(rawKind As Integer) As StatementSyntax Select Case rawKind Case SyntaxKind.ReturnStatement Return SyntaxFactory.ReturnStatement Case SyntaxKind.ExitSelectStatement Return SyntaxFactory.ExitSelectStatement Case SyntaxKind.ContinueDoStatement Return SyntaxFactory.ContinueDoStatement Case SyntaxKind.ContinueForStatement Return SyntaxFactory.ContinueForStatement Case SyntaxKind.ContinueWhileStatement Return SyntaxFactory.ContinueWhileStatement Case Else Throw ExceptionUtilities.UnexpectedValue(rawKind) End Select End Function Protected NotOverridable Overrides Function IsNoOpSyntaxNode(node As SyntaxNode) As Boolean Return node.IsKind(SyntaxKind.EmptyStatement) End Function Protected NotOverridable Overrides Function IsExecutableStatement(node As SyntaxNode) As Boolean Return TypeOf node Is ExecutableStatementSyntax End Function Protected NotOverridable Overrides Function UnwrapBlock(ifBody As SyntaxList(Of StatementSyntax)) As IEnumerable(Of StatementSyntax) Return ifBody End Function Protected NotOverridable Overrides Function GetEmptyEmbeddedStatement() As SyntaxList(Of StatementSyntax) Return SyntaxFactory.List(Of StatementSyntax) End Function Protected NotOverridable Overrides Function AsEmbeddedStatement(statements As IEnumerable(Of StatementSyntax), original As SyntaxList(Of StatementSyntax)) As SyntaxList(Of StatementSyntax) Return SyntaxFactory.List(statements) End Function Protected NotOverridable Overrides Function WithStatements(node As SyntaxNode, statements As IEnumerable(Of StatementSyntax)) As SyntaxNode Return node.ReplaceStatements(SyntaxFactory.List(statements)) End Function Protected NotOverridable Overrides Function IsSingleStatementStatementRange(statementRange As StatementRange) As Boolean Return Not statementRange.IsEmpty AndAlso statementRange.FirstStatement Is statementRange.LastStatement End Function End Class End Namespace
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/CSharp/Interactive/CSharpSendToInteractiveSubmissionProvider.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.ComponentModel.Composition; using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.Interactive; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.CSharp.Interactive { [Export(typeof(ISendToInteractiveSubmissionProvider))] internal sealed class CSharpSendToInteractiveSubmissionProvider : AbstractSendToInteractiveSubmissionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpSendToInteractiveSubmissionProvider() { } protected override bool CanParseSubmission(string code) { var options = CSharpInteractiveEvaluatorLanguageInfoProvider.Instance.ParseOptions; var tree = SyntaxFactory.ParseSyntaxTree(code, options); return tree.HasCompilationUnitRoot && !tree.GetDiagnostics().Any(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error); } protected override IEnumerable<TextSpan> GetExecutableSyntaxTreeNodeSelection(TextSpan selectionSpan, SyntaxNode root) { var expandedNode = GetSyntaxNodeForSubmission(selectionSpan, root); return expandedNode != null ? new TextSpan[] { expandedNode.Span } : Array.Empty<TextSpan>(); } /// <summary> /// Finds a <see cref="SyntaxNode"/> that should be submitted to REPL. /// </summary> /// <param name="selectionSpan">Selection that user has originally made.</param> /// <param name="root">Root of the syntax tree.</param> private static SyntaxNode GetSyntaxNodeForSubmission(TextSpan selectionSpan, SyntaxNode root) { GetSelectedTokens(selectionSpan, root, out var startToken, out var endToken); // Ensure that the first token comes before the last token. // Otherwise selection did not contain any tokens. if (startToken != endToken && startToken.Span.End > endToken.SpanStart) { return null; } if (startToken == endToken) { return GetSyntaxNodeForSubmission(startToken.Parent); } var startNode = GetSyntaxNodeForSubmission(startToken.Parent); var endNode = GetSyntaxNodeForSubmission(endToken.Parent); // If there is no SyntaxNode worth sending to the REPL return null. if (startNode == null || endNode == null) { return null; } // If one of the nodes is an ancestor of another node return that node. if (startNode.Span.Contains(endNode.Span)) { return startNode; } else if (endNode.Span.Contains(startNode.Span)) { return endNode; } // Selection spans multiple statements. // In this case find common parent and find a span of statements within that parent. return GetSyntaxNodeForSubmission(startNode.GetCommonRoot(endNode)); } /// <summary> /// Finds a <see cref="SyntaxNode"/> that should be submitted to REPL. /// </summary> /// <param name="node">The currently selected node.</param> private static SyntaxNode GetSyntaxNodeForSubmission(SyntaxNode node) { SyntaxNode candidate = node.GetAncestorOrThis<StatementSyntax>(); if (candidate != null) { return candidate; } candidate = node.GetAncestorsOrThis<SyntaxNode>() .Where(IsSubmissionNode).FirstOrDefault(); if (candidate != null) { return candidate; } return null; } /// <summary>Returns <c>true</c> if <c>node</c> could be treated as a REPL submission.</summary> private static bool IsSubmissionNode(SyntaxNode node) { var kind = node.Kind(); return SyntaxFacts.IsTypeDeclaration(kind) || SyntaxFacts.IsGlobalMemberDeclaration(kind) || node.IsKind(SyntaxKind.UsingDirective); } private static void GetSelectedTokens( TextSpan selectionSpan, SyntaxNode root, out SyntaxToken startToken, out SyntaxToken endToken) { endToken = root.FindTokenOnLeftOfPosition(selectionSpan.End); startToken = selectionSpan.Length == 0 ? endToken : root.FindTokenOnRightOfPosition(selectionSpan.Start); } } }
// Licensed to the .NET Foundation under one or more 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.ComponentModel.Composition; using System.Linq; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.Interactive; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.CSharp.Interactive { [Export(typeof(ISendToInteractiveSubmissionProvider))] internal sealed class CSharpSendToInteractiveSubmissionProvider : AbstractSendToInteractiveSubmissionProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpSendToInteractiveSubmissionProvider() { } protected override bool CanParseSubmission(string code) { var options = CSharpInteractiveEvaluatorLanguageInfoProvider.Instance.ParseOptions; var tree = SyntaxFactory.ParseSyntaxTree(code, options); return tree.HasCompilationUnitRoot && !tree.GetDiagnostics().Any(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error); } protected override IEnumerable<TextSpan> GetExecutableSyntaxTreeNodeSelection(TextSpan selectionSpan, SyntaxNode root) { var expandedNode = GetSyntaxNodeForSubmission(selectionSpan, root); return expandedNode != null ? new TextSpan[] { expandedNode.Span } : Array.Empty<TextSpan>(); } /// <summary> /// Finds a <see cref="SyntaxNode"/> that should be submitted to REPL. /// </summary> /// <param name="selectionSpan">Selection that user has originally made.</param> /// <param name="root">Root of the syntax tree.</param> private static SyntaxNode GetSyntaxNodeForSubmission(TextSpan selectionSpan, SyntaxNode root) { GetSelectedTokens(selectionSpan, root, out var startToken, out var endToken); // Ensure that the first token comes before the last token. // Otherwise selection did not contain any tokens. if (startToken != endToken && startToken.Span.End > endToken.SpanStart) { return null; } if (startToken == endToken) { return GetSyntaxNodeForSubmission(startToken.Parent); } var startNode = GetSyntaxNodeForSubmission(startToken.Parent); var endNode = GetSyntaxNodeForSubmission(endToken.Parent); // If there is no SyntaxNode worth sending to the REPL return null. if (startNode == null || endNode == null) { return null; } // If one of the nodes is an ancestor of another node return that node. if (startNode.Span.Contains(endNode.Span)) { return startNode; } else if (endNode.Span.Contains(startNode.Span)) { return endNode; } // Selection spans multiple statements. // In this case find common parent and find a span of statements within that parent. return GetSyntaxNodeForSubmission(startNode.GetCommonRoot(endNode)); } /// <summary> /// Finds a <see cref="SyntaxNode"/> that should be submitted to REPL. /// </summary> /// <param name="node">The currently selected node.</param> private static SyntaxNode GetSyntaxNodeForSubmission(SyntaxNode node) { SyntaxNode candidate = node.GetAncestorOrThis<StatementSyntax>(); if (candidate != null) { return candidate; } candidate = node.GetAncestorsOrThis<SyntaxNode>() .Where(IsSubmissionNode).FirstOrDefault(); if (candidate != null) { return candidate; } return null; } /// <summary>Returns <c>true</c> if <c>node</c> could be treated as a REPL submission.</summary> private static bool IsSubmissionNode(SyntaxNode node) { var kind = node.Kind(); return SyntaxFacts.IsTypeDeclaration(kind) || SyntaxFacts.IsGlobalMemberDeclaration(kind) || node.IsKind(SyntaxKind.UsingDirective); } private static void GetSelectedTokens( TextSpan selectionSpan, SyntaxNode root, out SyntaxToken startToken, out SyntaxToken endToken) { endToken = root.FindTokenOnLeftOfPosition(selectionSpan.End); startToken = selectionSpan.Length == 0 ? endToken : root.FindTokenOnRightOfPosition(selectionSpan.Start); } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Rules/NextSuppressOperationAction.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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting.Rules { [NonDefaultable] internal readonly struct NextSuppressOperationAction { private readonly ImmutableArray<AbstractFormattingRule> _formattingRules; private readonly int _index; private readonly SyntaxNode _node; private readonly List<SuppressOperation> _list; public NextSuppressOperationAction( ImmutableArray<AbstractFormattingRule> formattingRules, int index, SyntaxNode node, List<SuppressOperation> list) { _formattingRules = formattingRules; _index = index; _node = node; _list = list; } private NextSuppressOperationAction NextAction => new(_formattingRules, _index + 1, _node, _list); public void Invoke() { // If we have no remaining handlers to execute, then we'll execute our last handler if (_index >= _formattingRules.Length) { return; } else { // Call the handler at the index, passing a continuation that will come back to here with index + 1 _formattingRules[_index].AddSuppressOperations(_list, _node, NextAction); return; } } } }
// Licensed to the .NET Foundation under one or more 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Formatting.Rules { [NonDefaultable] internal readonly struct NextSuppressOperationAction { private readonly ImmutableArray<AbstractFormattingRule> _formattingRules; private readonly int _index; private readonly SyntaxNode _node; private readonly List<SuppressOperation> _list; public NextSuppressOperationAction( ImmutableArray<AbstractFormattingRule> formattingRules, int index, SyntaxNode node, List<SuppressOperation> list) { _formattingRules = formattingRules; _index = index; _node = node; _list = list; } private NextSuppressOperationAction NextAction => new(_formattingRules, _index + 1, _node, _list); public void Invoke() { // If we have no remaining handlers to execute, then we'll execute our last handler if (_index >= _formattingRules.Length) { return; } else { // Call the handler at the index, passing a continuation that will come back to here with index + 1 _formattingRules[_index].AddSuppressOperations(_list, _node, NextAction); return; } } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Features/CSharp/Portable/ConvertNamespace/ConvertNamespaceCodeRefactoringProvider.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; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ConvertNamespace { using static ConvertNamespaceAnalysis; using static ConvertNamespaceTransform; [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertNamespace), Shared] internal class ConvertNamespaceCodeRefactoringProvider : CodeRefactoringProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ConvertNamespaceCodeRefactoringProvider() { } public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, span, cancellationToken) = context; if (!span.IsEmpty) return; var position = span.Start; var root = (CompilationUnitSyntax)await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(position); var namespaceDecl = token.GetAncestor<BaseNamespaceDeclarationSyntax>(); if (namespaceDecl == null) return; if (!IsValidPosition(namespaceDecl, position)) return; var optionSet = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var info = CanOfferUseBlockScoped(optionSet, namespaceDecl, forAnalyzer: false) ? GetInfo(NamespaceDeclarationPreference.BlockScoped) : CanOfferUseFileScoped(optionSet, root, namespaceDecl, forAnalyzer: false) ? GetInfo(NamespaceDeclarationPreference.FileScoped) : ((string title, string equivalenceKey)?)null; if (info == null) return; context.RegisterRefactoring(new MyCodeAction( info.Value.title, c => ConvertAsync(document, namespaceDecl, c), info.Value.equivalenceKey)); } private static bool IsValidPosition(BaseNamespaceDeclarationSyntax baseDeclaration, int position) { if (position < baseDeclaration.SpanStart) return false; if (baseDeclaration is FileScopedNamespaceDeclarationSyntax fileScopedNamespace) return position <= fileScopedNamespace.SemicolonToken.Span.End; if (baseDeclaration is NamespaceDeclarationSyntax namespaceDeclaration) return position <= namespaceDeclaration.Name.Span.End; throw ExceptionUtilities.UnexpectedValue(baseDeclaration.Kind()); } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument, string equivalenceKey) : base(title, createChangedDocument, equivalenceKey) { } } } }
// Licensed to the .NET Foundation under one or more 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; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ConvertNamespace { using static ConvertNamespaceAnalysis; using static ConvertNamespaceTransform; [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertNamespace), Shared] internal class ConvertNamespaceCodeRefactoringProvider : CodeRefactoringProvider { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public ConvertNamespaceCodeRefactoringProvider() { } public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var (document, span, cancellationToken) = context; if (!span.IsEmpty) return; var position = span.Start; var root = (CompilationUnitSyntax)await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(position); var namespaceDecl = token.GetAncestor<BaseNamespaceDeclarationSyntax>(); if (namespaceDecl == null) return; if (!IsValidPosition(namespaceDecl, position)) return; var optionSet = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false); var info = CanOfferUseBlockScoped(optionSet, namespaceDecl, forAnalyzer: false) ? GetInfo(NamespaceDeclarationPreference.BlockScoped) : CanOfferUseFileScoped(optionSet, root, namespaceDecl, forAnalyzer: false) ? GetInfo(NamespaceDeclarationPreference.FileScoped) : ((string title, string equivalenceKey)?)null; if (info == null) return; context.RegisterRefactoring(new MyCodeAction( info.Value.title, c => ConvertAsync(document, namespaceDecl, c), info.Value.equivalenceKey)); } private static bool IsValidPosition(BaseNamespaceDeclarationSyntax baseDeclaration, int position) { if (position < baseDeclaration.SpanStart) return false; if (baseDeclaration is FileScopedNamespaceDeclarationSyntax fileScopedNamespace) return position <= fileScopedNamespace.SemicolonToken.Span.End; if (baseDeclaration is NamespaceDeclarationSyntax namespaceDeclaration) return position <= namespaceDeclaration.Name.Span.End; throw ExceptionUtilities.UnexpectedValue(baseDeclaration.Kind()); } private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument, string equivalenceKey) : base(title, createChangedDocument, equivalenceKey) { } } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/Compilers/VisualBasic/Portable/Emit/NoPia/EmbeddedTypeParameter.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.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols #If Not DEBUG Then Imports TypeParameterSymbolAdapter = Microsoft.CodeAnalysis.VisualBasic.Symbols.TypeParameterSymbol #End If Namespace Microsoft.CodeAnalysis.VisualBasic.Emit.NoPia Friend NotInheritable Class EmbeddedTypeParameter Inherits EmbeddedTypesManager.CommonEmbeddedTypeParameter Public Sub New(containingMethod As EmbeddedMethod, underlyingTypeParameter As TypeParameterSymbolAdapter) MyBase.New(containingMethod, underlyingTypeParameter) Debug.Assert(underlyingTypeParameter.AdaptedTypeParameterSymbol.IsDefinition) End Sub Protected Overrides Function GetConstraints(context As EmitContext) As IEnumerable(Of Cci.TypeReferenceWithAttributes) Return DirectCast(UnderlyingTypeParameter, Cci.IGenericParameter).GetConstraints(context) End Function Protected Overrides ReadOnly Property MustBeReferenceType As Boolean Get Return UnderlyingTypeParameter.AdaptedTypeParameterSymbol.HasReferenceTypeConstraint End Get End Property Protected Overrides ReadOnly Property MustBeValueType As Boolean Get Return UnderlyingTypeParameter.AdaptedTypeParameterSymbol.HasValueTypeConstraint End Get End Property Protected Overrides ReadOnly Property MustHaveDefaultConstructor As Boolean Get Return UnderlyingTypeParameter.AdaptedTypeParameterSymbol.HasConstructorConstraint End Get End Property Protected Overrides ReadOnly Property Name As String Get Return UnderlyingTypeParameter.AdaptedTypeParameterSymbol.MetadataName End Get End Property Protected Overrides ReadOnly Property Index As UShort Get Return CUShort(UnderlyingTypeParameter.AdaptedTypeParameterSymbol.Ordinal) End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols #If Not DEBUG Then Imports TypeParameterSymbolAdapter = Microsoft.CodeAnalysis.VisualBasic.Symbols.TypeParameterSymbol #End If Namespace Microsoft.CodeAnalysis.VisualBasic.Emit.NoPia Friend NotInheritable Class EmbeddedTypeParameter Inherits EmbeddedTypesManager.CommonEmbeddedTypeParameter Public Sub New(containingMethod As EmbeddedMethod, underlyingTypeParameter As TypeParameterSymbolAdapter) MyBase.New(containingMethod, underlyingTypeParameter) Debug.Assert(underlyingTypeParameter.AdaptedTypeParameterSymbol.IsDefinition) End Sub Protected Overrides Function GetConstraints(context As EmitContext) As IEnumerable(Of Cci.TypeReferenceWithAttributes) Return DirectCast(UnderlyingTypeParameter, Cci.IGenericParameter).GetConstraints(context) End Function Protected Overrides ReadOnly Property MustBeReferenceType As Boolean Get Return UnderlyingTypeParameter.AdaptedTypeParameterSymbol.HasReferenceTypeConstraint End Get End Property Protected Overrides ReadOnly Property MustBeValueType As Boolean Get Return UnderlyingTypeParameter.AdaptedTypeParameterSymbol.HasValueTypeConstraint End Get End Property Protected Overrides ReadOnly Property MustHaveDefaultConstructor As Boolean Get Return UnderlyingTypeParameter.AdaptedTypeParameterSymbol.HasConstructorConstraint End Get End Property Protected Overrides ReadOnly Property Name As String Get Return UnderlyingTypeParameter.AdaptedTypeParameterSymbol.MetadataName End Get End Property Protected Overrides ReadOnly Property Index As UShort Get Return CUShort(UnderlyingTypeParameter.AdaptedTypeParameterSymbol.Ordinal) End Get End Property End Class End Namespace
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicNavigateTo.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; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicNavigateTo : AbstractEditorTest { protected override string LanguageName => LanguageNames.VisualBasic; public BasicNavigateTo(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(BasicNavigateTo)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public void NavigateTo() { var project = new ProjectUtils.Project(ProjectName); var csProject = new ProjectUtils.Project("CSProject"); VisualStudio.SolutionExplorer.AddFile(project, "test1.vb", open: false, contents: @" Class FirstClass Sub FirstMethod() End Sub End Class"); VisualStudio.SolutionExplorer.AddFile(project, "test2.vb", open: true, contents: @" "); VisualStudio.Editor.InvokeNavigateTo("FirstMethod", VirtualKey.Enter); VisualStudio.Editor.WaitForActiveView("test1.vb"); Assert.Equal("FirstMethod", VisualStudio.Editor.GetSelectedText()); // Verify C# files are found when navigating from VB VisualStudio.SolutionExplorer.AddProject(csProject, WellKnownProjectTemplates.ClassLibrary, LanguageNames.CSharp); VisualStudio.SolutionExplorer.AddFile(csProject, "csfile.cs", open: true); VisualStudio.Editor.InvokeNavigateTo("FirstClass", VirtualKey.Enter); VisualStudio.Editor.WaitForActiveView("test1.vb"); Assert.Equal("FirstClass", VisualStudio.Editor.GetSelectedText()); } } }
// Licensed to the .NET Foundation under one or more 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; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Input; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; using ProjectUtils = Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicNavigateTo : AbstractEditorTest { protected override string LanguageName => LanguageNames.VisualBasic; public BasicNavigateTo(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(BasicNavigateTo)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.NavigateTo)] public void NavigateTo() { var project = new ProjectUtils.Project(ProjectName); var csProject = new ProjectUtils.Project("CSProject"); VisualStudio.SolutionExplorer.AddFile(project, "test1.vb", open: false, contents: @" Class FirstClass Sub FirstMethod() End Sub End Class"); VisualStudio.SolutionExplorer.AddFile(project, "test2.vb", open: true, contents: @" "); VisualStudio.Editor.InvokeNavigateTo("FirstMethod", VirtualKey.Enter); VisualStudio.Editor.WaitForActiveView("test1.vb"); Assert.Equal("FirstMethod", VisualStudio.Editor.GetSelectedText()); // Verify C# files are found when navigating from VB VisualStudio.SolutionExplorer.AddProject(csProject, WellKnownProjectTemplates.ClassLibrary, LanguageNames.CSharp); VisualStudio.SolutionExplorer.AddFile(csProject, "csfile.cs", open: true); VisualStudio.Editor.InvokeNavigateTo("FirstClass", VirtualKey.Enter); VisualStudio.Editor.WaitForActiveView("test1.vb"); Assert.Equal("FirstClass", VisualStudio.Editor.GetSelectedText()); } } }
-1
dotnet/roslyn
55,132
Support lambda expressions and method groups as `var` initializers
```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
cston
2021-07-27T03:12:21Z
2021-07-27T18:26:42Z
61a565cfcd777158cb6354351436aff997ad7bf6
5840335153dcca42570a853cdacd06d660fe9596
Support lambda expressions and method groups as `var` initializers. ```csharp var d1 = Program.Main; var d2 = () => { }; ``` Proposal: [lambda-improvements.md](https://github.com/dotnet/csharplang/blob/main/proposals/csharp-10.0/lambda-improvements.md) Test plan: https://github.com/dotnet/roslyn/issues/52192
./src/EditorFeatures/Core/Shared/Tagging/EventSources/TaggerEventSources.DiagnosticsChangedEventSource.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.Diagnostics; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging { internal partial class TaggerEventSources { private class DiagnosticsChangedEventSource : AbstractTaggerEventSource { private readonly ITextBuffer _subjectBuffer; private readonly IDiagnosticService _service; public DiagnosticsChangedEventSource(ITextBuffer subjectBuffer, IDiagnosticService service) { _subjectBuffer = subjectBuffer; _service = service; } private void OnDiagnosticsUpdated(object? sender, DiagnosticsUpdatedArgs e) { var document = _subjectBuffer.AsTextContainer().GetOpenDocumentInCurrentContext(); if (document != null && document.Project.Solution.Workspace == e.Workspace && document.Id == e.DocumentId) { this.RaiseChanged(); } } public override void Connect() => _service.DiagnosticsUpdated += OnDiagnosticsUpdated; public override void Disconnect() => _service.DiagnosticsUpdated -= OnDiagnosticsUpdated; } } }
// Licensed to the .NET Foundation under one or more 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.Diagnostics; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging { internal partial class TaggerEventSources { private class DiagnosticsChangedEventSource : AbstractTaggerEventSource { private readonly ITextBuffer _subjectBuffer; private readonly IDiagnosticService _service; public DiagnosticsChangedEventSource(ITextBuffer subjectBuffer, IDiagnosticService service) { _subjectBuffer = subjectBuffer; _service = service; } private void OnDiagnosticsUpdated(object? sender, DiagnosticsUpdatedArgs e) { var document = _subjectBuffer.AsTextContainer().GetOpenDocumentInCurrentContext(); if (document != null && document.Project.Solution.Workspace == e.Workspace && document.Id == e.DocumentId) { this.RaiseChanged(); } } public override void Connect() => _service.DiagnosticsUpdated += OnDiagnosticsUpdated; public override void Disconnect() => _service.DiagnosticsUpdated -= OnDiagnosticsUpdated; } } }
-1
dotnet/roslyn
55,125
Don't use DefaultInterpolatedStringHandler in expression trees
Introduces a binder flag to track whether we are currently in an expression tree or not. Fixes https://github.com/dotnet/roslyn/issues/55114.
333fred
2021-07-26T22:08:39Z
2021-07-27T19:33:24Z
5840335153dcca42570a853cdacd06d660fe9596
cfc12ce93ce377c4b9581ccf88403e6740d63977
Don't use DefaultInterpolatedStringHandler in expression trees. Introduces a binder flag to track whether we are currently in an expression tree or not. Fixes https://github.com/dotnet/roslyn/issues/55114.
./src/Compilers/CSharp/Portable/Binder/Binder.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.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// A Binder converts names in to symbols and syntax nodes into bound trees. It is context /// dependent, relative to a location in source code. /// </summary> internal partial class Binder { internal CSharpCompilation Compilation { get; } internal readonly BinderFlags Flags; /// <summary> /// Used to create a root binder. /// </summary> internal Binder(CSharpCompilation compilation) { RoslynDebug.Assert(compilation != null); RoslynDebug.Assert(this is BuckStopsHereBinder); this.Flags = compilation.Options.TopLevelBinderFlags; this.Compilation = compilation; } internal Binder(Binder next, Conversions? conversions = null) { RoslynDebug.Assert(next != null); Next = next; this.Flags = next.Flags; this.Compilation = next.Compilation; _lazyConversions = conversions; } protected Binder(Binder next, BinderFlags flags) { RoslynDebug.Assert(next != null); // Mutually exclusive. RoslynDebug.Assert(!flags.Includes(BinderFlags.UncheckedRegion | BinderFlags.CheckedRegion)); // Implied. RoslynDebug.Assert(!flags.Includes(BinderFlags.InNestedFinallyBlock) || flags.Includes(BinderFlags.InFinallyBlock | BinderFlags.InCatchBlock)); Next = next; this.Flags = flags; this.Compilation = next.Compilation; } internal bool IsSemanticModelBinder { get { return this.Flags.Includes(BinderFlags.SemanticModel); } } // IsEarlyAttributeBinder is called relatively frequently so we want fast code here. internal bool IsEarlyAttributeBinder { get { return this.Flags.Includes(BinderFlags.EarlyAttributeBinding); } } // Return the nearest enclosing node being bound as a nameof(...) argument, if any, or null if none. protected virtual SyntaxNode? EnclosingNameofArgument => null; private bool IsInsideNameof => this.EnclosingNameofArgument != null; /// <summary> /// Get the next binder in which to look up a name, if not found by this binder. /// </summary> protected internal Binder? Next { get; } /// <summary> /// Get the next binder in which to look up a name, if not found by this binder, asserting if `Next` is null. /// </summary> protected internal Binder NextRequired { get { Debug.Assert(Next is not null); return Next; } } /// <summary> /// <see cref="OverflowChecks.Enabled"/> if we are in an explicitly checked context (within checked block or expression). /// <see cref="OverflowChecks.Disabled"/> if we are in an explicitly unchecked context (within unchecked block or expression). /// <see cref="OverflowChecks.Implicit"/> otherwise. /// </summary> protected OverflowChecks CheckOverflow { get { // Although C# 4.0 specification says that checked context never flows in a lambda, // the Dev10 compiler implementation always flows the context in, except for // when the lambda is directly a "parameter" of the checked/unchecked expression. // For Roslyn we decided to change the spec and always flow the context in. // So we don't stop at lambda binder. RoslynDebug.Assert(!this.Flags.Includes(BinderFlags.UncheckedRegion | BinderFlags.CheckedRegion)); return this.Flags.Includes(BinderFlags.CheckedRegion) ? OverflowChecks.Enabled : this.Flags.Includes(BinderFlags.UncheckedRegion) ? OverflowChecks.Disabled : OverflowChecks.Implicit; } } /// <summary> /// True if instructions that check overflow should be generated. /// </summary> /// <remarks> /// Spec 7.5.12: /// For non-constant expressions (expressions that are evaluated at run-time) that are not /// enclosed by any checked or unchecked operators or statements, the default overflow checking /// context is unchecked unless external factors (such as compiler switches and execution /// environment configuration) call for checked evaluation. /// </remarks> protected bool CheckOverflowAtRuntime { get { var result = CheckOverflow; return result == OverflowChecks.Enabled || result == OverflowChecks.Implicit && Compilation.Options.CheckOverflow; } } /// <summary> /// True if the compiler should check for overflow while evaluating constant expressions. /// </summary> /// <remarks> /// Spec 7.5.12: /// For constant expressions (expressions that can be fully evaluated at compile-time), /// the default overflow checking context is always checked. Unless a constant expression /// is explicitly placed in an unchecked context, overflows that occur during the compile-time /// evaluation of the expression always cause compile-time errors. /// </remarks> internal bool CheckOverflowAtCompileTime { get { return CheckOverflow != OverflowChecks.Disabled; } } /// <summary> /// Some nodes have special binders for their contents (like Blocks) /// </summary> internal virtual Binder? GetBinder(SyntaxNode node) { RoslynDebug.Assert(Next is object); return this.Next.GetBinder(node); } /// <summary> /// Gets a binder for a node that must be not null, and asserts /// if it is not. /// </summary> internal Binder GetRequiredBinder(SyntaxNode node) { var binder = GetBinder(node); RoslynDebug.Assert(binder is object); return binder; } /// <summary> /// Get locals declared immediately in scope designated by the node. /// </summary> internal virtual ImmutableArray<LocalSymbol> GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) { RoslynDebug.Assert(Next is object); return this.Next.GetDeclaredLocalsForScope(scopeDesignator); } /// <summary> /// Get local functions declared immediately in scope designated by the node. /// </summary> internal virtual ImmutableArray<LocalFunctionSymbol> GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) { RoslynDebug.Assert(Next is object); return this.Next.GetDeclaredLocalFunctionsForScope(scopeDesignator); } /// <summary> /// If this binder owns a scope for locals, return syntax node that is used /// as the scope designator. Otherwise, null. /// </summary> internal virtual SyntaxNode? ScopeDesignator { get { return null; } } internal virtual bool IsLocalFunctionsScopeBinder { get { return false; } } internal virtual bool IsLabelsScopeBinder { get { return false; } } /// <summary> /// True if this is the top-level binder for a local function or lambda /// (including implicit lambdas from query expressions). /// </summary> internal virtual bool IsNestedFunctionBinder => false; /// <summary> /// The member containing the binding context. Note that for the purposes of the compiler, /// a lambda expression is considered a "member" of its enclosing method, field, or lambda. /// </summary> internal virtual Symbol? ContainingMemberOrLambda { get { RoslynDebug.Assert(Next is object); return Next.ContainingMemberOrLambda; } } /// <summary> /// Are we in a context where un-annotated types should be interpreted as non-null? /// </summary> internal bool AreNullableAnnotationsEnabled(SyntaxTree syntaxTree, int position) { CSharpSyntaxTree csTree = (CSharpSyntaxTree)syntaxTree; Syntax.NullableContextState context = csTree.GetNullableContextState(position); return context.AnnotationsState switch { Syntax.NullableContextState.State.Enabled => true, Syntax.NullableContextState.State.Disabled => false, Syntax.NullableContextState.State.ExplicitlyRestored => GetGlobalAnnotationState(), Syntax.NullableContextState.State.Unknown => !csTree.IsGeneratedCode(this.Compilation.Options.SyntaxTreeOptionsProvider, CancellationToken.None) && AreNullableAnnotationsGloballyEnabled(), _ => throw ExceptionUtilities.UnexpectedValue(context.AnnotationsState) }; } internal bool AreNullableAnnotationsEnabled(SyntaxToken token) { RoslynDebug.Assert(token.SyntaxTree is object); return AreNullableAnnotationsEnabled(token.SyntaxTree, token.SpanStart); } internal bool IsGeneratedCode(SyntaxToken token) { var tree = (CSharpSyntaxTree)token.SyntaxTree!; return tree.IsGeneratedCode(Compilation.Options.SyntaxTreeOptionsProvider, CancellationToken.None); } internal virtual bool AreNullableAnnotationsGloballyEnabled() { RoslynDebug.Assert(Next is object); return Next.AreNullableAnnotationsGloballyEnabled(); } protected bool GetGlobalAnnotationState() { switch (Compilation.Options.NullableContextOptions) { case NullableContextOptions.Enable: case NullableContextOptions.Annotations: return true; case NullableContextOptions.Disable: case NullableContextOptions.Warnings: return false; default: throw ExceptionUtilities.UnexpectedValue(Compilation.Options.NullableContextOptions); } } /// <summary> /// Is the contained code within a member method body? /// </summary> /// <remarks> /// May be false in lambdas that are outside of member method bodies, e.g. lambdas in /// field initializers. /// </remarks> internal virtual bool IsInMethodBody { get { RoslynDebug.Assert(Next is object); return Next.IsInMethodBody; } } /// <summary> /// Is the contained code within an iterator block? /// </summary> /// <remarks> /// Will be false in a lambda in an iterator. /// </remarks> internal virtual bool IsDirectlyInIterator { get { RoslynDebug.Assert(Next is object); return Next.IsDirectlyInIterator; } } /// <summary> /// Is the contained code within the syntactic span of an /// iterator method? /// </summary> /// <remarks> /// Will be true in a lambda in an iterator. /// </remarks> internal virtual bool IsIndirectlyInIterator { get { RoslynDebug.Assert(Next is object); return Next.IsIndirectlyInIterator; } } /// <summary> /// If we are inside a context where a break statement is legal, /// returns the <see cref="GeneratedLabelSymbol"/> that a break statement would branch to. /// Returns null otherwise. /// </summary> internal virtual GeneratedLabelSymbol? BreakLabel { get { RoslynDebug.Assert(Next is object); return Next.BreakLabel; } } /// <summary> /// If we are inside a context where a continue statement is legal, /// returns the <see cref="GeneratedLabelSymbol"/> that a continue statement would branch to. /// Returns null otherwise. /// </summary> internal virtual GeneratedLabelSymbol? ContinueLabel { get { RoslynDebug.Assert(Next is object); return Next.ContinueLabel; } } /// <summary> /// Get the element type of this iterator. /// </summary> /// <returns>Element type of the current iterator, or an error type.</returns> internal virtual TypeWithAnnotations GetIteratorElementType() { RoslynDebug.Assert(Next is object); return Next.GetIteratorElementType(); } /// <summary> /// The imports for all containing namespace declarations (innermost-to-outermost, including global), /// or null if there are none. /// </summary> internal virtual ImportChain? ImportChain { get { RoslynDebug.Assert(Next is object); return Next.ImportChain; } } /// <summary> /// Get <see cref="QuickAttributeChecker"/> that can be used to quickly /// check for certain attribute applications in context of this binder. /// </summary> internal virtual QuickAttributeChecker QuickAttributeChecker { get { RoslynDebug.Assert(Next is object); return Next.QuickAttributeChecker; } } protected virtual bool InExecutableBinder { get { RoslynDebug.Assert(Next is object); return Next.InExecutableBinder; } } /// <summary> /// The type containing the binding context /// </summary> internal NamedTypeSymbol? ContainingType { get { var member = this.ContainingMemberOrLambda; RoslynDebug.Assert(member is null || member.Kind != SymbolKind.ErrorType); return member switch { null => null, NamedTypeSymbol namedType => namedType, _ => member.ContainingType }; } } /// <summary> /// Returns true if the binder is binding top-level script code. /// </summary> internal bool BindingTopLevelScriptCode { get { var containingMember = this.ContainingMemberOrLambda; switch (containingMember?.Kind) { case SymbolKind.Method: // global statements return ((MethodSymbol)containingMember).IsScriptInitializer; case SymbolKind.NamedType: // script variable initializers return ((NamedTypeSymbol)containingMember).IsScriptClass; default: return false; } } } internal virtual ConstantFieldsInProgress ConstantFieldsInProgress { get { RoslynDebug.Assert(Next is object); return this.Next.ConstantFieldsInProgress; } } internal virtual ConsList<FieldSymbol> FieldsBeingBound { get { RoslynDebug.Assert(Next is object); return this.Next.FieldsBeingBound; } } internal virtual LocalSymbol? LocalInProgress { get { RoslynDebug.Assert(Next is object); return this.Next.LocalInProgress; } } internal virtual BoundExpression? ConditionalReceiverExpression { get { RoslynDebug.Assert(Next is object); return this.Next.ConditionalReceiverExpression; } } private Conversions? _lazyConversions; internal Conversions Conversions { get { if (_lazyConversions == null) { Interlocked.CompareExchange(ref _lazyConversions, new Conversions(this), null); } return _lazyConversions; } } private OverloadResolution? _lazyOverloadResolution; internal OverloadResolution OverloadResolution { get { if (_lazyOverloadResolution == null) { Interlocked.CompareExchange(ref _lazyOverloadResolution, new OverloadResolution(this), null); } return _lazyOverloadResolution; } } internal static void Error(BindingDiagnosticBag diagnostics, DiagnosticInfo info, SyntaxNode syntax) { diagnostics.Add(new CSDiagnostic(info, syntax.Location)); } internal static void Error(BindingDiagnosticBag diagnostics, DiagnosticInfo info, Location location) { diagnostics.Add(new CSDiagnostic(info, location)); } internal static void Error(BindingDiagnosticBag diagnostics, ErrorCode code, CSharpSyntaxNode syntax) { diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(code), syntax.Location)); } internal static void Error(BindingDiagnosticBag diagnostics, ErrorCode code, CSharpSyntaxNode syntax, params object[] args) { diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(code, args), syntax.Location)); } internal static void Error(BindingDiagnosticBag diagnostics, ErrorCode code, SyntaxToken token) { diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(code), token.GetLocation())); } internal static void Error(BindingDiagnosticBag diagnostics, ErrorCode code, SyntaxToken token, params object[] args) { diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(code, args), token.GetLocation())); } internal static void Error(BindingDiagnosticBag diagnostics, ErrorCode code, SyntaxNodeOrToken syntax) { var location = syntax.GetLocation(); RoslynDebug.Assert(location is object); Error(diagnostics, code, location); } internal static void Error(BindingDiagnosticBag diagnostics, ErrorCode code, SyntaxNodeOrToken syntax, params object[] args) { var location = syntax.GetLocation(); RoslynDebug.Assert(location is object); Error(diagnostics, code, location, args); } internal static void Error(BindingDiagnosticBag diagnostics, ErrorCode code, Location location) { diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(code), location)); } internal static void Error(BindingDiagnosticBag diagnostics, ErrorCode code, Location location, params object[] args) { diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(code, args), location)); } /// <summary> /// Issue an error or warning for a symbol if it is Obsolete. If there is not enough /// information to report diagnostics, then store the symbols so that diagnostics /// can be reported at a later stage. /// </summary> /// <remarks> /// This method is introduced to move the implicit conversion operator call from the caller /// so as to reduce the caller stack frame size /// </remarks> internal void ReportDiagnosticsIfObsolete(DiagnosticBag diagnostics, Symbol symbol, SyntaxNode node, bool hasBaseReceiver) { ReportDiagnosticsIfObsolete(diagnostics, symbol, (SyntaxNodeOrToken)node, hasBaseReceiver); } /// <summary> /// Issue an error or warning for a symbol if it is Obsolete. If there is not enough /// information to report diagnostics, then store the symbols so that diagnostics /// can be reported at a later stage. /// </summary> internal void ReportDiagnosticsIfObsolete(DiagnosticBag diagnostics, Symbol symbol, SyntaxNodeOrToken node, bool hasBaseReceiver) { switch (symbol.Kind) { case SymbolKind.NamedType: case SymbolKind.Field: case SymbolKind.Method: case SymbolKind.Event: case SymbolKind.Property: ReportDiagnosticsIfObsolete(diagnostics, symbol, node, hasBaseReceiver, this.ContainingMemberOrLambda, this.ContainingType, this.Flags); break; } } internal void ReportDiagnosticsIfObsolete(BindingDiagnosticBag diagnostics, Symbol symbol, SyntaxNodeOrToken node, bool hasBaseReceiver) { if (diagnostics.DiagnosticBag is object) { ReportDiagnosticsIfObsolete(diagnostics.DiagnosticBag, symbol, node, hasBaseReceiver); } } internal void ReportDiagnosticsIfObsolete(BindingDiagnosticBag diagnostics, Conversion conversion, SyntaxNodeOrToken node, bool hasBaseReceiver) { if (conversion.IsValid && conversion.Method is object) { ReportDiagnosticsIfObsolete(diagnostics, conversion.Method, node, hasBaseReceiver); } } internal static void ReportDiagnosticsIfObsolete( DiagnosticBag diagnostics, Symbol symbol, SyntaxNodeOrToken node, bool hasBaseReceiver, Symbol? containingMember, NamedTypeSymbol? containingType, BinderFlags location) { RoslynDebug.Assert(symbol is object); RoslynDebug.Assert(symbol.Kind == SymbolKind.NamedType || symbol.Kind == SymbolKind.Field || symbol.Kind == SymbolKind.Method || symbol.Kind == SymbolKind.Event || symbol.Kind == SymbolKind.Property); // Dev11 also reports on the unconstructed method. It would be nice to report on // the constructed method, but then we wouldn't be able to walk the override chain. if (symbol.Kind == SymbolKind.Method) { symbol = ((MethodSymbol)symbol).ConstructedFrom; } // There are two reasons to walk up to the least-overridden member: // 1) That's the method to which we will actually emit a call. // 2) We don't know what virtual dispatch will do at runtime so an // overriding member is basically a shot in the dark. Better to // just be consistent and always use the least-overridden member. Symbol leastOverriddenSymbol = symbol.GetLeastOverriddenMember(containingType); bool checkOverridingSymbol = hasBaseReceiver && !ReferenceEquals(symbol, leastOverriddenSymbol); if (checkOverridingSymbol) { // If we have a base receiver, we must be done with declaration binding, so it should // be safe to decode diagnostics. We want to do this since reporting for the overriding // member is conditional on reporting for the overridden member (i.e. we need a definite // answer so we don't double-report). You might think that double reporting just results // in cascading diagnostics, but it's possible that the second diagnostic is an error // while the first is merely a warning. leastOverriddenSymbol.GetAttributes(); } var diagnosticKind = ReportDiagnosticsIfObsoleteInternal(diagnostics, leastOverriddenSymbol, node, containingMember, location); // CONSIDER: In place of hasBaseReceiver, dev11 also accepts cases where symbol.ContainingType is a "simple type" (e.g. int) // or a special by-ref type (e.g. ArgumentHandle). These cases are probably more important for other checks performed by // ExpressionBinder::PostBindMethod, but they do appear to ObsoleteAttribute as well. We're skipping them because they // don't make much sense for ObsoleteAttribute (e.g. this would seem to address the case where int.ToString has been made // obsolete but object.ToString has not). // If the overridden member was not definitely obsolete and this is a (non-virtual) base member // access, then check the overriding symbol as well. switch (diagnosticKind) { case ObsoleteDiagnosticKind.NotObsolete: case ObsoleteDiagnosticKind.Lazy: if (checkOverridingSymbol) { RoslynDebug.Assert(diagnosticKind != ObsoleteDiagnosticKind.Lazy, "We forced attribute binding above."); ReportDiagnosticsIfObsoleteInternal(diagnostics, symbol, node, containingMember, location); } break; } } internal static void ReportDiagnosticsIfObsolete( BindingDiagnosticBag diagnostics, Symbol symbol, SyntaxNodeOrToken node, bool hasBaseReceiver, Symbol? containingMember, NamedTypeSymbol? containingType, BinderFlags location) { if (diagnostics.DiagnosticBag is object) { ReportDiagnosticsIfObsolete(diagnostics.DiagnosticBag, symbol, node, hasBaseReceiver, containingMember, containingType, location); } } internal static ObsoleteDiagnosticKind ReportDiagnosticsIfObsoleteInternal(DiagnosticBag diagnostics, Symbol symbol, SyntaxNodeOrToken node, Symbol? containingMember, BinderFlags location) { RoslynDebug.Assert(diagnostics != null); var kind = ObsoleteAttributeHelpers.GetObsoleteDiagnosticKind(symbol, containingMember); DiagnosticInfo? info = null; switch (kind) { case ObsoleteDiagnosticKind.Diagnostic: info = ObsoleteAttributeHelpers.CreateObsoleteDiagnostic(symbol, location); break; case ObsoleteDiagnosticKind.Lazy: case ObsoleteDiagnosticKind.LazyPotentiallySuppressed: info = new LazyObsoleteDiagnosticInfo(symbol, containingMember, location); break; } if (info != null) { diagnostics.Add(info, node.GetLocation()); } return kind; } internal static void ReportDiagnosticsIfObsoleteInternal(BindingDiagnosticBag diagnostics, Symbol symbol, SyntaxNodeOrToken node, Symbol containingMember, BinderFlags location) { if (diagnostics.DiagnosticBag is object) { ReportDiagnosticsIfObsoleteInternal(diagnostics.DiagnosticBag, symbol, node, containingMember, location); } } internal static void ReportDiagnosticsIfUnmanagedCallersOnly(BindingDiagnosticBag diagnostics, MethodSymbol symbol, Location location, bool isDelegateConversion) { var unmanagedCallersOnlyAttributeData = symbol.GetUnmanagedCallersOnlyAttributeData(forceComplete: false); if (unmanagedCallersOnlyAttributeData != null) { // Either we haven't yet bound the attributes of this method, or there is an UnmanagedCallersOnly present. // In the former case, we use a lazy diagnostic that may end up being ignored later, to avoid causing a // binding cycle. diagnostics.Add(unmanagedCallersOnlyAttributeData == UnmanagedCallersOnlyAttributeData.Uninitialized ? (DiagnosticInfo)new LazyUnmanagedCallersOnlyMethodCalledDiagnosticInfo(symbol, isDelegateConversion) : new CSDiagnosticInfo(isDelegateConversion ? ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate : ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, symbol), location); } } internal static bool IsSymbolAccessibleConditional( Symbol symbol, AssemblySymbol within, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return AccessCheck.IsSymbolAccessible(symbol, within, ref useSiteInfo); } internal bool IsSymbolAccessibleConditional( Symbol symbol, NamedTypeSymbol within, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, TypeSymbol? throughTypeOpt = null) { return this.Flags.Includes(BinderFlags.IgnoreAccessibility) || AccessCheck.IsSymbolAccessible(symbol, within, ref useSiteInfo, throughTypeOpt); } internal bool IsSymbolAccessibleConditional( Symbol symbol, NamedTypeSymbol within, TypeSymbol throughTypeOpt, out bool failedThroughTypeCheck, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConsList<TypeSymbol>? basesBeingResolved = null) { if (this.Flags.Includes(BinderFlags.IgnoreAccessibility)) { failedThroughTypeCheck = false; return true; } return AccessCheck.IsSymbolAccessible(symbol, within, throughTypeOpt, out failedThroughTypeCheck, ref useSiteInfo, basesBeingResolved); } /// <summary> /// Report diagnostics that should be reported when using a synthesized attribute. /// </summary> internal static void ReportUseSiteDiagnosticForSynthesizedAttribute( CSharpCompilation compilation, WellKnownMember attributeMember, BindingDiagnosticBag diagnostics, Location? location = null, CSharpSyntaxNode? syntax = null) { RoslynDebug.Assert((location != null) ^ (syntax != null)); // Dev11 reports use-site diagnostics when an optional attribute is found but is bad for some other reason // (comes from an unified assembly). When the symbol is not found no error is reported. See test VersionUnification_UseSiteDiagnostics_OptionalAttributes. bool isOptional = WellKnownMembers.IsSynthesizedAttributeOptional(attributeMember); GetWellKnownTypeMember(compilation, attributeMember, diagnostics, location, syntax, isOptional); } public CompoundUseSiteInfo<AssemblySymbol> GetNewCompoundUseSiteInfo(BindingDiagnosticBag futureDestination) { return new CompoundUseSiteInfo<AssemblySymbol>(futureDestination, Compilation.Assembly); } #if DEBUG // Helper to allow displaying the binder hierarchy in the debugger. internal Binder[] GetAllBinders() { var binders = ArrayBuilder<Binder>.GetInstance(); for (Binder? binder = this; binder != null; binder = binder.Next) { binders.Add(binder); } return binders.ToArrayAndFree(); } #endif internal BoundExpression WrapWithVariablesIfAny(CSharpSyntaxNode scopeDesignator, BoundExpression expression) { var locals = this.GetDeclaredLocalsForScope(scopeDesignator); return (locals.IsEmpty) ? expression : new BoundSequence(scopeDesignator, locals, ImmutableArray<BoundExpression>.Empty, expression, getType()) { WasCompilerGenerated = true }; TypeSymbol getType() { RoslynDebug.Assert(expression.Type is object); return expression.Type; } } internal BoundStatement WrapWithVariablesIfAny(CSharpSyntaxNode scopeDesignator, BoundStatement statement) { RoslynDebug.Assert(statement.Kind != BoundKind.StatementList); var locals = this.GetDeclaredLocalsForScope(scopeDesignator); if (locals.IsEmpty) { return statement; } return new BoundBlock(statement.Syntax, locals, ImmutableArray.Create(statement)) { WasCompilerGenerated = true }; } /// <summary> /// Should only be used with scopes that could declare local functions. /// </summary> internal BoundStatement WrapWithVariablesAndLocalFunctionsIfAny(CSharpSyntaxNode scopeDesignator, BoundStatement statement) { var locals = this.GetDeclaredLocalsForScope(scopeDesignator); var localFunctions = this.GetDeclaredLocalFunctionsForScope(scopeDesignator); if (locals.IsEmpty && localFunctions.IsEmpty) { return statement; } return new BoundBlock(statement.Syntax, locals, localFunctions, ImmutableArray.Create(statement)) { WasCompilerGenerated = true }; } internal string Dump() { return TreeDumper.DumpCompact(dumpAncestors()); TreeDumperNode dumpAncestors() { TreeDumperNode? current = null; for (Binder? scope = this; scope != null; scope = scope.Next) { var (description, snippet, locals) = print(scope); var sub = new List<TreeDumperNode>(); if (!locals.IsEmpty()) { sub.Add(new TreeDumperNode("locals", locals, null)); } var currentContainer = scope.ContainingMemberOrLambda; if (currentContainer != null && currentContainer != scope.Next?.ContainingMemberOrLambda) { sub.Add(new TreeDumperNode("containing symbol", currentContainer.ToDisplayString(), null)); } if (snippet != null) { sub.Add(new TreeDumperNode($"scope", $"{snippet} ({scope.ScopeDesignator?.Kind()})", null)); } if (current != null) { sub.Add(current); } current = new TreeDumperNode(description, null, sub); } RoslynDebug.Assert(current is object); return current; } static (string description, string? snippet, string locals) print(Binder scope) { var locals = string.Join(", ", scope.Locals.SelectAsArray(s => s.Name)); string? snippet = null; if (scope.ScopeDesignator != null) { var lines = scope.ScopeDesignator.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); if (lines.Length == 1) { snippet = lines[0]; } else { var first = lines[0]; var last = lines[lines.Length - 1].Trim(); var lastSize = Math.Min(last.Length, 12); snippet = first.Substring(0, Math.Min(first.Length, 12)) + " ... " + last.Substring(last.Length - lastSize, lastSize); } snippet = snippet.IsEmpty() ? null : snippet; } var description = scope.GetType().Name; return (description, snippet, locals); } } } }
// Licensed to the .NET Foundation under one or more 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.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// A Binder converts names in to symbols and syntax nodes into bound trees. It is context /// dependent, relative to a location in source code. /// </summary> internal partial class Binder { internal CSharpCompilation Compilation { get; } internal readonly BinderFlags Flags; /// <summary> /// Used to create a root binder. /// </summary> internal Binder(CSharpCompilation compilation) { RoslynDebug.Assert(compilation != null); RoslynDebug.Assert(this is BuckStopsHereBinder); this.Flags = compilation.Options.TopLevelBinderFlags; this.Compilation = compilation; } internal Binder(Binder next, Conversions? conversions = null) { RoslynDebug.Assert(next != null); Next = next; this.Flags = next.Flags; this.Compilation = next.Compilation; _lazyConversions = conversions; } protected Binder(Binder next, BinderFlags flags) { RoslynDebug.Assert(next != null); // Mutually exclusive. RoslynDebug.Assert(!flags.Includes(BinderFlags.UncheckedRegion | BinderFlags.CheckedRegion)); // Implied. RoslynDebug.Assert(!flags.Includes(BinderFlags.InNestedFinallyBlock) || flags.Includes(BinderFlags.InFinallyBlock | BinderFlags.InCatchBlock)); Next = next; this.Flags = flags; this.Compilation = next.Compilation; } internal bool IsSemanticModelBinder { get { return this.Flags.Includes(BinderFlags.SemanticModel); } } // IsEarlyAttributeBinder is called relatively frequently so we want fast code here. internal bool IsEarlyAttributeBinder { get { return this.Flags.Includes(BinderFlags.EarlyAttributeBinding); } } // Return the nearest enclosing node being bound as a nameof(...) argument, if any, or null if none. protected virtual SyntaxNode? EnclosingNameofArgument => null; private bool IsInsideNameof => this.EnclosingNameofArgument != null; /// <summary> /// Get the next binder in which to look up a name, if not found by this binder. /// </summary> protected internal Binder? Next { get; } /// <summary> /// Get the next binder in which to look up a name, if not found by this binder, asserting if `Next` is null. /// </summary> protected internal Binder NextRequired { get { Debug.Assert(Next is not null); return Next; } } /// <summary> /// <see cref="OverflowChecks.Enabled"/> if we are in an explicitly checked context (within checked block or expression). /// <see cref="OverflowChecks.Disabled"/> if we are in an explicitly unchecked context (within unchecked block or expression). /// <see cref="OverflowChecks.Implicit"/> otherwise. /// </summary> protected OverflowChecks CheckOverflow { get { // Although C# 4.0 specification says that checked context never flows in a lambda, // the Dev10 compiler implementation always flows the context in, except for // when the lambda is directly a "parameter" of the checked/unchecked expression. // For Roslyn we decided to change the spec and always flow the context in. // So we don't stop at lambda binder. RoslynDebug.Assert(!this.Flags.Includes(BinderFlags.UncheckedRegion | BinderFlags.CheckedRegion)); return this.Flags.Includes(BinderFlags.CheckedRegion) ? OverflowChecks.Enabled : this.Flags.Includes(BinderFlags.UncheckedRegion) ? OverflowChecks.Disabled : OverflowChecks.Implicit; } } /// <summary> /// True if instructions that check overflow should be generated. /// </summary> /// <remarks> /// Spec 7.5.12: /// For non-constant expressions (expressions that are evaluated at run-time) that are not /// enclosed by any checked or unchecked operators or statements, the default overflow checking /// context is unchecked unless external factors (such as compiler switches and execution /// environment configuration) call for checked evaluation. /// </remarks> protected bool CheckOverflowAtRuntime { get { var result = CheckOverflow; return result == OverflowChecks.Enabled || result == OverflowChecks.Implicit && Compilation.Options.CheckOverflow; } } /// <summary> /// True if the compiler should check for overflow while evaluating constant expressions. /// </summary> /// <remarks> /// Spec 7.5.12: /// For constant expressions (expressions that can be fully evaluated at compile-time), /// the default overflow checking context is always checked. Unless a constant expression /// is explicitly placed in an unchecked context, overflows that occur during the compile-time /// evaluation of the expression always cause compile-time errors. /// </remarks> internal bool CheckOverflowAtCompileTime { get { return CheckOverflow != OverflowChecks.Disabled; } } /// <summary> /// Some nodes have special binders for their contents (like Blocks) /// </summary> internal virtual Binder? GetBinder(SyntaxNode node) { RoslynDebug.Assert(Next is object); return this.Next.GetBinder(node); } /// <summary> /// Gets a binder for a node that must be not null, and asserts /// if it is not. /// </summary> internal Binder GetRequiredBinder(SyntaxNode node) { var binder = GetBinder(node); RoslynDebug.Assert(binder is object); return binder; } /// <summary> /// Get locals declared immediately in scope designated by the node. /// </summary> internal virtual ImmutableArray<LocalSymbol> GetDeclaredLocalsForScope(SyntaxNode scopeDesignator) { RoslynDebug.Assert(Next is object); return this.Next.GetDeclaredLocalsForScope(scopeDesignator); } /// <summary> /// Get local functions declared immediately in scope designated by the node. /// </summary> internal virtual ImmutableArray<LocalFunctionSymbol> GetDeclaredLocalFunctionsForScope(CSharpSyntaxNode scopeDesignator) { RoslynDebug.Assert(Next is object); return this.Next.GetDeclaredLocalFunctionsForScope(scopeDesignator); } /// <summary> /// If this binder owns a scope for locals, return syntax node that is used /// as the scope designator. Otherwise, null. /// </summary> internal virtual SyntaxNode? ScopeDesignator { get { return null; } } internal virtual bool IsLocalFunctionsScopeBinder { get { return false; } } internal virtual bool IsLabelsScopeBinder { get { return false; } } internal bool InExpressionTree => (Flags & BinderFlags.InExpressionTree) == BinderFlags.InExpressionTree; /// <summary> /// True if this is the top-level binder for a local function or lambda /// (including implicit lambdas from query expressions). /// </summary> internal virtual bool IsNestedFunctionBinder => false; /// <summary> /// The member containing the binding context. Note that for the purposes of the compiler, /// a lambda expression is considered a "member" of its enclosing method, field, or lambda. /// </summary> internal virtual Symbol? ContainingMemberOrLambda { get { RoslynDebug.Assert(Next is object); return Next.ContainingMemberOrLambda; } } /// <summary> /// Are we in a context where un-annotated types should be interpreted as non-null? /// </summary> internal bool AreNullableAnnotationsEnabled(SyntaxTree syntaxTree, int position) { CSharpSyntaxTree csTree = (CSharpSyntaxTree)syntaxTree; Syntax.NullableContextState context = csTree.GetNullableContextState(position); return context.AnnotationsState switch { Syntax.NullableContextState.State.Enabled => true, Syntax.NullableContextState.State.Disabled => false, Syntax.NullableContextState.State.ExplicitlyRestored => GetGlobalAnnotationState(), Syntax.NullableContextState.State.Unknown => !csTree.IsGeneratedCode(this.Compilation.Options.SyntaxTreeOptionsProvider, CancellationToken.None) && AreNullableAnnotationsGloballyEnabled(), _ => throw ExceptionUtilities.UnexpectedValue(context.AnnotationsState) }; } internal bool AreNullableAnnotationsEnabled(SyntaxToken token) { RoslynDebug.Assert(token.SyntaxTree is object); return AreNullableAnnotationsEnabled(token.SyntaxTree, token.SpanStart); } internal bool IsGeneratedCode(SyntaxToken token) { var tree = (CSharpSyntaxTree)token.SyntaxTree!; return tree.IsGeneratedCode(Compilation.Options.SyntaxTreeOptionsProvider, CancellationToken.None); } internal virtual bool AreNullableAnnotationsGloballyEnabled() { RoslynDebug.Assert(Next is object); return Next.AreNullableAnnotationsGloballyEnabled(); } protected bool GetGlobalAnnotationState() { switch (Compilation.Options.NullableContextOptions) { case NullableContextOptions.Enable: case NullableContextOptions.Annotations: return true; case NullableContextOptions.Disable: case NullableContextOptions.Warnings: return false; default: throw ExceptionUtilities.UnexpectedValue(Compilation.Options.NullableContextOptions); } } /// <summary> /// Is the contained code within a member method body? /// </summary> /// <remarks> /// May be false in lambdas that are outside of member method bodies, e.g. lambdas in /// field initializers. /// </remarks> internal virtual bool IsInMethodBody { get { RoslynDebug.Assert(Next is object); return Next.IsInMethodBody; } } /// <summary> /// Is the contained code within an iterator block? /// </summary> /// <remarks> /// Will be false in a lambda in an iterator. /// </remarks> internal virtual bool IsDirectlyInIterator { get { RoslynDebug.Assert(Next is object); return Next.IsDirectlyInIterator; } } /// <summary> /// Is the contained code within the syntactic span of an /// iterator method? /// </summary> /// <remarks> /// Will be true in a lambda in an iterator. /// </remarks> internal virtual bool IsIndirectlyInIterator { get { RoslynDebug.Assert(Next is object); return Next.IsIndirectlyInIterator; } } /// <summary> /// If we are inside a context where a break statement is legal, /// returns the <see cref="GeneratedLabelSymbol"/> that a break statement would branch to. /// Returns null otherwise. /// </summary> internal virtual GeneratedLabelSymbol? BreakLabel { get { RoslynDebug.Assert(Next is object); return Next.BreakLabel; } } /// <summary> /// If we are inside a context where a continue statement is legal, /// returns the <see cref="GeneratedLabelSymbol"/> that a continue statement would branch to. /// Returns null otherwise. /// </summary> internal virtual GeneratedLabelSymbol? ContinueLabel { get { RoslynDebug.Assert(Next is object); return Next.ContinueLabel; } } /// <summary> /// Get the element type of this iterator. /// </summary> /// <returns>Element type of the current iterator, or an error type.</returns> internal virtual TypeWithAnnotations GetIteratorElementType() { RoslynDebug.Assert(Next is object); return Next.GetIteratorElementType(); } /// <summary> /// The imports for all containing namespace declarations (innermost-to-outermost, including global), /// or null if there are none. /// </summary> internal virtual ImportChain? ImportChain { get { RoslynDebug.Assert(Next is object); return Next.ImportChain; } } /// <summary> /// Get <see cref="QuickAttributeChecker"/> that can be used to quickly /// check for certain attribute applications in context of this binder. /// </summary> internal virtual QuickAttributeChecker QuickAttributeChecker { get { RoslynDebug.Assert(Next is object); return Next.QuickAttributeChecker; } } protected virtual bool InExecutableBinder { get { RoslynDebug.Assert(Next is object); return Next.InExecutableBinder; } } /// <summary> /// The type containing the binding context /// </summary> internal NamedTypeSymbol? ContainingType { get { var member = this.ContainingMemberOrLambda; RoslynDebug.Assert(member is null || member.Kind != SymbolKind.ErrorType); return member switch { null => null, NamedTypeSymbol namedType => namedType, _ => member.ContainingType }; } } /// <summary> /// Returns true if the binder is binding top-level script code. /// </summary> internal bool BindingTopLevelScriptCode { get { var containingMember = this.ContainingMemberOrLambda; switch (containingMember?.Kind) { case SymbolKind.Method: // global statements return ((MethodSymbol)containingMember).IsScriptInitializer; case SymbolKind.NamedType: // script variable initializers return ((NamedTypeSymbol)containingMember).IsScriptClass; default: return false; } } } internal virtual ConstantFieldsInProgress ConstantFieldsInProgress { get { RoslynDebug.Assert(Next is object); return this.Next.ConstantFieldsInProgress; } } internal virtual ConsList<FieldSymbol> FieldsBeingBound { get { RoslynDebug.Assert(Next is object); return this.Next.FieldsBeingBound; } } internal virtual LocalSymbol? LocalInProgress { get { RoslynDebug.Assert(Next is object); return this.Next.LocalInProgress; } } internal virtual BoundExpression? ConditionalReceiverExpression { get { RoslynDebug.Assert(Next is object); return this.Next.ConditionalReceiverExpression; } } private Conversions? _lazyConversions; internal Conversions Conversions { get { if (_lazyConversions == null) { Interlocked.CompareExchange(ref _lazyConversions, new Conversions(this), null); } return _lazyConversions; } } private OverloadResolution? _lazyOverloadResolution; internal OverloadResolution OverloadResolution { get { if (_lazyOverloadResolution == null) { Interlocked.CompareExchange(ref _lazyOverloadResolution, new OverloadResolution(this), null); } return _lazyOverloadResolution; } } internal static void Error(BindingDiagnosticBag diagnostics, DiagnosticInfo info, SyntaxNode syntax) { diagnostics.Add(new CSDiagnostic(info, syntax.Location)); } internal static void Error(BindingDiagnosticBag diagnostics, DiagnosticInfo info, Location location) { diagnostics.Add(new CSDiagnostic(info, location)); } internal static void Error(BindingDiagnosticBag diagnostics, ErrorCode code, CSharpSyntaxNode syntax) { diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(code), syntax.Location)); } internal static void Error(BindingDiagnosticBag diagnostics, ErrorCode code, CSharpSyntaxNode syntax, params object[] args) { diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(code, args), syntax.Location)); } internal static void Error(BindingDiagnosticBag diagnostics, ErrorCode code, SyntaxToken token) { diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(code), token.GetLocation())); } internal static void Error(BindingDiagnosticBag diagnostics, ErrorCode code, SyntaxToken token, params object[] args) { diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(code, args), token.GetLocation())); } internal static void Error(BindingDiagnosticBag diagnostics, ErrorCode code, SyntaxNodeOrToken syntax) { var location = syntax.GetLocation(); RoslynDebug.Assert(location is object); Error(diagnostics, code, location); } internal static void Error(BindingDiagnosticBag diagnostics, ErrorCode code, SyntaxNodeOrToken syntax, params object[] args) { var location = syntax.GetLocation(); RoslynDebug.Assert(location is object); Error(diagnostics, code, location, args); } internal static void Error(BindingDiagnosticBag diagnostics, ErrorCode code, Location location) { diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(code), location)); } internal static void Error(BindingDiagnosticBag diagnostics, ErrorCode code, Location location, params object[] args) { diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(code, args), location)); } /// <summary> /// Issue an error or warning for a symbol if it is Obsolete. If there is not enough /// information to report diagnostics, then store the symbols so that diagnostics /// can be reported at a later stage. /// </summary> /// <remarks> /// This method is introduced to move the implicit conversion operator call from the caller /// so as to reduce the caller stack frame size /// </remarks> internal void ReportDiagnosticsIfObsolete(DiagnosticBag diagnostics, Symbol symbol, SyntaxNode node, bool hasBaseReceiver) { ReportDiagnosticsIfObsolete(diagnostics, symbol, (SyntaxNodeOrToken)node, hasBaseReceiver); } /// <summary> /// Issue an error or warning for a symbol if it is Obsolete. If there is not enough /// information to report diagnostics, then store the symbols so that diagnostics /// can be reported at a later stage. /// </summary> internal void ReportDiagnosticsIfObsolete(DiagnosticBag diagnostics, Symbol symbol, SyntaxNodeOrToken node, bool hasBaseReceiver) { switch (symbol.Kind) { case SymbolKind.NamedType: case SymbolKind.Field: case SymbolKind.Method: case SymbolKind.Event: case SymbolKind.Property: ReportDiagnosticsIfObsolete(diagnostics, symbol, node, hasBaseReceiver, this.ContainingMemberOrLambda, this.ContainingType, this.Flags); break; } } internal void ReportDiagnosticsIfObsolete(BindingDiagnosticBag diagnostics, Symbol symbol, SyntaxNodeOrToken node, bool hasBaseReceiver) { if (diagnostics.DiagnosticBag is object) { ReportDiagnosticsIfObsolete(diagnostics.DiagnosticBag, symbol, node, hasBaseReceiver); } } internal void ReportDiagnosticsIfObsolete(BindingDiagnosticBag diagnostics, Conversion conversion, SyntaxNodeOrToken node, bool hasBaseReceiver) { if (conversion.IsValid && conversion.Method is object) { ReportDiagnosticsIfObsolete(diagnostics, conversion.Method, node, hasBaseReceiver); } } internal static void ReportDiagnosticsIfObsolete( DiagnosticBag diagnostics, Symbol symbol, SyntaxNodeOrToken node, bool hasBaseReceiver, Symbol? containingMember, NamedTypeSymbol? containingType, BinderFlags location) { RoslynDebug.Assert(symbol is object); RoslynDebug.Assert(symbol.Kind == SymbolKind.NamedType || symbol.Kind == SymbolKind.Field || symbol.Kind == SymbolKind.Method || symbol.Kind == SymbolKind.Event || symbol.Kind == SymbolKind.Property); // Dev11 also reports on the unconstructed method. It would be nice to report on // the constructed method, but then we wouldn't be able to walk the override chain. if (symbol.Kind == SymbolKind.Method) { symbol = ((MethodSymbol)symbol).ConstructedFrom; } // There are two reasons to walk up to the least-overridden member: // 1) That's the method to which we will actually emit a call. // 2) We don't know what virtual dispatch will do at runtime so an // overriding member is basically a shot in the dark. Better to // just be consistent and always use the least-overridden member. Symbol leastOverriddenSymbol = symbol.GetLeastOverriddenMember(containingType); bool checkOverridingSymbol = hasBaseReceiver && !ReferenceEquals(symbol, leastOverriddenSymbol); if (checkOverridingSymbol) { // If we have a base receiver, we must be done with declaration binding, so it should // be safe to decode diagnostics. We want to do this since reporting for the overriding // member is conditional on reporting for the overridden member (i.e. we need a definite // answer so we don't double-report). You might think that double reporting just results // in cascading diagnostics, but it's possible that the second diagnostic is an error // while the first is merely a warning. leastOverriddenSymbol.GetAttributes(); } var diagnosticKind = ReportDiagnosticsIfObsoleteInternal(diagnostics, leastOverriddenSymbol, node, containingMember, location); // CONSIDER: In place of hasBaseReceiver, dev11 also accepts cases where symbol.ContainingType is a "simple type" (e.g. int) // or a special by-ref type (e.g. ArgumentHandle). These cases are probably more important for other checks performed by // ExpressionBinder::PostBindMethod, but they do appear to ObsoleteAttribute as well. We're skipping them because they // don't make much sense for ObsoleteAttribute (e.g. this would seem to address the case where int.ToString has been made // obsolete but object.ToString has not). // If the overridden member was not definitely obsolete and this is a (non-virtual) base member // access, then check the overriding symbol as well. switch (diagnosticKind) { case ObsoleteDiagnosticKind.NotObsolete: case ObsoleteDiagnosticKind.Lazy: if (checkOverridingSymbol) { RoslynDebug.Assert(diagnosticKind != ObsoleteDiagnosticKind.Lazy, "We forced attribute binding above."); ReportDiagnosticsIfObsoleteInternal(diagnostics, symbol, node, containingMember, location); } break; } } internal static void ReportDiagnosticsIfObsolete( BindingDiagnosticBag diagnostics, Symbol symbol, SyntaxNodeOrToken node, bool hasBaseReceiver, Symbol? containingMember, NamedTypeSymbol? containingType, BinderFlags location) { if (diagnostics.DiagnosticBag is object) { ReportDiagnosticsIfObsolete(diagnostics.DiagnosticBag, symbol, node, hasBaseReceiver, containingMember, containingType, location); } } internal static ObsoleteDiagnosticKind ReportDiagnosticsIfObsoleteInternal(DiagnosticBag diagnostics, Symbol symbol, SyntaxNodeOrToken node, Symbol? containingMember, BinderFlags location) { RoslynDebug.Assert(diagnostics != null); var kind = ObsoleteAttributeHelpers.GetObsoleteDiagnosticKind(symbol, containingMember); DiagnosticInfo? info = null; switch (kind) { case ObsoleteDiagnosticKind.Diagnostic: info = ObsoleteAttributeHelpers.CreateObsoleteDiagnostic(symbol, location); break; case ObsoleteDiagnosticKind.Lazy: case ObsoleteDiagnosticKind.LazyPotentiallySuppressed: info = new LazyObsoleteDiagnosticInfo(symbol, containingMember, location); break; } if (info != null) { diagnostics.Add(info, node.GetLocation()); } return kind; } internal static void ReportDiagnosticsIfObsoleteInternal(BindingDiagnosticBag diagnostics, Symbol symbol, SyntaxNodeOrToken node, Symbol containingMember, BinderFlags location) { if (diagnostics.DiagnosticBag is object) { ReportDiagnosticsIfObsoleteInternal(diagnostics.DiagnosticBag, symbol, node, containingMember, location); } } internal static void ReportDiagnosticsIfUnmanagedCallersOnly(BindingDiagnosticBag diagnostics, MethodSymbol symbol, Location location, bool isDelegateConversion) { var unmanagedCallersOnlyAttributeData = symbol.GetUnmanagedCallersOnlyAttributeData(forceComplete: false); if (unmanagedCallersOnlyAttributeData != null) { // Either we haven't yet bound the attributes of this method, or there is an UnmanagedCallersOnly present. // In the former case, we use a lazy diagnostic that may end up being ignored later, to avoid causing a // binding cycle. diagnostics.Add(unmanagedCallersOnlyAttributeData == UnmanagedCallersOnlyAttributeData.Uninitialized ? (DiagnosticInfo)new LazyUnmanagedCallersOnlyMethodCalledDiagnosticInfo(symbol, isDelegateConversion) : new CSDiagnosticInfo(isDelegateConversion ? ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeConvertedToDelegate : ErrorCode.ERR_UnmanagedCallersOnlyMethodsCannotBeCalledDirectly, symbol), location); } } internal static bool IsSymbolAccessibleConditional( Symbol symbol, AssemblySymbol within, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return AccessCheck.IsSymbolAccessible(symbol, within, ref useSiteInfo); } internal bool IsSymbolAccessibleConditional( Symbol symbol, NamedTypeSymbol within, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, TypeSymbol? throughTypeOpt = null) { return this.Flags.Includes(BinderFlags.IgnoreAccessibility) || AccessCheck.IsSymbolAccessible(symbol, within, ref useSiteInfo, throughTypeOpt); } internal bool IsSymbolAccessibleConditional( Symbol symbol, NamedTypeSymbol within, TypeSymbol throughTypeOpt, out bool failedThroughTypeCheck, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConsList<TypeSymbol>? basesBeingResolved = null) { if (this.Flags.Includes(BinderFlags.IgnoreAccessibility)) { failedThroughTypeCheck = false; return true; } return AccessCheck.IsSymbolAccessible(symbol, within, throughTypeOpt, out failedThroughTypeCheck, ref useSiteInfo, basesBeingResolved); } /// <summary> /// Report diagnostics that should be reported when using a synthesized attribute. /// </summary> internal static void ReportUseSiteDiagnosticForSynthesizedAttribute( CSharpCompilation compilation, WellKnownMember attributeMember, BindingDiagnosticBag diagnostics, Location? location = null, CSharpSyntaxNode? syntax = null) { RoslynDebug.Assert((location != null) ^ (syntax != null)); // Dev11 reports use-site diagnostics when an optional attribute is found but is bad for some other reason // (comes from an unified assembly). When the symbol is not found no error is reported. See test VersionUnification_UseSiteDiagnostics_OptionalAttributes. bool isOptional = WellKnownMembers.IsSynthesizedAttributeOptional(attributeMember); GetWellKnownTypeMember(compilation, attributeMember, diagnostics, location, syntax, isOptional); } public CompoundUseSiteInfo<AssemblySymbol> GetNewCompoundUseSiteInfo(BindingDiagnosticBag futureDestination) { return new CompoundUseSiteInfo<AssemblySymbol>(futureDestination, Compilation.Assembly); } #if DEBUG // Helper to allow displaying the binder hierarchy in the debugger. internal Binder[] GetAllBinders() { var binders = ArrayBuilder<Binder>.GetInstance(); for (Binder? binder = this; binder != null; binder = binder.Next) { binders.Add(binder); } return binders.ToArrayAndFree(); } #endif internal BoundExpression WrapWithVariablesIfAny(CSharpSyntaxNode scopeDesignator, BoundExpression expression) { var locals = this.GetDeclaredLocalsForScope(scopeDesignator); return (locals.IsEmpty) ? expression : new BoundSequence(scopeDesignator, locals, ImmutableArray<BoundExpression>.Empty, expression, getType()) { WasCompilerGenerated = true }; TypeSymbol getType() { RoslynDebug.Assert(expression.Type is object); return expression.Type; } } internal BoundStatement WrapWithVariablesIfAny(CSharpSyntaxNode scopeDesignator, BoundStatement statement) { RoslynDebug.Assert(statement.Kind != BoundKind.StatementList); var locals = this.GetDeclaredLocalsForScope(scopeDesignator); if (locals.IsEmpty) { return statement; } return new BoundBlock(statement.Syntax, locals, ImmutableArray.Create(statement)) { WasCompilerGenerated = true }; } /// <summary> /// Should only be used with scopes that could declare local functions. /// </summary> internal BoundStatement WrapWithVariablesAndLocalFunctionsIfAny(CSharpSyntaxNode scopeDesignator, BoundStatement statement) { var locals = this.GetDeclaredLocalsForScope(scopeDesignator); var localFunctions = this.GetDeclaredLocalFunctionsForScope(scopeDesignator); if (locals.IsEmpty && localFunctions.IsEmpty) { return statement; } return new BoundBlock(statement.Syntax, locals, localFunctions, ImmutableArray.Create(statement)) { WasCompilerGenerated = true }; } internal string Dump() { return TreeDumper.DumpCompact(dumpAncestors()); TreeDumperNode dumpAncestors() { TreeDumperNode? current = null; for (Binder? scope = this; scope != null; scope = scope.Next) { var (description, snippet, locals) = print(scope); var sub = new List<TreeDumperNode>(); if (!locals.IsEmpty()) { sub.Add(new TreeDumperNode("locals", locals, null)); } var currentContainer = scope.ContainingMemberOrLambda; if (currentContainer != null && currentContainer != scope.Next?.ContainingMemberOrLambda) { sub.Add(new TreeDumperNode("containing symbol", currentContainer.ToDisplayString(), null)); } if (snippet != null) { sub.Add(new TreeDumperNode($"scope", $"{snippet} ({scope.ScopeDesignator?.Kind()})", null)); } if (current != null) { sub.Add(current); } current = new TreeDumperNode(description, null, sub); } RoslynDebug.Assert(current is object); return current; } static (string description, string? snippet, string locals) print(Binder scope) { var locals = string.Join(", ", scope.Locals.SelectAsArray(s => s.Name)); string? snippet = null; if (scope.ScopeDesignator != null) { var lines = scope.ScopeDesignator.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); if (lines.Length == 1) { snippet = lines[0]; } else { var first = lines[0]; var last = lines[lines.Length - 1].Trim(); var lastSize = Math.Min(last.Length, 12); snippet = first.Substring(0, Math.Min(first.Length, 12)) + " ... " + last.Substring(last.Length - lastSize, lastSize); } snippet = snippet.IsEmpty() ? null : snippet; } var description = scope.GetType().Name; return (description, snippet, locals); } } } }
1
dotnet/roslyn
55,125
Don't use DefaultInterpolatedStringHandler in expression trees
Introduces a binder flag to track whether we are currently in an expression tree or not. Fixes https://github.com/dotnet/roslyn/issues/55114.
333fred
2021-07-26T22:08:39Z
2021-07-27T19:33:24Z
5840335153dcca42570a853cdacd06d660fe9596
cfc12ce93ce377c4b9581ccf88403e6740d63977
Don't use DefaultInterpolatedStringHandler in expression trees. Introduces a binder flag to track whether we are currently in an expression tree or not. Fixes https://github.com/dotnet/roslyn/issues/55114.
./src/Compilers/CSharp/Portable/Binder/BinderFlags.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 { /// <summary> /// A specific location for binding. /// </summary> [Flags] internal enum BinderFlags : uint { None, // No specific location SuppressConstraintChecks = 1 << 0, SuppressObsoleteChecks = 1 << 1, ConstructorInitializer = 1 << 2, FieldInitializer = 1 << 3, ObjectInitializerMember = 1 << 4, // object initializer field/property access CollectionInitializerAddMethod = 1 << 5, // used for collection initializer add method overload resolution diagnostics AttributeArgument = 1 << 6, GenericConstraintsClause = 1 << 7, // "where" clause (used for cycle checking) Cref = 1 << 8, // documentation comment cref CrefParameterOrReturnType = 1 << 9, // Same as Cref, but lookup considers inherited members /// <summary> /// Indicates that the current context allows unsafe constructs. /// </summary> /// <remarks> /// NOTE: Dev10 doesn't seem to treat attributes as being within the unsafe region. /// Fortunately, not following this behavior should not be a breaking change since /// attribute arguments have to be constants and there are no constants of unsafe /// types. /// </remarks> UnsafeRegion = 1 << 10, /// <summary> /// Indicates that the unsafe diagnostics are not reported in the current context, regardless /// of whether or not it is (part of) an unsafe region. /// </summary> SuppressUnsafeDiagnostics = 1 << 11, /// <summary> /// Indicates that this binder is being used to answer SemanticModel questions (i.e. not /// for batch compilation). /// </summary> /// <remarks> /// Imports touched by a binder with this flag set are not consider "used". /// </remarks> SemanticModel = 1 << 12, EarlyAttributeBinding = 1 << 13, /// <summary>Remarks, mutually exclusive with <see cref="UncheckedRegion"/>.</summary> CheckedRegion = 1 << 14, /// <summary>Remarks, mutually exclusive with <see cref="CheckedRegion"/>.</summary> UncheckedRegion = 1 << 15, // Each of these produces a different diagnostic, so we need separate flags. InLockBody = 1 << 16, // body, not the expression InCatchBlock = 1 << 17, InFinallyBlock = 1 << 18, InTryBlockOfTryCatch = 1 << 19, // try block must have at least one catch clause InCatchFilter = 1 << 20, // Indicates that this binder is inside of a finally block that is nested inside // of a catch block. This flag resets at every catch clause in the binder chain. // This flag is only used to support CS0724. Implies that InFinallyBlock and // InCatchBlock are also set. InNestedFinallyBlock = 1 << 21, IgnoreAccessibility = 1 << 22, ParameterDefaultValue = 1 << 23, /// <summary> /// In the debugger, one can take the address of a managed object. /// </summary> AllowManagedAddressOf = 1 << 24, /// <summary> /// In the debugger, the context is always unsafe, but one can still await. /// </summary> AllowAwaitInUnsafeContext = 1 << 25, /// <summary> /// Ignore duplicate types from the cor library. /// </summary> IgnoreCorLibraryDuplicatedTypes = 1 << 26, /// <summary> /// This is a <see cref="ContextualAttributeBinder"/>, or has <see cref="ContextualAttributeBinder"/> as its parent. /// </summary> InContextualAttributeBinder = 1 << 27, /// <summary> /// Are we binding for the purpose of an Expression Evaluator /// </summary> InEEMethodBinder = 1 << 28, /// <summary> /// Skip binding type arguments (we use <see cref="Symbols.PlaceholderTypeArgumentSymbol"/> instead). /// For example, currently used when type constraints are bound in some scenarios. /// </summary> SuppressTypeArgumentBinding = 1 << 29, // Groups AllClearedAtExecutableCodeBoundary = InLockBody | InCatchBlock | InCatchFilter | InFinallyBlock | InTryBlockOfTryCatch | InNestedFinallyBlock, } }
// Licensed to the .NET Foundation under one or more 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 { /// <summary> /// A specific location for binding. /// </summary> [Flags] internal enum BinderFlags : uint { None, // No specific location SuppressConstraintChecks = 1 << 0, SuppressObsoleteChecks = 1 << 1, ConstructorInitializer = 1 << 2, FieldInitializer = 1 << 3, ObjectInitializerMember = 1 << 4, // object initializer field/property access CollectionInitializerAddMethod = 1 << 5, // used for collection initializer add method overload resolution diagnostics AttributeArgument = 1 << 6, GenericConstraintsClause = 1 << 7, // "where" clause (used for cycle checking) Cref = 1 << 8, // documentation comment cref CrefParameterOrReturnType = 1 << 9, // Same as Cref, but lookup considers inherited members /// <summary> /// Indicates that the current context allows unsafe constructs. /// </summary> /// <remarks> /// NOTE: Dev10 doesn't seem to treat attributes as being within the unsafe region. /// Fortunately, not following this behavior should not be a breaking change since /// attribute arguments have to be constants and there are no constants of unsafe /// types. /// </remarks> UnsafeRegion = 1 << 10, /// <summary> /// Indicates that the unsafe diagnostics are not reported in the current context, regardless /// of whether or not it is (part of) an unsafe region. /// </summary> SuppressUnsafeDiagnostics = 1 << 11, /// <summary> /// Indicates that this binder is being used to answer SemanticModel questions (i.e. not /// for batch compilation). /// </summary> /// <remarks> /// Imports touched by a binder with this flag set are not consider "used". /// </remarks> SemanticModel = 1 << 12, EarlyAttributeBinding = 1 << 13, /// <summary>Remarks, mutually exclusive with <see cref="UncheckedRegion"/>.</summary> CheckedRegion = 1 << 14, /// <summary>Remarks, mutually exclusive with <see cref="CheckedRegion"/>.</summary> UncheckedRegion = 1 << 15, // Each of these produces a different diagnostic, so we need separate flags. InLockBody = 1 << 16, // body, not the expression InCatchBlock = 1 << 17, InFinallyBlock = 1 << 18, InTryBlockOfTryCatch = 1 << 19, // try block must have at least one catch clause InCatchFilter = 1 << 20, // Indicates that this binder is inside of a finally block that is nested inside // of a catch block. This flag resets at every catch clause in the binder chain. // This flag is only used to support CS0724. Implies that InFinallyBlock and // InCatchBlock are also set. InNestedFinallyBlock = 1 << 21, IgnoreAccessibility = 1 << 22, ParameterDefaultValue = 1 << 23, /// <summary> /// In the debugger, one can take the address of a managed object. /// </summary> AllowManagedAddressOf = 1 << 24, /// <summary> /// In the debugger, the context is always unsafe, but one can still await. /// </summary> AllowAwaitInUnsafeContext = 1 << 25, /// <summary> /// Ignore duplicate types from the cor library. /// </summary> IgnoreCorLibraryDuplicatedTypes = 1 << 26, /// <summary> /// This is a <see cref="ContextualAttributeBinder"/>, or has <see cref="ContextualAttributeBinder"/> as its parent. /// </summary> InContextualAttributeBinder = 1 << 27, /// <summary> /// Are we binding for the purpose of an Expression Evaluator /// </summary> InEEMethodBinder = 1 << 28, /// <summary> /// Skip binding type arguments (we use <see cref="Symbols.PlaceholderTypeArgumentSymbol"/> instead). /// For example, currently used when type constraints are bound in some scenarios. /// </summary> SuppressTypeArgumentBinding = 1 << 29, /// <summary> /// The current context is an expression tree /// </summary> InExpressionTree = 1 << 30, // Groups AllClearedAtExecutableCodeBoundary = InLockBody | InCatchBlock | InCatchFilter | InFinallyBlock | InTryBlockOfTryCatch | InNestedFinallyBlock, } }
1
dotnet/roslyn
55,125
Don't use DefaultInterpolatedStringHandler in expression trees
Introduces a binder flag to track whether we are currently in an expression tree or not. Fixes https://github.com/dotnet/roslyn/issues/55114.
333fred
2021-07-26T22:08:39Z
2021-07-27T19:33:24Z
5840335153dcca42570a853cdacd06d660fe9596
cfc12ce93ce377c4b9581ccf88403e6740d63977
Don't use DefaultInterpolatedStringHandler in expression trees. Introduces a binder flag to track whether we are currently in an expression tree or not. Fixes https://github.com/dotnet/roslyn/issues/55114.
./src/Compilers/CSharp/Portable/Binder/Binder_Conversions.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; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class Binder { internal BoundExpression CreateConversion( BoundExpression source, TypeSymbol destination, BindingDiagnosticBag diagnostics) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var conversion = Conversions.ClassifyConversionFromExpression(source, destination, ref useSiteInfo); diagnostics.Add(source.Syntax, useSiteInfo); return CreateConversion(source.Syntax, source, conversion, isCast: false, conversionGroupOpt: null, destination: destination, diagnostics: diagnostics); } internal BoundExpression CreateConversion( BoundExpression source, Conversion conversion, TypeSymbol destination, BindingDiagnosticBag diagnostics) { return CreateConversion(source.Syntax, source, conversion, isCast: false, conversionGroupOpt: null, destination: destination, diagnostics: diagnostics); } internal BoundExpression CreateConversion( SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroupOpt, TypeSymbol destination, BindingDiagnosticBag diagnostics) { return CreateConversion(syntax, source, conversion, isCast: isCast, conversionGroupOpt, source.WasCompilerGenerated, destination, diagnostics); } protected BoundExpression CreateConversion( SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroupOpt, bool wasCompilerGenerated, TypeSymbol destination, BindingDiagnosticBag diagnostics, bool hasErrors = false) { RoslynDebug.Assert(source != null); RoslynDebug.Assert((object)destination != null); RoslynDebug.Assert(!isCast || conversionGroupOpt != null); if (conversion.IsIdentity) { if (source is BoundTupleLiteral sourceTuple) { NamedTypeSymbol.ReportTupleNamesMismatchesIfAny(destination, sourceTuple, diagnostics); } // identity tuple and switch conversions result in a converted expression // to indicate that such conversions are no longer applicable. source = BindToNaturalType(source, diagnostics); RoslynDebug.Assert(source.Type is object); // We need to preserve any conversion that changes the type (even identity conversions, like object->dynamic), // or that was explicitly written in code (so that GetSemanticInfo can find the syntax in the bound tree). if (!isCast && source.Type.Equals(destination, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { return source; } } if (conversion.IsMethodGroup) { return CreateMethodGroupConversion(syntax, source, conversion, isCast: isCast, conversionGroupOpt, destination, diagnostics); } // Obsolete diagnostics for method group are reported as part of creating the method group conversion. ReportDiagnosticsIfObsolete(diagnostics, conversion, syntax, hasBaseReceiver: false); CheckConstraintLanguageVersionAndRuntimeSupportForConversion(syntax, conversion, diagnostics); if (conversion.IsAnonymousFunction && source.Kind == BoundKind.UnboundLambda) { return CreateAnonymousFunctionConversion(syntax, source, conversion, isCast: isCast, conversionGroupOpt, destination, diagnostics); } if (conversion.IsStackAlloc) { return CreateStackAllocConversion(syntax, source, conversion, isCast, conversionGroupOpt, destination, diagnostics); } if (conversion.IsTupleLiteralConversion || (conversion.IsNullable && conversion.UnderlyingConversions[0].IsTupleLiteralConversion)) { return CreateTupleLiteralConversion(syntax, (BoundTupleLiteral)source, conversion, isCast: isCast, conversionGroupOpt, destination, diagnostics); } if (conversion.Kind == ConversionKind.SwitchExpression) { var convertedSwitch = ConvertSwitchExpression((BoundUnconvertedSwitchExpression)source, destination, conversionIfTargetTyped: conversion, diagnostics); return new BoundConversion( syntax, convertedSwitch, conversion, CheckOverflowAtRuntime, explicitCastInCode: isCast && !wasCompilerGenerated, conversionGroupOpt, convertedSwitch.ConstantValue, destination, hasErrors); } if (conversion.Kind == ConversionKind.ConditionalExpression) { var convertedConditional = ConvertConditionalExpression((BoundUnconvertedConditionalOperator)source, destination, conversionIfTargetTyped: conversion, diagnostics); return new BoundConversion( syntax, convertedConditional, conversion, CheckOverflowAtRuntime, explicitCastInCode: isCast && !wasCompilerGenerated, conversionGroupOpt, convertedConditional.ConstantValue, destination, hasErrors); } if (conversion.Kind == ConversionKind.InterpolatedString) { var unconvertedSource = (BoundUnconvertedInterpolatedString)source; source = new BoundInterpolatedString( unconvertedSource.Syntax, interpolationData: null, BindInterpolatedStringParts(unconvertedSource, diagnostics), unconvertedSource.ConstantValue, unconvertedSource.Type, unconvertedSource.HasErrors); } if (conversion.Kind == ConversionKind.InterpolatedStringHandler) { var unconvertedSource = (BoundUnconvertedInterpolatedString)source; return new BoundConversion( syntax, BindUnconvertedInterpolatedStringToHandlerType(unconvertedSource, (NamedTypeSymbol)destination, diagnostics, isHandlerConversion: true), conversion, @checked: CheckOverflowAtRuntime, explicitCastInCode: isCast && !wasCompilerGenerated, conversionGroupOpt, constantValueOpt: null, destination); } if (source.Kind == BoundKind.UnconvertedSwitchExpression) { TypeSymbol? type = source.Type; if (type is null) { Debug.Assert(!conversion.Exists); type = CreateErrorType(); hasErrors = true; } source = ConvertSwitchExpression((BoundUnconvertedSwitchExpression)source, type, conversionIfTargetTyped: null, diagnostics, hasErrors); if (destination.Equals(type, TypeCompareKind.ConsiderEverything) && wasCompilerGenerated) { return source; } } if (conversion.IsObjectCreation) { return ConvertObjectCreationExpression(syntax, (BoundUnconvertedObjectCreationExpression)source, isCast, destination, diagnostics); } if (source.Kind == BoundKind.UnconvertedConditionalOperator) { TypeSymbol? type = source.Type; if (type is null) { Debug.Assert(!conversion.Exists); type = CreateErrorType(); hasErrors = true; } source = ConvertConditionalExpression((BoundUnconvertedConditionalOperator)source, type, conversionIfTargetTyped: null, diagnostics, hasErrors); if (destination.Equals(type, TypeCompareKind.ConsiderEverything) && wasCompilerGenerated) { return source; } } if (conversion.IsUserDefined) { // User-defined conversions are likely to be represented as multiple // BoundConversion instances so a ConversionGroup is necessary. return CreateUserDefinedConversion(syntax, source, conversion, isCast: isCast, conversionGroupOpt ?? new ConversionGroup(conversion), destination, diagnostics, hasErrors); } ConstantValue? constantValue = this.FoldConstantConversion(syntax, source, conversion, destination, diagnostics); if (conversion.Kind == ConversionKind.DefaultLiteral) { source = new BoundDefaultExpression(source.Syntax, targetType: null, constantValue, type: destination) .WithSuppression(source.IsSuppressed); } return new BoundConversion( syntax, BindToNaturalType(source, diagnostics), conversion, @checked: CheckOverflowAtRuntime, explicitCastInCode: isCast && !wasCompilerGenerated, conversionGroupOpt, constantValueOpt: constantValue, type: destination, hasErrors: hasErrors) { WasCompilerGenerated = wasCompilerGenerated }; } internal void CheckConstraintLanguageVersionAndRuntimeSupportForConversion(SyntaxNodeOrToken syntax, Conversion conversion, BindingDiagnosticBag diagnostics) { if (conversion.IsUserDefined && conversion.Method is MethodSymbol method && method.IsStatic && method.IsAbstract) { Debug.Assert(conversion.ConstrainedToTypeOpt is TypeParameterSymbol); if (Compilation.SourceModule != method.ContainingModule) { Debug.Assert(syntax.SyntaxTree is object); CheckFeatureAvailability(syntax.SyntaxTree, MessageID.IDS_FeatureStaticAbstractMembersInInterfaces, diagnostics, syntax.GetLocation()!); if (!Compilation.Assembly.RuntimeSupportsStaticAbstractMembersInInterfaces) { Error(diagnostics, ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, syntax); } } } } private BoundExpression ConvertObjectCreationExpression(SyntaxNode syntax, BoundUnconvertedObjectCreationExpression node, bool isCast, TypeSymbol destination, BindingDiagnosticBag diagnostics) { var arguments = AnalyzedArguments.GetInstance(node.Arguments, node.ArgumentRefKindsOpt, node.ArgumentNamesOpt); BoundExpression expr = BindObjectCreationExpression(node, destination.StrippedType(), arguments, diagnostics); if (destination.IsNullableType()) { // We manually create an ImplicitNullable conversion // if the destination is nullable, in which case we // target the underlying type e.g. `S? x = new();` // is actually identical to `S? x = new S();`. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var conversion = Conversions.ClassifyStandardConversion(null, expr.Type, destination, ref useSiteInfo); expr = new BoundConversion( node.Syntax, operand: expr, conversion: conversion, @checked: false, explicitCastInCode: isCast, conversionGroupOpt: new ConversionGroup(conversion), constantValueOpt: expr.ConstantValue, type: destination); diagnostics.Add(syntax, useSiteInfo); } arguments.Free(); return expr; } private BoundExpression BindObjectCreationExpression(BoundUnconvertedObjectCreationExpression node, TypeSymbol type, AnalyzedArguments arguments, BindingDiagnosticBag diagnostics) { var syntax = node.Syntax; switch (type.TypeKind) { case TypeKind.Enum: case TypeKind.Struct: case TypeKind.Class when !type.IsAnonymousType: // We don't want to enable object creation with unspeakable types return BindClassCreationExpression(syntax, type.Name, typeNode: syntax, (NamedTypeSymbol)type, arguments, diagnostics, node.InitializerOpt, wasTargetTyped: true); case TypeKind.TypeParameter: return BindTypeParameterCreationExpression(syntax, (TypeParameterSymbol)type, arguments, node.InitializerOpt, typeSyntax: syntax, diagnostics); case TypeKind.Delegate: return BindDelegateCreationExpression(syntax, (NamedTypeSymbol)type, arguments, node.InitializerOpt, diagnostics); case TypeKind.Interface: return BindInterfaceCreationExpression(syntax, (NamedTypeSymbol)type, diagnostics, typeNode: syntax, arguments, node.InitializerOpt, wasTargetTyped: true); case TypeKind.Array: case TypeKind.Class: case TypeKind.Dynamic: Error(diagnostics, ErrorCode.ERR_ImplicitObjectCreationIllegalTargetType, syntax, type); goto case TypeKind.Error; case TypeKind.Pointer: case TypeKind.FunctionPointer: Error(diagnostics, ErrorCode.ERR_UnsafeTypeInObjectCreation, syntax, type); goto case TypeKind.Error; case TypeKind.Error: return MakeBadExpressionForObjectCreation(syntax, type, arguments, node.InitializerOpt, typeSyntax: syntax, diagnostics); case var v: throw ExceptionUtilities.UnexpectedValue(v); } } /// <summary> /// Rewrite the subexpressions in a conditional expression to convert the whole thing to the destination type. /// </summary> private BoundExpression ConvertConditionalExpression( BoundUnconvertedConditionalOperator source, TypeSymbol destination, Conversion? conversionIfTargetTyped, BindingDiagnosticBag diagnostics, bool hasErrors = false) { bool targetTyped = conversionIfTargetTyped is { }; Debug.Assert(targetTyped || destination.IsErrorType() || destination.Equals(source.Type, TypeCompareKind.ConsiderEverything)); ImmutableArray<Conversion> underlyingConversions = conversionIfTargetTyped.GetValueOrDefault().UnderlyingConversions; var condition = source.Condition; hasErrors |= source.HasErrors || destination.IsErrorType(); var trueExpr = targetTyped ? CreateConversion(source.Consequence.Syntax, source.Consequence, underlyingConversions[0], isCast: false, conversionGroupOpt: null, destination, diagnostics) : GenerateConversionForAssignment(destination, source.Consequence, diagnostics); var falseExpr = targetTyped ? CreateConversion(source.Alternative.Syntax, source.Alternative, underlyingConversions[1], isCast: false, conversionGroupOpt: null, destination, diagnostics) : GenerateConversionForAssignment(destination, source.Alternative, diagnostics); var constantValue = FoldConditionalOperator(condition, trueExpr, falseExpr); hasErrors |= constantValue?.IsBad == true; if (targetTyped && !destination.IsErrorType() && !Compilation.IsFeatureEnabled(MessageID.IDS_FeatureTargetTypedConditional)) { diagnostics.Add( ErrorCode.ERR_NoImplicitConvTargetTypedConditional, source.Syntax.Location, Compilation.LanguageVersion.ToDisplayString(), source.Consequence.Display, source.Alternative.Display, new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureTargetTypedConditional.RequiredVersion())); } return new BoundConditionalOperator(source.Syntax, isRef: false, condition, trueExpr, falseExpr, constantValue, source.Type, wasTargetTyped: targetTyped, destination, hasErrors) .WithSuppression(source.IsSuppressed); } /// <summary> /// Rewrite the expressions in the switch expression arms to add a conversion to the destination type. /// </summary> private BoundExpression ConvertSwitchExpression(BoundUnconvertedSwitchExpression source, TypeSymbol destination, Conversion? conversionIfTargetTyped, BindingDiagnosticBag diagnostics, bool hasErrors = false) { bool targetTyped = conversionIfTargetTyped is { }; Conversion conversion = conversionIfTargetTyped ?? Conversion.Identity; Debug.Assert(targetTyped || destination.IsErrorType() || destination.Equals(source.Type, TypeCompareKind.ConsiderEverything)); ImmutableArray<Conversion> underlyingConversions = conversion.UnderlyingConversions; var builder = ArrayBuilder<BoundSwitchExpressionArm>.GetInstance(source.SwitchArms.Length); for (int i = 0, n = source.SwitchArms.Length; i < n; i++) { var oldCase = source.SwitchArms[i]; Debug.Assert(oldCase.Syntax is SwitchExpressionArmSyntax); var binder = GetRequiredBinder(oldCase.Syntax); var oldValue = oldCase.Value; var newValue = targetTyped ? binder.CreateConversion(oldValue.Syntax, oldValue, underlyingConversions[i], isCast: false, conversionGroupOpt: null, destination, diagnostics) : binder.GenerateConversionForAssignment(destination, oldValue, diagnostics); var newCase = (oldValue == newValue) ? oldCase : new BoundSwitchExpressionArm(oldCase.Syntax, oldCase.Locals, oldCase.Pattern, oldCase.WhenClause, newValue, oldCase.Label, oldCase.HasErrors); builder.Add(newCase); } var newSwitchArms = builder.ToImmutableAndFree(); return new BoundConvertedSwitchExpression( source.Syntax, source.Type, targetTyped, conversion, source.Expression, newSwitchArms, source.DecisionDag, source.DefaultLabel, source.ReportedNotExhaustive, destination, hasErrors || source.HasErrors); } private BoundExpression CreateUserDefinedConversion( SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics, bool hasErrors) { Debug.Assert(conversionGroup != null); Debug.Assert(conversion.IsUserDefined); if (!conversion.IsValid) { if (!hasErrors) GenerateImplicitConversionError(diagnostics, syntax, conversion, source, destination); return new BoundConversion( syntax, source, conversion, CheckOverflowAtRuntime, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: destination, hasErrors: true) { WasCompilerGenerated = source.WasCompilerGenerated }; } // Due to an oddity in the way we create a non-lifted user-defined conversion from A to D? // (required backwards compatibility with the native compiler) we can end up in a situation // where we have: // a standard conversion from A to B? // then a standard conversion from B? to B // then a user-defined conversion from B to C // then a standard conversion from C to C? // then a standard conversion from C? to D? // // In that scenario, the "from type" of the conversion will be B? and the "from conversion" will be // from A to B?. Similarly the "to type" of the conversion will be C? and the "to conversion" // of the conversion will be from C? to D?. // // Therefore, we might need to introduce an extra conversion on the source side, from B? to B. // Now, you might think we should also introduce an extra conversion on the destination side, // from C to C?. But that then gives us the following bad situation: If we in fact bind this as // // (D?)(C?)(C)(B)(B?)(A)x // // then what we are in effect doing is saying "convert C? to D? by checking for null, unwrapping, // converting C to D, and then wrapping". But we know that the C? will never be null. In this case // we should actually generate // // (D?)(C)(B)(B?)(A)x // // And thereby skip the unnecessary nullable conversion. Debug.Assert(conversion.BestUserDefinedConversionAnalysis is object); // All valid user-defined conversions have this populated // Original expression --> conversion's "from" type BoundExpression convertedOperand = CreateConversion( syntax: source.Syntax, source: source, conversion: conversion.UserDefinedFromConversion, isCast: false, conversionGroupOpt: conversionGroup, wasCompilerGenerated: false, destination: conversion.BestUserDefinedConversionAnalysis.FromType, diagnostics: diagnostics); TypeSymbol conversionParameterType = conversion.BestUserDefinedConversionAnalysis.Operator.GetParameterType(0); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if (conversion.BestUserDefinedConversionAnalysis.Kind == UserDefinedConversionAnalysisKind.ApplicableInNormalForm && !TypeSymbol.Equals(conversion.BestUserDefinedConversionAnalysis.FromType, conversionParameterType, TypeCompareKind.ConsiderEverything2)) { // Conversion's "from" type --> conversion method's parameter type. convertedOperand = CreateConversion( syntax: syntax, source: convertedOperand, conversion: Conversions.ClassifyStandardConversion(null, convertedOperand.Type, conversionParameterType, ref useSiteInfo), isCast: false, conversionGroupOpt: conversionGroup, wasCompilerGenerated: true, destination: conversionParameterType, diagnostics: diagnostics); } BoundExpression userDefinedConversion; TypeSymbol conversionReturnType = conversion.BestUserDefinedConversionAnalysis.Operator.ReturnType; TypeSymbol conversionToType = conversion.BestUserDefinedConversionAnalysis.ToType; Conversion toConversion = conversion.UserDefinedToConversion; if (conversion.BestUserDefinedConversionAnalysis.Kind == UserDefinedConversionAnalysisKind.ApplicableInNormalForm && !TypeSymbol.Equals(conversionToType, conversionReturnType, TypeCompareKind.ConsiderEverything2)) { // Conversion method's parameter type --> conversion method's return type // NB: not calling CreateConversion here because this is the recursive base case. userDefinedConversion = new BoundConversion( syntax, convertedOperand, conversion, @checked: false, // There are no checked user-defined conversions, but the conversions on either side might be checked. explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: conversionReturnType) { WasCompilerGenerated = true }; if (conversionToType.IsNullableType() && TypeSymbol.Equals(conversionToType.GetNullableUnderlyingType(), conversionReturnType, TypeCompareKind.ConsiderEverything2)) { // Skip introducing the conversion from C to C?. The "to" conversion is now wrong though, // because it will still assume converting C? to D?. toConversion = Conversions.ClassifyConversionFromType(conversionReturnType, destination, ref useSiteInfo); Debug.Assert(toConversion.Exists); } else { // Conversion method's return type --> conversion's "to" type userDefinedConversion = CreateConversion( syntax: syntax, source: userDefinedConversion, conversion: Conversions.ClassifyStandardConversion(null, conversionReturnType, conversionToType, ref useSiteInfo), isCast: false, conversionGroupOpt: conversionGroup, wasCompilerGenerated: true, destination: conversionToType, diagnostics: diagnostics); } } else { // Conversion method's parameter type --> conversion method's "to" type // NB: not calling CreateConversion here because this is the recursive base case. userDefinedConversion = new BoundConversion( syntax, convertedOperand, conversion, @checked: false, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: conversionToType) { WasCompilerGenerated = true }; } diagnostics.Add(syntax, useSiteInfo); // Conversion's "to" type --> final type BoundExpression finalConversion = CreateConversion( syntax: syntax, source: userDefinedConversion, conversion: toConversion, isCast: false, conversionGroupOpt: conversionGroup, wasCompilerGenerated: true, // NOTE: doesn't necessarily set flag on resulting bound expression. destination: destination, diagnostics: diagnostics); finalConversion.ResetCompilerGenerated(source.WasCompilerGenerated); return finalConversion; } private BoundExpression CreateAnonymousFunctionConversion(SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics) { // We have a successful anonymous function conversion; rather than producing a node // which is a conversion on top of an unbound lambda, replace it with the bound // lambda. // UNDONE: Figure out what to do about the error case, where a lambda // UNDONE: is converted to a delegate that does not match. What to surface then? var unboundLambda = (UnboundLambda)source; if (destination.SpecialType == SpecialType.System_Delegate || destination.IsNonGenericExpressionType()) { CheckFeatureAvailability(syntax, MessageID.IDS_FeatureInferredDelegateType, diagnostics); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var delegateType = unboundLambda.InferDelegateType(ref useSiteInfo); BoundLambda boundLambda; if (delegateType is { }) { if (destination.IsNonGenericExpressionType()) { delegateType = Compilation.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression_T).Construct(delegateType); delegateType.AddUseSiteInfo(ref useSiteInfo); } boundLambda = unboundLambda.Bind(delegateType); } else { diagnostics.Add(ErrorCode.ERR_CannotInferDelegateType, syntax.GetLocation()); delegateType = CreateErrorType(); boundLambda = unboundLambda.BindForErrorRecovery(); } diagnostics.AddRange(boundLambda.Diagnostics); var expr = createAnonymousFunctionConversion(syntax, source, boundLambda, conversion, isCast, conversionGroup, delegateType); conversion = Conversions.ClassifyConversionFromExpression(expr, destination, ref useSiteInfo); diagnostics.Add(syntax, useSiteInfo); return CreateConversion(syntax, expr, conversion, isCast, conversionGroup, destination, diagnostics); } else { #if DEBUG // Test inferring a delegate type for all callers. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; _ = unboundLambda.InferDelegateType(ref discardedUseSiteInfo); #endif var boundLambda = unboundLambda.Bind((NamedTypeSymbol)destination); diagnostics.AddRange(boundLambda.Diagnostics); return createAnonymousFunctionConversion(syntax, source, boundLambda, conversion, isCast, conversionGroup, destination); } static BoundConversion createAnonymousFunctionConversion(SyntaxNode syntax, BoundExpression source, BoundLambda boundLambda, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination) { return new BoundConversion( syntax, boundLambda, conversion, @checked: false, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: destination) { WasCompilerGenerated = source.WasCompilerGenerated }; } } private BoundExpression CreateMethodGroupConversion(SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics) { var (originalGroup, isAddressOf) = source switch { BoundMethodGroup m => (m, false), BoundUnconvertedAddressOfOperator { Operand: { } m } => (m, true), _ => throw ExceptionUtilities.UnexpectedValue(source), }; BoundMethodGroup group = FixMethodGroupWithTypeOrValue(originalGroup, conversion, diagnostics); bool hasErrors = false; if (MethodGroupConversionHasErrors(syntax, conversion, group.ReceiverOpt, conversion.IsExtensionMethod, isAddressOf, destination, diagnostics)) { hasErrors = true; } if (destination.SpecialType == SpecialType.System_Delegate) { CheckFeatureAvailability(syntax, MessageID.IDS_FeatureInferredDelegateType, diagnostics); // https://github.com/dotnet/roslyn/issues/52869: Avoid calculating the delegate type multiple times during conversion. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var delegateType = GetMethodGroupDelegateType(group, ref useSiteInfo); var expr = createMethodGroupConversion(syntax, group, conversion, isCast, conversionGroup, delegateType!, hasErrors); conversion = Conversions.ClassifyConversionFromExpression(expr, destination, ref useSiteInfo); diagnostics.Add(syntax, useSiteInfo); return CreateConversion(syntax, expr, conversion, isCast, conversionGroup, destination, diagnostics); } #if DEBUG // Test inferring a delegate type for all callers. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; _ = GetMethodGroupDelegateType(group, ref discardedUseSiteInfo); #endif return createMethodGroupConversion(syntax, group, conversion, isCast, conversionGroup, destination, hasErrors); static BoundConversion createMethodGroupConversion(SyntaxNode syntax, BoundMethodGroup group, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, bool hasErrors) { return new BoundConversion(syntax, group, conversion, @checked: false, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: destination, hasErrors: hasErrors) { WasCompilerGenerated = group.WasCompilerGenerated }; } } private BoundExpression CreateStackAllocConversion(SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics) { Debug.Assert(conversion.IsStackAlloc); var boundStackAlloc = (BoundStackAllocArrayCreation)source; var elementType = boundStackAlloc.ElementType; TypeSymbol stackAllocType; switch (conversion.Kind) { case ConversionKind.StackAllocToPointerType: ReportUnsafeIfNotAllowed(syntax.Location, diagnostics); stackAllocType = new PointerTypeSymbol(TypeWithAnnotations.Create(elementType)); break; case ConversionKind.StackAllocToSpanType: CheckFeatureAvailability(syntax, MessageID.IDS_FeatureRefStructs, diagnostics); stackAllocType = Compilation.GetWellKnownType(WellKnownType.System_Span_T).Construct(elementType); break; default: throw ExceptionUtilities.UnexpectedValue(conversion.Kind); } var convertedNode = new BoundConvertedStackAllocExpression(syntax, elementType, boundStackAlloc.Count, boundStackAlloc.InitializerOpt, stackAllocType, boundStackAlloc.HasErrors); var underlyingConversion = conversion.UnderlyingConversions.Single(); return CreateConversion(syntax, convertedNode, underlyingConversion, isCast: isCast, conversionGroup, destination, diagnostics); } private BoundExpression CreateTupleLiteralConversion(SyntaxNode syntax, BoundTupleLiteral sourceTuple, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics) { // We have a successful tuple conversion; rather than producing a separate conversion node // which is a conversion on top of a tuple literal, tuple conversion is an element-wise conversion of arguments. Debug.Assert(conversion.IsNullable == destination.IsNullableType()); var destinationWithoutNullable = destination; var conversionWithoutNullable = conversion; if (conversion.IsNullable) { destinationWithoutNullable = destination.GetNullableUnderlyingType(); conversionWithoutNullable = conversion.UnderlyingConversions[0]; } Debug.Assert(conversionWithoutNullable.IsTupleLiteralConversion); NamedTypeSymbol targetType = (NamedTypeSymbol)destinationWithoutNullable; if (targetType.IsTupleType) { NamedTypeSymbol.ReportTupleNamesMismatchesIfAny(targetType, sourceTuple, diagnostics); // do not lose the original element names and locations in the literal if different from names in the target // // the tuple has changed the type of elements due to target-typing, // but element names has not changed and locations of their declarations // should not be confused with element locations on the target type. if (sourceTuple.Type is NamedTypeSymbol { IsTupleType: true } sourceType) { targetType = targetType.WithTupleDataFrom(sourceType); } else { var tupleSyntax = (TupleExpressionSyntax)sourceTuple.Syntax; var locationBuilder = ArrayBuilder<Location?>.GetInstance(); foreach (var argument in tupleSyntax.Arguments) { locationBuilder.Add(argument.NameColon?.Name.Location); } targetType = targetType.WithElementNames(sourceTuple.ArgumentNamesOpt!, locationBuilder.ToImmutableAndFree(), errorPositions: default, ImmutableArray.Create(tupleSyntax.Location)); } } var arguments = sourceTuple.Arguments; var convertedArguments = ArrayBuilder<BoundExpression>.GetInstance(arguments.Length); var targetElementTypes = targetType.TupleElementTypesWithAnnotations; Debug.Assert(targetElementTypes.Length == arguments.Length, "converting a tuple literal to incompatible type?"); var underlyingConversions = conversionWithoutNullable.UnderlyingConversions; for (int i = 0; i < arguments.Length; i++) { var argument = arguments[i]; var destType = targetElementTypes[i]; var elementConversion = underlyingConversions[i]; var elementConversionGroup = isCast ? new ConversionGroup(elementConversion, destType) : null; convertedArguments.Add(CreateConversion(argument.Syntax, argument, elementConversion, isCast: isCast, elementConversionGroup, destType.Type, diagnostics)); } BoundExpression result = new BoundConvertedTupleLiteral( sourceTuple.Syntax, sourceTuple, wasTargetTyped: true, convertedArguments.ToImmutableAndFree(), sourceTuple.ArgumentNamesOpt, sourceTuple.InferredNamesOpt, targetType).WithSuppression(sourceTuple.IsSuppressed); if (!TypeSymbol.Equals(sourceTuple.Type, destination, TypeCompareKind.ConsiderEverything2)) { // literal cast is applied to the literal result = new BoundConversion( sourceTuple.Syntax, result, conversion, @checked: false, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: destination); } // If we had a cast in the code, keep conversion in the tree. // even though the literal is already converted to the target type. if (isCast) { result = new BoundConversion( syntax, result, Conversion.Identity, @checked: false, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: destination); } return result; } private static bool IsMethodGroupWithTypeOrValueReceiver(BoundNode node) { if (node.Kind != BoundKind.MethodGroup) { return false; } return Binder.IsTypeOrValueExpression(((BoundMethodGroup)node).ReceiverOpt); } private BoundMethodGroup FixMethodGroupWithTypeOrValue(BoundMethodGroup group, Conversion conversion, BindingDiagnosticBag diagnostics) { if (!IsMethodGroupWithTypeOrValueReceiver(group)) { return group; } BoundExpression? receiverOpt = group.ReceiverOpt; RoslynDebug.Assert(receiverOpt != null); receiverOpt = ReplaceTypeOrValueReceiver(receiverOpt, useType: conversion.Method?.RequiresInstanceReceiver == false && !conversion.IsExtensionMethod, diagnostics); return group.Update( group.TypeArgumentsOpt, group.Name, group.Methods, group.LookupSymbolOpt, group.LookupError, group.Flags, receiverOpt, //only change group.ResultKind); } /// <summary> /// This method implements the algorithm in spec section 7.6.5.1. /// /// For method group conversions, there are situations in which the conversion is /// considered to exist ("Otherwise the algorithm produces a single best method M having /// the same number of parameters as D and the conversion is considered to exist"), but /// application of the conversion fails. These are the "final validation" steps of /// overload resolution. /// </summary> /// <returns> /// True if there is any error, except lack of runtime support errors. /// </returns> private bool MemberGroupFinalValidation(BoundExpression? receiverOpt, MethodSymbol methodSymbol, SyntaxNode node, BindingDiagnosticBag diagnostics, bool invokedAsExtensionMethod) { if (!IsBadBaseAccess(node, receiverOpt, methodSymbol, diagnostics)) { CheckReceiverAndRuntimeSupportForSymbolAccess(node, receiverOpt, methodSymbol, diagnostics); } if (MemberGroupFinalValidationAccessibilityChecks(receiverOpt, methodSymbol, node, diagnostics, invokedAsExtensionMethod)) { return true; } // SPEC: If the best method is a generic method, the type arguments (supplied or inferred) are checked against the constraints // SPEC: declared on the generic method. If any type argument does not satisfy the corresponding constraint(s) on // SPEC: the type parameter, a binding-time error occurs. // The portion of the overload resolution spec quoted above is subtle and somewhat // controversial. The upshot of this is that overload resolution does not consider // constraints to be a part of the signature. Overload resolution matches arguments to // parameter lists; it does not consider things which are outside of the parameter list. // If the best match from the arguments to the formal parameters is not viable then we // give an error rather than falling back to a worse match. // // Consider the following: // // void M<T>(T t) where T : Reptile {} // void M(object x) {} // ... // M(new Giraffe()); // // The correct analysis is to determine that the applicable candidates are // M<Giraffe>(Giraffe) and M(object). Overload resolution then chooses the former // because it is an exact match, over the latter which is an inexact match. Only after // the best method is determined do we check the constraints and discover that the // constraint on T has been violated. // // Note that this is different from the rule that says that during type inference, if an // inference violates a constraint then inference fails. For example: // // class C<T> where T : struct {} // ... // void M<U>(U u, C<U> c){} // void M(object x, object y) {} // ... // M("hello", null); // // Type inference determines that U is string, but since C<string> is not a valid type // because of the constraint, type inference fails. M<string> is never added to the // applicable candidate set, so the applicable candidate set consists solely of // M(object, object) and is therefore the best match. return !methodSymbol.CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(this.Compilation, this.Conversions, includeNullability: false, node.Location, diagnostics)); } /// <summary> /// Performs the following checks: /// /// Spec 7.6.5: Invocation expressions (definition of Final Validation) /// The method is validated in the context of the method group: If the best method is a static method, /// the method group must have resulted from a simple-name or a member-access through a type. If the best /// method is an instance method, the method group must have resulted from a simple-name, a member-access /// through a variable or value, or a base-access. If neither of these requirements is true, a binding-time /// error occurs. /// (Note that the spec omits to mention, in the case of an instance method invoked through a simple name, that /// the invocation must appear within the body of an instance method) /// /// Spec 7.5.4: Compile-time checking of dynamic overload resolution /// If F is a static method, the method group must have resulted from a simple-name, a member-access through a type, /// or a member-access whose receiver can't be classified as a type or value until after overload resolution (see §7.6.4.1). /// If F is an instance method, the method group must have resulted from a simple-name, a member-access through a variable or value, /// or a member-access whose receiver can't be classified as a type or value until after overload resolution (see §7.6.4.1). /// </summary> /// <returns> /// True if there is any error. /// </returns> private bool MemberGroupFinalValidationAccessibilityChecks(BoundExpression? receiverOpt, Symbol memberSymbol, SyntaxNode node, BindingDiagnosticBag diagnostics, bool invokedAsExtensionMethod) { // Perform final validation of the method to be invoked. Debug.Assert(memberSymbol.Kind != SymbolKind.Method || memberSymbol.CanBeReferencedByName); //note that the same assert does not hold for all properties. Some properties and (all indexers) are not referenceable by name, yet //their binding brings them through here, perhaps needlessly. if (IsTypeOrValueExpression(receiverOpt)) { // TypeOrValue expression isn't replaced only if the invocation is late bound, in which case it can't be extension method. // None of the checks below apply if the receiver can't be classified as a type or value. Debug.Assert(!invokedAsExtensionMethod); } else if (!memberSymbol.RequiresInstanceReceiver()) { Debug.Assert(!invokedAsExtensionMethod || (receiverOpt != null)); if (invokedAsExtensionMethod) { if (IsMemberAccessedThroughType(receiverOpt)) { if (receiverOpt.Kind == BoundKind.QueryClause) { RoslynDebug.Assert(receiverOpt.Type is object); // Could not find an implementation of the query pattern for source type '{0}'. '{1}' not found. diagnostics.Add(ErrorCode.ERR_QueryNoProvider, node.Location, receiverOpt.Type, memberSymbol.Name); } else { // An object reference is required for the non-static field, method, or property '{0}' diagnostics.Add(ErrorCode.ERR_ObjectRequired, node.Location, memberSymbol); } return true; } } else if (!WasImplicitReceiver(receiverOpt) && IsMemberAccessedThroughVariableOrValue(receiverOpt)) { if (this.Flags.Includes(BinderFlags.CollectionInitializerAddMethod)) { diagnostics.Add(ErrorCode.ERR_InitializerAddHasWrongSignature, node.Location, memberSymbol); } else if (node.Kind() == SyntaxKind.AwaitExpression && memberSymbol.Name == WellKnownMemberNames.GetAwaiter) { RoslynDebug.Assert(receiverOpt.Type is object); diagnostics.Add(ErrorCode.ERR_BadAwaitArg, node.Location, receiverOpt.Type); } else { diagnostics.Add(ErrorCode.ERR_ObjectProhibited, node.Location, memberSymbol); } return true; } } else if (IsMemberAccessedThroughType(receiverOpt)) { diagnostics.Add(ErrorCode.ERR_ObjectRequired, node.Location, memberSymbol); return true; } else if (WasImplicitReceiver(receiverOpt)) { if (InFieldInitializer && !ContainingType!.IsScriptClass || InConstructorInitializer || InAttributeArgument) { SyntaxNode errorNode = node; if (node.Parent != null && node.Parent.Kind() == SyntaxKind.InvocationExpression) { errorNode = node.Parent; } ErrorCode code = InFieldInitializer ? ErrorCode.ERR_FieldInitRefNonstatic : ErrorCode.ERR_ObjectRequired; diagnostics.Add(code, errorNode.Location, memberSymbol); return true; } // If we could access the member through implicit "this" the receiver would be a BoundThisReference. // If it is null it means that the instance member is inaccessible. if (receiverOpt == null || ContainingMember().IsStatic) { Error(diagnostics, ErrorCode.ERR_ObjectRequired, node, memberSymbol); return true; } } var containingType = this.ContainingType; if (containingType is object) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); bool isAccessible = this.IsSymbolAccessibleConditional(memberSymbol.GetTypeOrReturnType().Type, containingType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!isAccessible) { // In the presence of non-transitive [InternalsVisibleTo] in source, or obnoxious symbols from metadata, it is possible // to select a method through overload resolution in which the type is not accessible. In this case a method cannot // be called through normal IL, so we give an error. Neither [InternalsVisibleTo] nor the need for this diagnostic is // described by the language specification. // // Dev11 perform different access checks. See bug #530360 and tests AccessCheckTests.InaccessibleReturnType. Error(diagnostics, ErrorCode.ERR_BadAccess, node, memberSymbol); return true; } } return false; } private static bool IsMemberAccessedThroughVariableOrValue(BoundExpression? receiverOpt) { if (receiverOpt == null) { return false; } return !IsMemberAccessedThroughType(receiverOpt); } internal static bool IsMemberAccessedThroughType([NotNullWhen(true)] BoundExpression? receiverOpt) { if (receiverOpt == null) { return false; } while (receiverOpt.Kind == BoundKind.QueryClause) { receiverOpt = ((BoundQueryClause)receiverOpt).Value; } return receiverOpt.Kind == BoundKind.TypeExpression; } /// <summary> /// Was the receiver expression compiler-generated? /// </summary> internal static bool WasImplicitReceiver([NotNullWhen(false)] BoundExpression? receiverOpt) { if (receiverOpt == null) return true; if (!receiverOpt.WasCompilerGenerated) return false; switch (receiverOpt.Kind) { case BoundKind.ThisReference: case BoundKind.HostObjectMemberReference: case BoundKind.PreviousSubmissionReference: return true; default: return false; } } /// <summary> /// This method implements the checks in spec section 15.2. /// </summary> internal bool MethodIsCompatibleWithDelegateOrFunctionPointer(BoundExpression? receiverOpt, bool isExtensionMethod, MethodSymbol method, TypeSymbol delegateType, Location errorLocation, BindingDiagnosticBag diagnostics) { Debug.Assert(delegateType is NamedTypeSymbol { TypeKind: TypeKind.Delegate, DelegateInvokeMethod: { HasUseSiteError: false } } || delegateType.TypeKind == TypeKind.FunctionPointer, "This method should only be called for valid delegate or function pointer types."); MethodSymbol delegateOrFuncPtrMethod = delegateType switch { NamedTypeSymbol { DelegateInvokeMethod: { } invokeMethod } => invokeMethod, FunctionPointerTypeSymbol { Signature: { } signature } => signature, _ => throw ExceptionUtilities.UnexpectedValue(delegateType), }; Debug.Assert(!isExtensionMethod || (receiverOpt != null)); // - Argument types "match", and var delegateOrFuncPtrParameters = delegateOrFuncPtrMethod.Parameters; var methodParameters = method.Parameters; int numParams = delegateOrFuncPtrParameters.Length; if (methodParameters.Length != numParams + (isExtensionMethod ? 1 : 0)) { // This can happen if "method" has optional parameters. Debug.Assert(methodParameters.Length > numParams + (isExtensionMethod ? 1 : 0)); Error(diagnostics, getMethodMismatchErrorCode(delegateType.TypeKind), errorLocation, method, delegateType); return false; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); // If this is an extension method delegate, the caller should have verified the // receiver is compatible with the "this" parameter of the extension method. Debug.Assert(!isExtensionMethod || (Conversions.ConvertExtensionMethodThisArg(methodParameters[0].Type, receiverOpt!.Type, ref useSiteInfo).Exists && useSiteInfo.Diagnostics.IsNullOrEmpty())); useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(useSiteInfo); for (int i = 0; i < numParams; i++) { var delegateParameter = delegateOrFuncPtrParameters[i]; var methodParameter = methodParameters[isExtensionMethod ? i + 1 : i]; // The delegate compatibility checks are stricter than the checks on applicable functions: it's possible // to get here with a method that, while all the parameters are applicable, is not actually delegate // compatible. This is because the Applicable function member spec requires that: // * Every value parameter (non-ref or similar) from the delegate type has an implicit conversion to the corresponding // target parameter // * Every ref or similar parameter has an identity conversion to the corresponding target parameter // However, the delegate compatibility requirements are stricter: // * Every value parameter (non-ref or similar) from the delegate type has an implicit _reference_ conversion to the // corresponding target parameter. // * Every ref or similar parameter has an identity conversion to the corresponding target parameter // Note the addition of the reference requirement: it means that for delegate type void D(int i), void M(long l) is // _applicable_, but not _compatible_. if (!hasConversion(delegateType.TypeKind, Conversions, delegateParameter.Type, methodParameter.Type, delegateParameter.RefKind, methodParameter.RefKind, ref useSiteInfo)) { // No overload for '{0}' matches delegate '{1}' Error(diagnostics, getMethodMismatchErrorCode(delegateType.TypeKind), errorLocation, method, delegateType); diagnostics.Add(errorLocation, useSiteInfo); return false; } } if (delegateOrFuncPtrMethod.RefKind != method.RefKind) { Error(diagnostics, getRefMismatchErrorCode(delegateType.TypeKind), errorLocation, method, delegateType); diagnostics.Add(errorLocation, useSiteInfo); return false; } var methodReturnType = method.ReturnType; var delegateReturnType = delegateOrFuncPtrMethod.ReturnType; bool returnsMatch = delegateOrFuncPtrMethod switch { { RefKind: RefKind.None, ReturnsVoid: true } => method.ReturnsVoid, { RefKind: var destinationRefKind } => hasConversion(delegateType.TypeKind, Conversions, methodReturnType, delegateReturnType, method.RefKind, destinationRefKind, ref useSiteInfo), }; if (!returnsMatch) { Error(diagnostics, ErrorCode.ERR_BadRetType, errorLocation, method, method.ReturnType); diagnostics.Add(errorLocation, useSiteInfo); return false; } if (delegateType.IsFunctionPointer()) { if (isExtensionMethod) { Error(diagnostics, ErrorCode.ERR_CannotUseReducedExtensionMethodInAddressOf, errorLocation); diagnostics.Add(errorLocation, useSiteInfo); return false; } if (!method.IsStatic) { // This check is here purely for completeness of implementing the spec. It should // never be hit, as static methods should be eliminated as candidates in overload // resolution and should never make it to this point. Debug.Fail("This method should have been eliminated in overload resolution!"); Error(diagnostics, ErrorCode.ERR_FuncPtrMethMustBeStatic, errorLocation, method); diagnostics.Add(errorLocation, useSiteInfo); return false; } } diagnostics.Add(errorLocation, useSiteInfo); return true; static bool hasConversion(TypeKind targetKind, Conversions conversions, TypeSymbol source, TypeSymbol destination, RefKind sourceRefKind, RefKind destinationRefKind, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (sourceRefKind != destinationRefKind) { return false; } if (sourceRefKind != RefKind.None) { return ConversionsBase.HasIdentityConversion(source, destination); } if (conversions.HasIdentityOrImplicitReferenceConversion(source, destination, ref useSiteInfo)) { return true; } return targetKind == TypeKind.FunctionPointer && (ConversionsBase.HasImplicitPointerToVoidConversion(source, destination) || conversions.HasImplicitPointerConversion(source, destination, ref useSiteInfo)); } static ErrorCode getMethodMismatchErrorCode(TypeKind type) => type switch { TypeKind.Delegate => ErrorCode.ERR_MethDelegateMismatch, TypeKind.FunctionPointer => ErrorCode.ERR_MethFuncPtrMismatch, _ => throw ExceptionUtilities.UnexpectedValue(type) }; static ErrorCode getRefMismatchErrorCode(TypeKind type) => type switch { TypeKind.Delegate => ErrorCode.ERR_DelegateRefMismatch, TypeKind.FunctionPointer => ErrorCode.ERR_FuncPtrRefMismatch, _ => throw ExceptionUtilities.UnexpectedValue(type) }; } /// <summary> /// This method combines final validation (section 7.6.5.1) and delegate compatibility (section 15.2). /// </summary> /// <param name="syntax">CSharpSyntaxNode of the expression requiring method group conversion.</param> /// <param name="conversion">Conversion to be performed.</param> /// <param name="receiverOpt">Optional receiver.</param> /// <param name="isExtensionMethod">Method invoked as extension method.</param> /// <param name="delegateOrFuncPtrType">Target delegate type.</param> /// <param name="diagnostics">Where diagnostics should be added.</param> /// <returns>True if a diagnostic has been added.</returns> private bool MethodGroupConversionHasErrors( SyntaxNode syntax, Conversion conversion, BoundExpression? receiverOpt, bool isExtensionMethod, bool isAddressOf, TypeSymbol delegateOrFuncPtrType, BindingDiagnosticBag diagnostics) { Debug.Assert(delegateOrFuncPtrType.SpecialType == SpecialType.System_Delegate || delegateOrFuncPtrType.TypeKind == TypeKind.Delegate || delegateOrFuncPtrType.TypeKind == TypeKind.FunctionPointer); Debug.Assert(conversion.Method is object); MethodSymbol selectedMethod = conversion.Method; var location = syntax.Location; if (delegateOrFuncPtrType.SpecialType != SpecialType.System_Delegate) { if (!MethodIsCompatibleWithDelegateOrFunctionPointer(receiverOpt, isExtensionMethod, selectedMethod, delegateOrFuncPtrType, location, diagnostics) || MemberGroupFinalValidation(receiverOpt, selectedMethod, syntax, diagnostics, isExtensionMethod)) { return true; } } if (selectedMethod.IsConditional) { // CS1618: Cannot create delegate with '{0}' because it has a Conditional attribute Error(diagnostics, ErrorCode.ERR_DelegateOnConditional, location, selectedMethod); return true; } var sourceMethod = selectedMethod as SourceOrdinaryMethodSymbol; if (sourceMethod is object && sourceMethod.IsPartialWithoutImplementation) { // CS0762: Cannot create delegate from method '{0}' because it is a partial method without an implementing declaration Error(diagnostics, ErrorCode.ERR_PartialMethodToDelegate, location, selectedMethod); return true; } if ((selectedMethod.HasUnsafeParameter() || selectedMethod.ReturnType.IsUnsafe()) && ReportUnsafeIfNotAllowed(syntax, diagnostics)) { return true; } if (!isAddressOf) { ReportDiagnosticsIfUnmanagedCallersOnly(diagnostics, selectedMethod, location, isDelegateConversion: true); } ReportDiagnosticsIfObsolete(diagnostics, selectedMethod, syntax, hasBaseReceiver: false); // No use site errors, but there could be use site warnings. // If there are use site warnings, they were reported during the overload resolution process // that chose selectedMethod. Debug.Assert(!selectedMethod.HasUseSiteError, "Shouldn't have reached this point if there were use site errors."); return false; } /// <summary> /// This method is a wrapper around MethodGroupConversionHasErrors. As a preliminary step, /// it checks whether a conversion exists. /// </summary> private bool MethodGroupConversionDoesNotExistOrHasErrors( BoundMethodGroup boundMethodGroup, NamedTypeSymbol delegateType, Location delegateMismatchLocation, BindingDiagnosticBag diagnostics, out Conversion conversion) { if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, delegateType, delegateMismatchLocation)) { conversion = Conversion.NoConversion; return true; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); conversion = Conversions.GetMethodGroupDelegateConversion(boundMethodGroup, delegateType, ref useSiteInfo); diagnostics.Add(delegateMismatchLocation, useSiteInfo); if (!conversion.Exists) { if (!Conversions.ReportDelegateOrFunctionPointerMethodGroupDiagnostics(this, boundMethodGroup, delegateType, diagnostics)) { // No overload for '{0}' matches delegate '{1}' diagnostics.Add(ErrorCode.ERR_MethDelegateMismatch, delegateMismatchLocation, boundMethodGroup.Name, delegateType); } return true; } else { Debug.Assert(conversion.IsValid); // i.e. if it exists, then it is valid. // Only cares about nullness and type of receiver, so no need to worry about BoundTypeOrValueExpression. return this.MethodGroupConversionHasErrors(boundMethodGroup.Syntax, conversion, boundMethodGroup.ReceiverOpt, conversion.IsExtensionMethod, isAddressOf: false, delegateType, diagnostics); } } public ConstantValue? FoldConstantConversion( SyntaxNode syntax, BoundExpression source, Conversion conversion, TypeSymbol destination, BindingDiagnosticBag diagnostics) { RoslynDebug.Assert(source != null); RoslynDebug.Assert((object)destination != null); // The diagnostics bag can be null in cases where we know ahead of time that the // conversion will succeed without error or warning. (For example, if we have a valid // implicit numeric conversion on a constant of numeric type.) // SPEC: A constant expression must be the null literal or a value with one of // SPEC: the following types: sbyte, byte, short, ushort, int, uint, long, // SPEC: ulong, char, float, double, decimal, bool, string, or any enumeration type. // SPEC: The following conversions are permitted in constant expressions: // SPEC: Identity conversions // SPEC: Numeric conversions // SPEC: Enumeration conversions // SPEC: Constant expression conversions // SPEC: Implicit and explicit reference conversions, provided that the source of the conversions // SPEC: is a constant expression that evaluates to the null value. // SPEC VIOLATION: C# has always allowed the following, even though this does violate the rule that // SPEC VIOLATION: a constant expression must be either the null literal, or an expression of one // SPEC VIOLATION: of the given types. // SPEC VIOLATION: const C c = (C)null; // TODO: Some conversions can produce errors or warnings depending on checked/unchecked. // TODO: Fold conversions on enums and strings too. var sourceConstantValue = source.ConstantValue; if (sourceConstantValue == null) { if (conversion.Kind == ConversionKind.DefaultLiteral) { return destination.GetDefaultValue(); } else { return sourceConstantValue; } } else if (sourceConstantValue.IsBad) { return sourceConstantValue; } if (source.HasAnyErrors) { return null; } switch (conversion.Kind) { case ConversionKind.Identity: // An identity conversion to a floating-point type (for example from a cast in // source code) changes the internal representation of the constant value // to precisely the required precision. switch (destination.SpecialType) { case SpecialType.System_Single: return ConstantValue.Create(sourceConstantValue.SingleValue); case SpecialType.System_Double: return ConstantValue.Create(sourceConstantValue.DoubleValue); default: return sourceConstantValue; } case ConversionKind.NullLiteral: return sourceConstantValue; case ConversionKind.ImplicitConstant: return FoldConstantNumericConversion(syntax, sourceConstantValue, destination, diagnostics); case ConversionKind.ExplicitNumeric: case ConversionKind.ImplicitNumeric: case ConversionKind.ExplicitEnumeration: case ConversionKind.ImplicitEnumeration: // The C# specification categorizes conversion from literal zero to nullable enum as // an Implicit Enumeration Conversion. Such a thing should not be constant folded // because nullable enums are never constants. if (destination.IsNullableType()) { return null; } return FoldConstantNumericConversion(syntax, sourceConstantValue, destination, diagnostics); case ConversionKind.ExplicitReference: case ConversionKind.ImplicitReference: return sourceConstantValue.IsNull ? sourceConstantValue : null; } return null; } private ConstantValue? FoldConstantNumericConversion( SyntaxNode syntax, ConstantValue sourceValue, TypeSymbol destination, BindingDiagnosticBag diagnostics) { RoslynDebug.Assert(sourceValue != null); Debug.Assert(!sourceValue.IsBad); SpecialType destinationType; if ((object)destination != null && destination.IsEnumType()) { var underlyingType = ((NamedTypeSymbol)destination).EnumUnderlyingType; RoslynDebug.Assert((object)underlyingType != null); Debug.Assert(underlyingType.SpecialType != SpecialType.None); destinationType = underlyingType.SpecialType; } else { destinationType = destination.GetSpecialTypeSafe(); } // In an unchecked context we ignore overflowing conversions on conversions from any // integral type, float and double to any integral type. "unchecked" actually does not // affect conversions from decimal to any integral type; if those are out of bounds then // we always give an error regardless. if (sourceValue.IsDecimal) { if (!CheckConstantBounds(destinationType, sourceValue, out _)) { // NOTE: Dev10 puts a suffix, "M", on the constant value. Error(diagnostics, ErrorCode.ERR_ConstOutOfRange, syntax, sourceValue.Value + "M", destination!); return ConstantValue.Bad; } } else if (destinationType == SpecialType.System_Decimal) { if (!CheckConstantBounds(destinationType, sourceValue, out _)) { Error(diagnostics, ErrorCode.ERR_ConstOutOfRange, syntax, sourceValue.Value!, destination!); return ConstantValue.Bad; } } else if (CheckOverflowAtCompileTime) { if (!CheckConstantBounds(destinationType, sourceValue, out bool maySucceedAtRuntime)) { if (maySucceedAtRuntime) { // Can be calculated at runtime, but is not a compile-time constant. Error(diagnostics, ErrorCode.WRN_ConstOutOfRangeChecked, syntax, sourceValue.Value!, destination!); return null; } else { Error(diagnostics, ErrorCode.ERR_ConstOutOfRangeChecked, syntax, sourceValue.Value!, destination!); return ConstantValue.Bad; } } } else if (destinationType == SpecialType.System_IntPtr || destinationType == SpecialType.System_UIntPtr) { if (!CheckConstantBounds(destinationType, sourceValue, out _)) { // Can be calculated at runtime, but is not a compile-time constant. return null; } } return ConstantValue.Create(DoUncheckedConversion(destinationType, sourceValue), destinationType); } private static object DoUncheckedConversion(SpecialType destinationType, ConstantValue value) { // Note that we keep "single" floats as doubles internally to maintain higher precision. However, // we do not do so in an entirely "lossless" manner. When *converting* to a float, we do lose // the precision lost due to the conversion. But when doing arithmetic, we do the arithmetic on // the double values. // // An example will help. Suppose we have: // // const float cf1 = 1.0f; // const float cf2 = 1.0e-15f; // const double cd3 = cf1 - cf2; // // We first take the double-precision values for 1.0 and 1.0e-15 and round them to floats, // and then turn them back into doubles. Then when we do the subtraction, we do the subtraction // in doubles, not in floats. Had we done the subtraction in floats, we'd get 1.0; but instead we // do it in doubles and get 0.99999999999999. // // Similarly, if we have // // const int i4 = int.MaxValue; // 2147483647 // const float cf5 = int.MaxValue; // 2147483648.0 // const double cd6 = cf5; // 2147483648.0 // // The int is converted to float and stored internally as the double 214783648, even though the // fully precise int would fit into a double. unchecked { switch (value.Discriminator) { case ConstantValueTypeDiscriminator.Byte: byte byteValue = value.ByteValue; switch (destinationType) { case SpecialType.System_Byte: return (byte)byteValue; case SpecialType.System_Char: return (char)byteValue; case SpecialType.System_UInt16: return (ushort)byteValue; case SpecialType.System_UInt32: return (uint)byteValue; case SpecialType.System_UInt64: return (ulong)byteValue; case SpecialType.System_SByte: return (sbyte)byteValue; case SpecialType.System_Int16: return (short)byteValue; case SpecialType.System_Int32: return (int)byteValue; case SpecialType.System_Int64: return (long)byteValue; case SpecialType.System_IntPtr: return (int)byteValue; case SpecialType.System_UIntPtr: return (uint)byteValue; case SpecialType.System_Single: case SpecialType.System_Double: return (double)byteValue; case SpecialType.System_Decimal: return (decimal)byteValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.Char: char charValue = value.CharValue; switch (destinationType) { case SpecialType.System_Byte: return (byte)charValue; case SpecialType.System_Char: return (char)charValue; case SpecialType.System_UInt16: return (ushort)charValue; case SpecialType.System_UInt32: return (uint)charValue; case SpecialType.System_UInt64: return (ulong)charValue; case SpecialType.System_SByte: return (sbyte)charValue; case SpecialType.System_Int16: return (short)charValue; case SpecialType.System_Int32: return (int)charValue; case SpecialType.System_Int64: return (long)charValue; case SpecialType.System_IntPtr: return (int)charValue; case SpecialType.System_UIntPtr: return (uint)charValue; case SpecialType.System_Single: case SpecialType.System_Double: return (double)charValue; case SpecialType.System_Decimal: return (decimal)charValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.UInt16: ushort uint16Value = value.UInt16Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)uint16Value; case SpecialType.System_Char: return (char)uint16Value; case SpecialType.System_UInt16: return (ushort)uint16Value; case SpecialType.System_UInt32: return (uint)uint16Value; case SpecialType.System_UInt64: return (ulong)uint16Value; case SpecialType.System_SByte: return (sbyte)uint16Value; case SpecialType.System_Int16: return (short)uint16Value; case SpecialType.System_Int32: return (int)uint16Value; case SpecialType.System_Int64: return (long)uint16Value; case SpecialType.System_IntPtr: return (int)uint16Value; case SpecialType.System_UIntPtr: return (uint)uint16Value; case SpecialType.System_Single: case SpecialType.System_Double: return (double)uint16Value; case SpecialType.System_Decimal: return (decimal)uint16Value; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.UInt32: uint uint32Value = value.UInt32Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)uint32Value; case SpecialType.System_Char: return (char)uint32Value; case SpecialType.System_UInt16: return (ushort)uint32Value; case SpecialType.System_UInt32: return (uint)uint32Value; case SpecialType.System_UInt64: return (ulong)uint32Value; case SpecialType.System_SByte: return (sbyte)uint32Value; case SpecialType.System_Int16: return (short)uint32Value; case SpecialType.System_Int32: return (int)uint32Value; case SpecialType.System_Int64: return (long)uint32Value; case SpecialType.System_IntPtr: return (int)uint32Value; case SpecialType.System_UIntPtr: return (uint)uint32Value; case SpecialType.System_Single: return (double)(float)uint32Value; case SpecialType.System_Double: return (double)uint32Value; case SpecialType.System_Decimal: return (decimal)uint32Value; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.UInt64: ulong uint64Value = value.UInt64Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)uint64Value; case SpecialType.System_Char: return (char)uint64Value; case SpecialType.System_UInt16: return (ushort)uint64Value; case SpecialType.System_UInt32: return (uint)uint64Value; case SpecialType.System_UInt64: return (ulong)uint64Value; case SpecialType.System_SByte: return (sbyte)uint64Value; case SpecialType.System_Int16: return (short)uint64Value; case SpecialType.System_Int32: return (int)uint64Value; case SpecialType.System_Int64: return (long)uint64Value; case SpecialType.System_IntPtr: return (int)uint64Value; case SpecialType.System_UIntPtr: return (uint)uint64Value; case SpecialType.System_Single: return (double)(float)uint64Value; case SpecialType.System_Double: return (double)uint64Value; case SpecialType.System_Decimal: return (decimal)uint64Value; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.NUInt: uint nuintValue = value.UInt32Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)nuintValue; case SpecialType.System_Char: return (char)nuintValue; case SpecialType.System_UInt16: return (ushort)nuintValue; case SpecialType.System_UInt32: return (uint)nuintValue; case SpecialType.System_UInt64: return (ulong)nuintValue; case SpecialType.System_SByte: return (sbyte)nuintValue; case SpecialType.System_Int16: return (short)nuintValue; case SpecialType.System_Int32: return (int)nuintValue; case SpecialType.System_Int64: return (long)nuintValue; case SpecialType.System_IntPtr: return (int)nuintValue; case SpecialType.System_Single: return (double)(float)nuintValue; case SpecialType.System_Double: return (double)nuintValue; case SpecialType.System_Decimal: return (decimal)nuintValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.SByte: sbyte sbyteValue = value.SByteValue; switch (destinationType) { case SpecialType.System_Byte: return (byte)sbyteValue; case SpecialType.System_Char: return (char)sbyteValue; case SpecialType.System_UInt16: return (ushort)sbyteValue; case SpecialType.System_UInt32: return (uint)sbyteValue; case SpecialType.System_UInt64: return (ulong)sbyteValue; case SpecialType.System_SByte: return (sbyte)sbyteValue; case SpecialType.System_Int16: return (short)sbyteValue; case SpecialType.System_Int32: return (int)sbyteValue; case SpecialType.System_Int64: return (long)sbyteValue; case SpecialType.System_IntPtr: return (int)sbyteValue; case SpecialType.System_UIntPtr: return (uint)sbyteValue; case SpecialType.System_Single: case SpecialType.System_Double: return (double)sbyteValue; case SpecialType.System_Decimal: return (decimal)sbyteValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.Int16: short int16Value = value.Int16Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)int16Value; case SpecialType.System_Char: return (char)int16Value; case SpecialType.System_UInt16: return (ushort)int16Value; case SpecialType.System_UInt32: return (uint)int16Value; case SpecialType.System_UInt64: return (ulong)int16Value; case SpecialType.System_SByte: return (sbyte)int16Value; case SpecialType.System_Int16: return (short)int16Value; case SpecialType.System_Int32: return (int)int16Value; case SpecialType.System_Int64: return (long)int16Value; case SpecialType.System_IntPtr: return (int)int16Value; case SpecialType.System_UIntPtr: return (uint)int16Value; case SpecialType.System_Single: case SpecialType.System_Double: return (double)int16Value; case SpecialType.System_Decimal: return (decimal)int16Value; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.Int32: int int32Value = value.Int32Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)int32Value; case SpecialType.System_Char: return (char)int32Value; case SpecialType.System_UInt16: return (ushort)int32Value; case SpecialType.System_UInt32: return (uint)int32Value; case SpecialType.System_UInt64: return (ulong)int32Value; case SpecialType.System_SByte: return (sbyte)int32Value; case SpecialType.System_Int16: return (short)int32Value; case SpecialType.System_Int32: return (int)int32Value; case SpecialType.System_Int64: return (long)int32Value; case SpecialType.System_IntPtr: return (int)int32Value; case SpecialType.System_UIntPtr: return (uint)int32Value; case SpecialType.System_Single: return (double)(float)int32Value; case SpecialType.System_Double: return (double)int32Value; case SpecialType.System_Decimal: return (decimal)int32Value; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.Int64: long int64Value = value.Int64Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)int64Value; case SpecialType.System_Char: return (char)int64Value; case SpecialType.System_UInt16: return (ushort)int64Value; case SpecialType.System_UInt32: return (uint)int64Value; case SpecialType.System_UInt64: return (ulong)int64Value; case SpecialType.System_SByte: return (sbyte)int64Value; case SpecialType.System_Int16: return (short)int64Value; case SpecialType.System_Int32: return (int)int64Value; case SpecialType.System_Int64: return (long)int64Value; case SpecialType.System_IntPtr: return (int)int64Value; case SpecialType.System_UIntPtr: return (uint)int64Value; case SpecialType.System_Single: return (double)(float)int64Value; case SpecialType.System_Double: return (double)int64Value; case SpecialType.System_Decimal: return (decimal)int64Value; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.NInt: int nintValue = value.Int32Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)nintValue; case SpecialType.System_Char: return (char)nintValue; case SpecialType.System_UInt16: return (ushort)nintValue; case SpecialType.System_UInt32: return (uint)nintValue; case SpecialType.System_UInt64: return (ulong)nintValue; case SpecialType.System_SByte: return (sbyte)nintValue; case SpecialType.System_Int16: return (short)nintValue; case SpecialType.System_Int32: return (int)nintValue; case SpecialType.System_Int64: return (long)nintValue; case SpecialType.System_IntPtr: return (int)nintValue; case SpecialType.System_UIntPtr: return (uint)nintValue; case SpecialType.System_Single: return (double)(float)nintValue; case SpecialType.System_Double: return (double)nintValue; case SpecialType.System_Decimal: return (decimal)nintValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.Single: case ConstantValueTypeDiscriminator.Double: // When converting from a floating-point type to an integral type, if the checked conversion would // throw an overflow exception, then the unchecked conversion is undefined. So that we have // identical behavior on every host platform, we yield a result of zero in that case. double doubleValue = CheckConstantBounds(destinationType, value.DoubleValue, out _) ? value.DoubleValue : 0D; switch (destinationType) { case SpecialType.System_Byte: return (byte)doubleValue; case SpecialType.System_Char: return (char)doubleValue; case SpecialType.System_UInt16: return (ushort)doubleValue; case SpecialType.System_UInt32: return (uint)doubleValue; case SpecialType.System_UInt64: return (ulong)doubleValue; case SpecialType.System_SByte: return (sbyte)doubleValue; case SpecialType.System_Int16: return (short)doubleValue; case SpecialType.System_Int32: return (int)doubleValue; case SpecialType.System_Int64: return (long)doubleValue; case SpecialType.System_IntPtr: return (int)doubleValue; case SpecialType.System_UIntPtr: return (uint)doubleValue; case SpecialType.System_Single: return (double)(float)doubleValue; case SpecialType.System_Double: return (double)doubleValue; case SpecialType.System_Decimal: return (value.Discriminator == ConstantValueTypeDiscriminator.Single) ? (decimal)(float)doubleValue : (decimal)doubleValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.Decimal: decimal decimalValue = CheckConstantBounds(destinationType, value.DecimalValue, out _) ? value.DecimalValue : 0m; switch (destinationType) { case SpecialType.System_Byte: return (byte)decimalValue; case SpecialType.System_Char: return (char)decimalValue; case SpecialType.System_UInt16: return (ushort)decimalValue; case SpecialType.System_UInt32: return (uint)decimalValue; case SpecialType.System_UInt64: return (ulong)decimalValue; case SpecialType.System_SByte: return (sbyte)decimalValue; case SpecialType.System_Int16: return (short)decimalValue; case SpecialType.System_Int32: return (int)decimalValue; case SpecialType.System_Int64: return (long)decimalValue; case SpecialType.System_IntPtr: return (int)decimalValue; case SpecialType.System_UIntPtr: return (uint)decimalValue; case SpecialType.System_Single: return (double)(float)decimalValue; case SpecialType.System_Double: return (double)decimalValue; case SpecialType.System_Decimal: return (decimal)decimalValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } default: throw ExceptionUtilities.UnexpectedValue(value.Discriminator); } } // all cases should have been handled in the switch above. // return value.Value; } public static bool CheckConstantBounds(SpecialType destinationType, ConstantValue value, out bool maySucceedAtRuntime) { if (value.IsBad) { //assume that the constant was intended to be in bounds maySucceedAtRuntime = false; return true; } // Compute whether the value fits into the bounds of the given destination type without // error. We know that the constant will fit into either a double or a decimal, so // convert it to one of those and then check the bounds on that. var canonicalValue = CanonicalizeConstant(value); return canonicalValue is decimal ? CheckConstantBounds(destinationType, (decimal)canonicalValue, out maySucceedAtRuntime) : CheckConstantBounds(destinationType, (double)canonicalValue, out maySucceedAtRuntime); } private static bool CheckConstantBounds(SpecialType destinationType, double value, out bool maySucceedAtRuntime) { maySucceedAtRuntime = false; // Dev10 checks (minValue - 1) < value < (maxValue + 1). // See ExpressionBinder::isConstantInRange. switch (destinationType) { case SpecialType.System_Byte: return (byte.MinValue - 1D) < value && value < (byte.MaxValue + 1D); case SpecialType.System_Char: return (char.MinValue - 1D) < value && value < (char.MaxValue + 1D); case SpecialType.System_UInt16: return (ushort.MinValue - 1D) < value && value < (ushort.MaxValue + 1D); case SpecialType.System_UInt32: return (uint.MinValue - 1D) < value && value < (uint.MaxValue + 1D); case SpecialType.System_UInt64: return (ulong.MinValue - 1D) < value && value < (ulong.MaxValue + 1D); case SpecialType.System_SByte: return (sbyte.MinValue - 1D) < value && value < (sbyte.MaxValue + 1D); case SpecialType.System_Int16: return (short.MinValue - 1D) < value && value < (short.MaxValue + 1D); case SpecialType.System_Int32: return (int.MinValue - 1D) < value && value < (int.MaxValue + 1D); // Note: Using <= to compare the min value matches the native compiler. case SpecialType.System_Int64: return (long.MinValue - 1D) <= value && value < (long.MaxValue + 1D); case SpecialType.System_Decimal: return ((double)decimal.MinValue - 1D) < value && value < ((double)decimal.MaxValue + 1D); case SpecialType.System_IntPtr: maySucceedAtRuntime = (long.MinValue - 1D) < value && value < (long.MaxValue + 1D); return (int.MinValue - 1D) < value && value < (int.MaxValue + 1D); case SpecialType.System_UIntPtr: maySucceedAtRuntime = (ulong.MinValue - 1D) < value && value < (ulong.MaxValue + 1D); return (uint.MinValue - 1D) < value && value < (uint.MaxValue + 1D); } return true; } private static bool CheckConstantBounds(SpecialType destinationType, decimal value, out bool maySucceedAtRuntime) { maySucceedAtRuntime = false; // Dev10 checks (minValue - 1) < value < (maxValue + 1). // See ExpressionBinder::isConstantInRange. switch (destinationType) { case SpecialType.System_Byte: return (byte.MinValue - 1M) < value && value < (byte.MaxValue + 1M); case SpecialType.System_Char: return (char.MinValue - 1M) < value && value < (char.MaxValue + 1M); case SpecialType.System_UInt16: return (ushort.MinValue - 1M) < value && value < (ushort.MaxValue + 1M); case SpecialType.System_UInt32: return (uint.MinValue - 1M) < value && value < (uint.MaxValue + 1M); case SpecialType.System_UInt64: return (ulong.MinValue - 1M) < value && value < (ulong.MaxValue + 1M); case SpecialType.System_SByte: return (sbyte.MinValue - 1M) < value && value < (sbyte.MaxValue + 1M); case SpecialType.System_Int16: return (short.MinValue - 1M) < value && value < (short.MaxValue + 1M); case SpecialType.System_Int32: return (int.MinValue - 1M) < value && value < (int.MaxValue + 1M); case SpecialType.System_Int64: return (long.MinValue - 1M) < value && value < (long.MaxValue + 1M); case SpecialType.System_IntPtr: maySucceedAtRuntime = (long.MinValue - 1M) < value && value < (long.MaxValue + 1M); return (int.MinValue - 1M) < value && value < (int.MaxValue + 1M); case SpecialType.System_UIntPtr: maySucceedAtRuntime = (ulong.MinValue - 1M) < value && value < (ulong.MaxValue + 1M); return (uint.MinValue - 1M) < value && value < (uint.MaxValue + 1M); } return true; } // Takes in a constant of any kind and returns the constant as either a double or decimal private static object CanonicalizeConstant(ConstantValue value) { switch (value.Discriminator) { case ConstantValueTypeDiscriminator.SByte: return (decimal)value.SByteValue; case ConstantValueTypeDiscriminator.Int16: return (decimal)value.Int16Value; case ConstantValueTypeDiscriminator.Int32: return (decimal)value.Int32Value; case ConstantValueTypeDiscriminator.Int64: return (decimal)value.Int64Value; case ConstantValueTypeDiscriminator.NInt: return (decimal)value.Int32Value; case ConstantValueTypeDiscriminator.Byte: return (decimal)value.ByteValue; case ConstantValueTypeDiscriminator.Char: return (decimal)value.CharValue; case ConstantValueTypeDiscriminator.UInt16: return (decimal)value.UInt16Value; case ConstantValueTypeDiscriminator.UInt32: return (decimal)value.UInt32Value; case ConstantValueTypeDiscriminator.UInt64: return (decimal)value.UInt64Value; case ConstantValueTypeDiscriminator.NUInt: return (decimal)value.UInt32Value; case ConstantValueTypeDiscriminator.Single: case ConstantValueTypeDiscriminator.Double: return value.DoubleValue; case ConstantValueTypeDiscriminator.Decimal: return value.DecimalValue; default: throw ExceptionUtilities.UnexpectedValue(value.Discriminator); } // all cases handled in the switch, above. } } }
// Licensed to the .NET Foundation under one or more 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; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class Binder { internal BoundExpression CreateConversion( BoundExpression source, TypeSymbol destination, BindingDiagnosticBag diagnostics) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var conversion = Conversions.ClassifyConversionFromExpression(source, destination, ref useSiteInfo); diagnostics.Add(source.Syntax, useSiteInfo); return CreateConversion(source.Syntax, source, conversion, isCast: false, conversionGroupOpt: null, destination: destination, diagnostics: diagnostics); } internal BoundExpression CreateConversion( BoundExpression source, Conversion conversion, TypeSymbol destination, BindingDiagnosticBag diagnostics) { return CreateConversion(source.Syntax, source, conversion, isCast: false, conversionGroupOpt: null, destination: destination, diagnostics: diagnostics); } internal BoundExpression CreateConversion( SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroupOpt, TypeSymbol destination, BindingDiagnosticBag diagnostics) { return CreateConversion(syntax, source, conversion, isCast: isCast, conversionGroupOpt, source.WasCompilerGenerated, destination, diagnostics); } protected BoundExpression CreateConversion( SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroupOpt, bool wasCompilerGenerated, TypeSymbol destination, BindingDiagnosticBag diagnostics, bool hasErrors = false) { RoslynDebug.Assert(source != null); RoslynDebug.Assert((object)destination != null); RoslynDebug.Assert(!isCast || conversionGroupOpt != null); if (conversion.IsIdentity) { if (source is BoundTupleLiteral sourceTuple) { NamedTypeSymbol.ReportTupleNamesMismatchesIfAny(destination, sourceTuple, diagnostics); } // identity tuple and switch conversions result in a converted expression // to indicate that such conversions are no longer applicable. source = BindToNaturalType(source, diagnostics); RoslynDebug.Assert(source.Type is object); // We need to preserve any conversion that changes the type (even identity conversions, like object->dynamic), // or that was explicitly written in code (so that GetSemanticInfo can find the syntax in the bound tree). if (!isCast && source.Type.Equals(destination, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { return source; } } if (conversion.IsMethodGroup) { return CreateMethodGroupConversion(syntax, source, conversion, isCast: isCast, conversionGroupOpt, destination, diagnostics); } // Obsolete diagnostics for method group are reported as part of creating the method group conversion. ReportDiagnosticsIfObsolete(diagnostics, conversion, syntax, hasBaseReceiver: false); CheckConstraintLanguageVersionAndRuntimeSupportForConversion(syntax, conversion, diagnostics); if (conversion.IsAnonymousFunction && source.Kind == BoundKind.UnboundLambda) { return CreateAnonymousFunctionConversion(syntax, source, conversion, isCast: isCast, conversionGroupOpt, destination, diagnostics); } if (conversion.IsStackAlloc) { return CreateStackAllocConversion(syntax, source, conversion, isCast, conversionGroupOpt, destination, diagnostics); } if (conversion.IsTupleLiteralConversion || (conversion.IsNullable && conversion.UnderlyingConversions[0].IsTupleLiteralConversion)) { return CreateTupleLiteralConversion(syntax, (BoundTupleLiteral)source, conversion, isCast: isCast, conversionGroupOpt, destination, diagnostics); } if (conversion.Kind == ConversionKind.SwitchExpression) { var convertedSwitch = ConvertSwitchExpression((BoundUnconvertedSwitchExpression)source, destination, conversionIfTargetTyped: conversion, diagnostics); return new BoundConversion( syntax, convertedSwitch, conversion, CheckOverflowAtRuntime, explicitCastInCode: isCast && !wasCompilerGenerated, conversionGroupOpt, convertedSwitch.ConstantValue, destination, hasErrors); } if (conversion.Kind == ConversionKind.ConditionalExpression) { var convertedConditional = ConvertConditionalExpression((BoundUnconvertedConditionalOperator)source, destination, conversionIfTargetTyped: conversion, diagnostics); return new BoundConversion( syntax, convertedConditional, conversion, CheckOverflowAtRuntime, explicitCastInCode: isCast && !wasCompilerGenerated, conversionGroupOpt, convertedConditional.ConstantValue, destination, hasErrors); } if (conversion.Kind == ConversionKind.InterpolatedString) { var unconvertedSource = (BoundUnconvertedInterpolatedString)source; source = new BoundInterpolatedString( unconvertedSource.Syntax, interpolationData: null, BindInterpolatedStringParts(unconvertedSource, diagnostics), unconvertedSource.ConstantValue, unconvertedSource.Type, unconvertedSource.HasErrors); } if (conversion.Kind == ConversionKind.InterpolatedStringHandler) { var unconvertedSource = (BoundUnconvertedInterpolatedString)source; return new BoundConversion( syntax, BindUnconvertedInterpolatedStringToHandlerType(unconvertedSource, (NamedTypeSymbol)destination, diagnostics, isHandlerConversion: true), conversion, @checked: CheckOverflowAtRuntime, explicitCastInCode: isCast && !wasCompilerGenerated, conversionGroupOpt, constantValueOpt: null, destination); } if (source.Kind == BoundKind.UnconvertedSwitchExpression) { TypeSymbol? type = source.Type; if (type is null) { Debug.Assert(!conversion.Exists); type = CreateErrorType(); hasErrors = true; } source = ConvertSwitchExpression((BoundUnconvertedSwitchExpression)source, type, conversionIfTargetTyped: null, diagnostics, hasErrors); if (destination.Equals(type, TypeCompareKind.ConsiderEverything) && wasCompilerGenerated) { return source; } } if (conversion.IsObjectCreation) { return ConvertObjectCreationExpression(syntax, (BoundUnconvertedObjectCreationExpression)source, isCast, destination, diagnostics); } if (source.Kind == BoundKind.UnconvertedConditionalOperator) { TypeSymbol? type = source.Type; if (type is null) { Debug.Assert(!conversion.Exists); type = CreateErrorType(); hasErrors = true; } source = ConvertConditionalExpression((BoundUnconvertedConditionalOperator)source, type, conversionIfTargetTyped: null, diagnostics, hasErrors); if (destination.Equals(type, TypeCompareKind.ConsiderEverything) && wasCompilerGenerated) { return source; } } if (conversion.IsUserDefined) { // User-defined conversions are likely to be represented as multiple // BoundConversion instances so a ConversionGroup is necessary. return CreateUserDefinedConversion(syntax, source, conversion, isCast: isCast, conversionGroupOpt ?? new ConversionGroup(conversion), destination, diagnostics, hasErrors); } ConstantValue? constantValue = this.FoldConstantConversion(syntax, source, conversion, destination, diagnostics); if (conversion.Kind == ConversionKind.DefaultLiteral) { source = new BoundDefaultExpression(source.Syntax, targetType: null, constantValue, type: destination) .WithSuppression(source.IsSuppressed); } return new BoundConversion( syntax, BindToNaturalType(source, diagnostics), conversion, @checked: CheckOverflowAtRuntime, explicitCastInCode: isCast && !wasCompilerGenerated, conversionGroupOpt, constantValueOpt: constantValue, type: destination, hasErrors: hasErrors) { WasCompilerGenerated = wasCompilerGenerated }; } internal void CheckConstraintLanguageVersionAndRuntimeSupportForConversion(SyntaxNodeOrToken syntax, Conversion conversion, BindingDiagnosticBag diagnostics) { if (conversion.IsUserDefined && conversion.Method is MethodSymbol method && method.IsStatic && method.IsAbstract) { Debug.Assert(conversion.ConstrainedToTypeOpt is TypeParameterSymbol); if (Compilation.SourceModule != method.ContainingModule) { Debug.Assert(syntax.SyntaxTree is object); CheckFeatureAvailability(syntax.SyntaxTree, MessageID.IDS_FeatureStaticAbstractMembersInInterfaces, diagnostics, syntax.GetLocation()!); if (!Compilation.Assembly.RuntimeSupportsStaticAbstractMembersInInterfaces) { Error(diagnostics, ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, syntax); } } } } private BoundExpression ConvertObjectCreationExpression(SyntaxNode syntax, BoundUnconvertedObjectCreationExpression node, bool isCast, TypeSymbol destination, BindingDiagnosticBag diagnostics) { var arguments = AnalyzedArguments.GetInstance(node.Arguments, node.ArgumentRefKindsOpt, node.ArgumentNamesOpt); BoundExpression expr = BindObjectCreationExpression(node, destination.StrippedType(), arguments, diagnostics); if (destination.IsNullableType()) { // We manually create an ImplicitNullable conversion // if the destination is nullable, in which case we // target the underlying type e.g. `S? x = new();` // is actually identical to `S? x = new S();`. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var conversion = Conversions.ClassifyStandardConversion(null, expr.Type, destination, ref useSiteInfo); expr = new BoundConversion( node.Syntax, operand: expr, conversion: conversion, @checked: false, explicitCastInCode: isCast, conversionGroupOpt: new ConversionGroup(conversion), constantValueOpt: expr.ConstantValue, type: destination); diagnostics.Add(syntax, useSiteInfo); } arguments.Free(); return expr; } private BoundExpression BindObjectCreationExpression(BoundUnconvertedObjectCreationExpression node, TypeSymbol type, AnalyzedArguments arguments, BindingDiagnosticBag diagnostics) { var syntax = node.Syntax; switch (type.TypeKind) { case TypeKind.Enum: case TypeKind.Struct: case TypeKind.Class when !type.IsAnonymousType: // We don't want to enable object creation with unspeakable types return BindClassCreationExpression(syntax, type.Name, typeNode: syntax, (NamedTypeSymbol)type, arguments, diagnostics, node.InitializerOpt, wasTargetTyped: true); case TypeKind.TypeParameter: return BindTypeParameterCreationExpression(syntax, (TypeParameterSymbol)type, arguments, node.InitializerOpt, typeSyntax: syntax, diagnostics); case TypeKind.Delegate: return BindDelegateCreationExpression(syntax, (NamedTypeSymbol)type, arguments, node.InitializerOpt, diagnostics); case TypeKind.Interface: return BindInterfaceCreationExpression(syntax, (NamedTypeSymbol)type, diagnostics, typeNode: syntax, arguments, node.InitializerOpt, wasTargetTyped: true); case TypeKind.Array: case TypeKind.Class: case TypeKind.Dynamic: Error(diagnostics, ErrorCode.ERR_ImplicitObjectCreationIllegalTargetType, syntax, type); goto case TypeKind.Error; case TypeKind.Pointer: case TypeKind.FunctionPointer: Error(diagnostics, ErrorCode.ERR_UnsafeTypeInObjectCreation, syntax, type); goto case TypeKind.Error; case TypeKind.Error: return MakeBadExpressionForObjectCreation(syntax, type, arguments, node.InitializerOpt, typeSyntax: syntax, diagnostics); case var v: throw ExceptionUtilities.UnexpectedValue(v); } } /// <summary> /// Rewrite the subexpressions in a conditional expression to convert the whole thing to the destination type. /// </summary> private BoundExpression ConvertConditionalExpression( BoundUnconvertedConditionalOperator source, TypeSymbol destination, Conversion? conversionIfTargetTyped, BindingDiagnosticBag diagnostics, bool hasErrors = false) { bool targetTyped = conversionIfTargetTyped is { }; Debug.Assert(targetTyped || destination.IsErrorType() || destination.Equals(source.Type, TypeCompareKind.ConsiderEverything)); ImmutableArray<Conversion> underlyingConversions = conversionIfTargetTyped.GetValueOrDefault().UnderlyingConversions; var condition = source.Condition; hasErrors |= source.HasErrors || destination.IsErrorType(); var trueExpr = targetTyped ? CreateConversion(source.Consequence.Syntax, source.Consequence, underlyingConversions[0], isCast: false, conversionGroupOpt: null, destination, diagnostics) : GenerateConversionForAssignment(destination, source.Consequence, diagnostics); var falseExpr = targetTyped ? CreateConversion(source.Alternative.Syntax, source.Alternative, underlyingConversions[1], isCast: false, conversionGroupOpt: null, destination, diagnostics) : GenerateConversionForAssignment(destination, source.Alternative, diagnostics); var constantValue = FoldConditionalOperator(condition, trueExpr, falseExpr); hasErrors |= constantValue?.IsBad == true; if (targetTyped && !destination.IsErrorType() && !Compilation.IsFeatureEnabled(MessageID.IDS_FeatureTargetTypedConditional)) { diagnostics.Add( ErrorCode.ERR_NoImplicitConvTargetTypedConditional, source.Syntax.Location, Compilation.LanguageVersion.ToDisplayString(), source.Consequence.Display, source.Alternative.Display, new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureTargetTypedConditional.RequiredVersion())); } return new BoundConditionalOperator(source.Syntax, isRef: false, condition, trueExpr, falseExpr, constantValue, source.Type, wasTargetTyped: targetTyped, destination, hasErrors) .WithSuppression(source.IsSuppressed); } /// <summary> /// Rewrite the expressions in the switch expression arms to add a conversion to the destination type. /// </summary> private BoundExpression ConvertSwitchExpression(BoundUnconvertedSwitchExpression source, TypeSymbol destination, Conversion? conversionIfTargetTyped, BindingDiagnosticBag diagnostics, bool hasErrors = false) { bool targetTyped = conversionIfTargetTyped is { }; Conversion conversion = conversionIfTargetTyped ?? Conversion.Identity; Debug.Assert(targetTyped || destination.IsErrorType() || destination.Equals(source.Type, TypeCompareKind.ConsiderEverything)); ImmutableArray<Conversion> underlyingConversions = conversion.UnderlyingConversions; var builder = ArrayBuilder<BoundSwitchExpressionArm>.GetInstance(source.SwitchArms.Length); for (int i = 0, n = source.SwitchArms.Length; i < n; i++) { var oldCase = source.SwitchArms[i]; Debug.Assert(oldCase.Syntax is SwitchExpressionArmSyntax); var binder = GetRequiredBinder(oldCase.Syntax); var oldValue = oldCase.Value; var newValue = targetTyped ? binder.CreateConversion(oldValue.Syntax, oldValue, underlyingConversions[i], isCast: false, conversionGroupOpt: null, destination, diagnostics) : binder.GenerateConversionForAssignment(destination, oldValue, diagnostics); var newCase = (oldValue == newValue) ? oldCase : new BoundSwitchExpressionArm(oldCase.Syntax, oldCase.Locals, oldCase.Pattern, oldCase.WhenClause, newValue, oldCase.Label, oldCase.HasErrors); builder.Add(newCase); } var newSwitchArms = builder.ToImmutableAndFree(); return new BoundConvertedSwitchExpression( source.Syntax, source.Type, targetTyped, conversion, source.Expression, newSwitchArms, source.DecisionDag, source.DefaultLabel, source.ReportedNotExhaustive, destination, hasErrors || source.HasErrors); } private BoundExpression CreateUserDefinedConversion( SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics, bool hasErrors) { Debug.Assert(conversionGroup != null); Debug.Assert(conversion.IsUserDefined); if (!conversion.IsValid) { if (!hasErrors) GenerateImplicitConversionError(diagnostics, syntax, conversion, source, destination); return new BoundConversion( syntax, source, conversion, CheckOverflowAtRuntime, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: destination, hasErrors: true) { WasCompilerGenerated = source.WasCompilerGenerated }; } // Due to an oddity in the way we create a non-lifted user-defined conversion from A to D? // (required backwards compatibility with the native compiler) we can end up in a situation // where we have: // a standard conversion from A to B? // then a standard conversion from B? to B // then a user-defined conversion from B to C // then a standard conversion from C to C? // then a standard conversion from C? to D? // // In that scenario, the "from type" of the conversion will be B? and the "from conversion" will be // from A to B?. Similarly the "to type" of the conversion will be C? and the "to conversion" // of the conversion will be from C? to D?. // // Therefore, we might need to introduce an extra conversion on the source side, from B? to B. // Now, you might think we should also introduce an extra conversion on the destination side, // from C to C?. But that then gives us the following bad situation: If we in fact bind this as // // (D?)(C?)(C)(B)(B?)(A)x // // then what we are in effect doing is saying "convert C? to D? by checking for null, unwrapping, // converting C to D, and then wrapping". But we know that the C? will never be null. In this case // we should actually generate // // (D?)(C)(B)(B?)(A)x // // And thereby skip the unnecessary nullable conversion. Debug.Assert(conversion.BestUserDefinedConversionAnalysis is object); // All valid user-defined conversions have this populated // Original expression --> conversion's "from" type BoundExpression convertedOperand = CreateConversion( syntax: source.Syntax, source: source, conversion: conversion.UserDefinedFromConversion, isCast: false, conversionGroupOpt: conversionGroup, wasCompilerGenerated: false, destination: conversion.BestUserDefinedConversionAnalysis.FromType, diagnostics: diagnostics); TypeSymbol conversionParameterType = conversion.BestUserDefinedConversionAnalysis.Operator.GetParameterType(0); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if (conversion.BestUserDefinedConversionAnalysis.Kind == UserDefinedConversionAnalysisKind.ApplicableInNormalForm && !TypeSymbol.Equals(conversion.BestUserDefinedConversionAnalysis.FromType, conversionParameterType, TypeCompareKind.ConsiderEverything2)) { // Conversion's "from" type --> conversion method's parameter type. convertedOperand = CreateConversion( syntax: syntax, source: convertedOperand, conversion: Conversions.ClassifyStandardConversion(null, convertedOperand.Type, conversionParameterType, ref useSiteInfo), isCast: false, conversionGroupOpt: conversionGroup, wasCompilerGenerated: true, destination: conversionParameterType, diagnostics: diagnostics); } BoundExpression userDefinedConversion; TypeSymbol conversionReturnType = conversion.BestUserDefinedConversionAnalysis.Operator.ReturnType; TypeSymbol conversionToType = conversion.BestUserDefinedConversionAnalysis.ToType; Conversion toConversion = conversion.UserDefinedToConversion; if (conversion.BestUserDefinedConversionAnalysis.Kind == UserDefinedConversionAnalysisKind.ApplicableInNormalForm && !TypeSymbol.Equals(conversionToType, conversionReturnType, TypeCompareKind.ConsiderEverything2)) { // Conversion method's parameter type --> conversion method's return type // NB: not calling CreateConversion here because this is the recursive base case. userDefinedConversion = new BoundConversion( syntax, convertedOperand, conversion, @checked: false, // There are no checked user-defined conversions, but the conversions on either side might be checked. explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: conversionReturnType) { WasCompilerGenerated = true }; if (conversionToType.IsNullableType() && TypeSymbol.Equals(conversionToType.GetNullableUnderlyingType(), conversionReturnType, TypeCompareKind.ConsiderEverything2)) { // Skip introducing the conversion from C to C?. The "to" conversion is now wrong though, // because it will still assume converting C? to D?. toConversion = Conversions.ClassifyConversionFromType(conversionReturnType, destination, ref useSiteInfo); Debug.Assert(toConversion.Exists); } else { // Conversion method's return type --> conversion's "to" type userDefinedConversion = CreateConversion( syntax: syntax, source: userDefinedConversion, conversion: Conversions.ClassifyStandardConversion(null, conversionReturnType, conversionToType, ref useSiteInfo), isCast: false, conversionGroupOpt: conversionGroup, wasCompilerGenerated: true, destination: conversionToType, diagnostics: diagnostics); } } else { // Conversion method's parameter type --> conversion method's "to" type // NB: not calling CreateConversion here because this is the recursive base case. userDefinedConversion = new BoundConversion( syntax, convertedOperand, conversion, @checked: false, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: conversionToType) { WasCompilerGenerated = true }; } diagnostics.Add(syntax, useSiteInfo); // Conversion's "to" type --> final type BoundExpression finalConversion = CreateConversion( syntax: syntax, source: userDefinedConversion, conversion: toConversion, isCast: false, conversionGroupOpt: conversionGroup, wasCompilerGenerated: true, // NOTE: doesn't necessarily set flag on resulting bound expression. destination: destination, diagnostics: diagnostics); finalConversion.ResetCompilerGenerated(source.WasCompilerGenerated); return finalConversion; } private BoundExpression CreateAnonymousFunctionConversion(SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics) { // We have a successful anonymous function conversion; rather than producing a node // which is a conversion on top of an unbound lambda, replace it with the bound // lambda. // UNDONE: Figure out what to do about the error case, where a lambda // UNDONE: is converted to a delegate that does not match. What to surface then? var unboundLambda = (UnboundLambda)source; if (destination.SpecialType == SpecialType.System_Delegate || destination.IsNonGenericExpressionType()) { CheckFeatureAvailability(syntax, MessageID.IDS_FeatureInferredDelegateType, diagnostics); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var delegateType = unboundLambda.InferDelegateType(ref useSiteInfo); BoundLambda boundLambda; if (delegateType is { }) { bool isExpressionTree = destination.IsNonGenericExpressionType(); if (isExpressionTree) { delegateType = Compilation.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression_T).Construct(delegateType); delegateType.AddUseSiteInfo(ref useSiteInfo); } boundLambda = unboundLambda.Bind(delegateType, isExpressionTree); } else { diagnostics.Add(ErrorCode.ERR_CannotInferDelegateType, syntax.GetLocation()); delegateType = CreateErrorType(); boundLambda = unboundLambda.BindForErrorRecovery(); } diagnostics.AddRange(boundLambda.Diagnostics); var expr = createAnonymousFunctionConversion(syntax, source, boundLambda, conversion, isCast, conversionGroup, delegateType); conversion = Conversions.ClassifyConversionFromExpression(expr, destination, ref useSiteInfo); diagnostics.Add(syntax, useSiteInfo); return CreateConversion(syntax, expr, conversion, isCast, conversionGroup, destination, diagnostics); } else { #if DEBUG // Test inferring a delegate type for all callers. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; _ = unboundLambda.InferDelegateType(ref discardedUseSiteInfo); #endif var boundLambda = unboundLambda.Bind((NamedTypeSymbol)destination, isExpressionTree: destination.IsGenericOrNonGenericExpressionType(out _)); diagnostics.AddRange(boundLambda.Diagnostics); return createAnonymousFunctionConversion(syntax, source, boundLambda, conversion, isCast, conversionGroup, destination); } static BoundConversion createAnonymousFunctionConversion(SyntaxNode syntax, BoundExpression source, BoundLambda boundLambda, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination) { return new BoundConversion( syntax, boundLambda, conversion, @checked: false, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: destination) { WasCompilerGenerated = source.WasCompilerGenerated }; } } private BoundExpression CreateMethodGroupConversion(SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics) { var (originalGroup, isAddressOf) = source switch { BoundMethodGroup m => (m, false), BoundUnconvertedAddressOfOperator { Operand: { } m } => (m, true), _ => throw ExceptionUtilities.UnexpectedValue(source), }; BoundMethodGroup group = FixMethodGroupWithTypeOrValue(originalGroup, conversion, diagnostics); bool hasErrors = false; if (MethodGroupConversionHasErrors(syntax, conversion, group.ReceiverOpt, conversion.IsExtensionMethod, isAddressOf, destination, diagnostics)) { hasErrors = true; } if (destination.SpecialType == SpecialType.System_Delegate) { CheckFeatureAvailability(syntax, MessageID.IDS_FeatureInferredDelegateType, diagnostics); // https://github.com/dotnet/roslyn/issues/52869: Avoid calculating the delegate type multiple times during conversion. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var delegateType = GetMethodGroupDelegateType(group, ref useSiteInfo); var expr = createMethodGroupConversion(syntax, group, conversion, isCast, conversionGroup, delegateType!, hasErrors); conversion = Conversions.ClassifyConversionFromExpression(expr, destination, ref useSiteInfo); diagnostics.Add(syntax, useSiteInfo); return CreateConversion(syntax, expr, conversion, isCast, conversionGroup, destination, diagnostics); } #if DEBUG // Test inferring a delegate type for all callers. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; _ = GetMethodGroupDelegateType(group, ref discardedUseSiteInfo); #endif return createMethodGroupConversion(syntax, group, conversion, isCast, conversionGroup, destination, hasErrors); static BoundConversion createMethodGroupConversion(SyntaxNode syntax, BoundMethodGroup group, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, bool hasErrors) { return new BoundConversion(syntax, group, conversion, @checked: false, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: destination, hasErrors: hasErrors) { WasCompilerGenerated = group.WasCompilerGenerated }; } } private BoundExpression CreateStackAllocConversion(SyntaxNode syntax, BoundExpression source, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics) { Debug.Assert(conversion.IsStackAlloc); var boundStackAlloc = (BoundStackAllocArrayCreation)source; var elementType = boundStackAlloc.ElementType; TypeSymbol stackAllocType; switch (conversion.Kind) { case ConversionKind.StackAllocToPointerType: ReportUnsafeIfNotAllowed(syntax.Location, diagnostics); stackAllocType = new PointerTypeSymbol(TypeWithAnnotations.Create(elementType)); break; case ConversionKind.StackAllocToSpanType: CheckFeatureAvailability(syntax, MessageID.IDS_FeatureRefStructs, diagnostics); stackAllocType = Compilation.GetWellKnownType(WellKnownType.System_Span_T).Construct(elementType); break; default: throw ExceptionUtilities.UnexpectedValue(conversion.Kind); } var convertedNode = new BoundConvertedStackAllocExpression(syntax, elementType, boundStackAlloc.Count, boundStackAlloc.InitializerOpt, stackAllocType, boundStackAlloc.HasErrors); var underlyingConversion = conversion.UnderlyingConversions.Single(); return CreateConversion(syntax, convertedNode, underlyingConversion, isCast: isCast, conversionGroup, destination, diagnostics); } private BoundExpression CreateTupleLiteralConversion(SyntaxNode syntax, BoundTupleLiteral sourceTuple, Conversion conversion, bool isCast, ConversionGroup? conversionGroup, TypeSymbol destination, BindingDiagnosticBag diagnostics) { // We have a successful tuple conversion; rather than producing a separate conversion node // which is a conversion on top of a tuple literal, tuple conversion is an element-wise conversion of arguments. Debug.Assert(conversion.IsNullable == destination.IsNullableType()); var destinationWithoutNullable = destination; var conversionWithoutNullable = conversion; if (conversion.IsNullable) { destinationWithoutNullable = destination.GetNullableUnderlyingType(); conversionWithoutNullable = conversion.UnderlyingConversions[0]; } Debug.Assert(conversionWithoutNullable.IsTupleLiteralConversion); NamedTypeSymbol targetType = (NamedTypeSymbol)destinationWithoutNullable; if (targetType.IsTupleType) { NamedTypeSymbol.ReportTupleNamesMismatchesIfAny(targetType, sourceTuple, diagnostics); // do not lose the original element names and locations in the literal if different from names in the target // // the tuple has changed the type of elements due to target-typing, // but element names has not changed and locations of their declarations // should not be confused with element locations on the target type. if (sourceTuple.Type is NamedTypeSymbol { IsTupleType: true } sourceType) { targetType = targetType.WithTupleDataFrom(sourceType); } else { var tupleSyntax = (TupleExpressionSyntax)sourceTuple.Syntax; var locationBuilder = ArrayBuilder<Location?>.GetInstance(); foreach (var argument in tupleSyntax.Arguments) { locationBuilder.Add(argument.NameColon?.Name.Location); } targetType = targetType.WithElementNames(sourceTuple.ArgumentNamesOpt!, locationBuilder.ToImmutableAndFree(), errorPositions: default, ImmutableArray.Create(tupleSyntax.Location)); } } var arguments = sourceTuple.Arguments; var convertedArguments = ArrayBuilder<BoundExpression>.GetInstance(arguments.Length); var targetElementTypes = targetType.TupleElementTypesWithAnnotations; Debug.Assert(targetElementTypes.Length == arguments.Length, "converting a tuple literal to incompatible type?"); var underlyingConversions = conversionWithoutNullable.UnderlyingConversions; for (int i = 0; i < arguments.Length; i++) { var argument = arguments[i]; var destType = targetElementTypes[i]; var elementConversion = underlyingConversions[i]; var elementConversionGroup = isCast ? new ConversionGroup(elementConversion, destType) : null; convertedArguments.Add(CreateConversion(argument.Syntax, argument, elementConversion, isCast: isCast, elementConversionGroup, destType.Type, diagnostics)); } BoundExpression result = new BoundConvertedTupleLiteral( sourceTuple.Syntax, sourceTuple, wasTargetTyped: true, convertedArguments.ToImmutableAndFree(), sourceTuple.ArgumentNamesOpt, sourceTuple.InferredNamesOpt, targetType).WithSuppression(sourceTuple.IsSuppressed); if (!TypeSymbol.Equals(sourceTuple.Type, destination, TypeCompareKind.ConsiderEverything2)) { // literal cast is applied to the literal result = new BoundConversion( sourceTuple.Syntax, result, conversion, @checked: false, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: destination); } // If we had a cast in the code, keep conversion in the tree. // even though the literal is already converted to the target type. if (isCast) { result = new BoundConversion( syntax, result, Conversion.Identity, @checked: false, explicitCastInCode: isCast, conversionGroup, constantValueOpt: ConstantValue.NotAvailable, type: destination); } return result; } private static bool IsMethodGroupWithTypeOrValueReceiver(BoundNode node) { if (node.Kind != BoundKind.MethodGroup) { return false; } return Binder.IsTypeOrValueExpression(((BoundMethodGroup)node).ReceiverOpt); } private BoundMethodGroup FixMethodGroupWithTypeOrValue(BoundMethodGroup group, Conversion conversion, BindingDiagnosticBag diagnostics) { if (!IsMethodGroupWithTypeOrValueReceiver(group)) { return group; } BoundExpression? receiverOpt = group.ReceiverOpt; RoslynDebug.Assert(receiverOpt != null); receiverOpt = ReplaceTypeOrValueReceiver(receiverOpt, useType: conversion.Method?.RequiresInstanceReceiver == false && !conversion.IsExtensionMethod, diagnostics); return group.Update( group.TypeArgumentsOpt, group.Name, group.Methods, group.LookupSymbolOpt, group.LookupError, group.Flags, receiverOpt, //only change group.ResultKind); } /// <summary> /// This method implements the algorithm in spec section 7.6.5.1. /// /// For method group conversions, there are situations in which the conversion is /// considered to exist ("Otherwise the algorithm produces a single best method M having /// the same number of parameters as D and the conversion is considered to exist"), but /// application of the conversion fails. These are the "final validation" steps of /// overload resolution. /// </summary> /// <returns> /// True if there is any error, except lack of runtime support errors. /// </returns> private bool MemberGroupFinalValidation(BoundExpression? receiverOpt, MethodSymbol methodSymbol, SyntaxNode node, BindingDiagnosticBag diagnostics, bool invokedAsExtensionMethod) { if (!IsBadBaseAccess(node, receiverOpt, methodSymbol, diagnostics)) { CheckReceiverAndRuntimeSupportForSymbolAccess(node, receiverOpt, methodSymbol, diagnostics); } if (MemberGroupFinalValidationAccessibilityChecks(receiverOpt, methodSymbol, node, diagnostics, invokedAsExtensionMethod)) { return true; } // SPEC: If the best method is a generic method, the type arguments (supplied or inferred) are checked against the constraints // SPEC: declared on the generic method. If any type argument does not satisfy the corresponding constraint(s) on // SPEC: the type parameter, a binding-time error occurs. // The portion of the overload resolution spec quoted above is subtle and somewhat // controversial. The upshot of this is that overload resolution does not consider // constraints to be a part of the signature. Overload resolution matches arguments to // parameter lists; it does not consider things which are outside of the parameter list. // If the best match from the arguments to the formal parameters is not viable then we // give an error rather than falling back to a worse match. // // Consider the following: // // void M<T>(T t) where T : Reptile {} // void M(object x) {} // ... // M(new Giraffe()); // // The correct analysis is to determine that the applicable candidates are // M<Giraffe>(Giraffe) and M(object). Overload resolution then chooses the former // because it is an exact match, over the latter which is an inexact match. Only after // the best method is determined do we check the constraints and discover that the // constraint on T has been violated. // // Note that this is different from the rule that says that during type inference, if an // inference violates a constraint then inference fails. For example: // // class C<T> where T : struct {} // ... // void M<U>(U u, C<U> c){} // void M(object x, object y) {} // ... // M("hello", null); // // Type inference determines that U is string, but since C<string> is not a valid type // because of the constraint, type inference fails. M<string> is never added to the // applicable candidate set, so the applicable candidate set consists solely of // M(object, object) and is therefore the best match. return !methodSymbol.CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(this.Compilation, this.Conversions, includeNullability: false, node.Location, diagnostics)); } /// <summary> /// Performs the following checks: /// /// Spec 7.6.5: Invocation expressions (definition of Final Validation) /// The method is validated in the context of the method group: If the best method is a static method, /// the method group must have resulted from a simple-name or a member-access through a type. If the best /// method is an instance method, the method group must have resulted from a simple-name, a member-access /// through a variable or value, or a base-access. If neither of these requirements is true, a binding-time /// error occurs. /// (Note that the spec omits to mention, in the case of an instance method invoked through a simple name, that /// the invocation must appear within the body of an instance method) /// /// Spec 7.5.4: Compile-time checking of dynamic overload resolution /// If F is a static method, the method group must have resulted from a simple-name, a member-access through a type, /// or a member-access whose receiver can't be classified as a type or value until after overload resolution (see §7.6.4.1). /// If F is an instance method, the method group must have resulted from a simple-name, a member-access through a variable or value, /// or a member-access whose receiver can't be classified as a type or value until after overload resolution (see §7.6.4.1). /// </summary> /// <returns> /// True if there is any error. /// </returns> private bool MemberGroupFinalValidationAccessibilityChecks(BoundExpression? receiverOpt, Symbol memberSymbol, SyntaxNode node, BindingDiagnosticBag diagnostics, bool invokedAsExtensionMethod) { // Perform final validation of the method to be invoked. Debug.Assert(memberSymbol.Kind != SymbolKind.Method || memberSymbol.CanBeReferencedByName); //note that the same assert does not hold for all properties. Some properties and (all indexers) are not referenceable by name, yet //their binding brings them through here, perhaps needlessly. if (IsTypeOrValueExpression(receiverOpt)) { // TypeOrValue expression isn't replaced only if the invocation is late bound, in which case it can't be extension method. // None of the checks below apply if the receiver can't be classified as a type or value. Debug.Assert(!invokedAsExtensionMethod); } else if (!memberSymbol.RequiresInstanceReceiver()) { Debug.Assert(!invokedAsExtensionMethod || (receiverOpt != null)); if (invokedAsExtensionMethod) { if (IsMemberAccessedThroughType(receiverOpt)) { if (receiverOpt.Kind == BoundKind.QueryClause) { RoslynDebug.Assert(receiverOpt.Type is object); // Could not find an implementation of the query pattern for source type '{0}'. '{1}' not found. diagnostics.Add(ErrorCode.ERR_QueryNoProvider, node.Location, receiverOpt.Type, memberSymbol.Name); } else { // An object reference is required for the non-static field, method, or property '{0}' diagnostics.Add(ErrorCode.ERR_ObjectRequired, node.Location, memberSymbol); } return true; } } else if (!WasImplicitReceiver(receiverOpt) && IsMemberAccessedThroughVariableOrValue(receiverOpt)) { if (this.Flags.Includes(BinderFlags.CollectionInitializerAddMethod)) { diagnostics.Add(ErrorCode.ERR_InitializerAddHasWrongSignature, node.Location, memberSymbol); } else if (node.Kind() == SyntaxKind.AwaitExpression && memberSymbol.Name == WellKnownMemberNames.GetAwaiter) { RoslynDebug.Assert(receiverOpt.Type is object); diagnostics.Add(ErrorCode.ERR_BadAwaitArg, node.Location, receiverOpt.Type); } else { diagnostics.Add(ErrorCode.ERR_ObjectProhibited, node.Location, memberSymbol); } return true; } } else if (IsMemberAccessedThroughType(receiverOpt)) { diagnostics.Add(ErrorCode.ERR_ObjectRequired, node.Location, memberSymbol); return true; } else if (WasImplicitReceiver(receiverOpt)) { if (InFieldInitializer && !ContainingType!.IsScriptClass || InConstructorInitializer || InAttributeArgument) { SyntaxNode errorNode = node; if (node.Parent != null && node.Parent.Kind() == SyntaxKind.InvocationExpression) { errorNode = node.Parent; } ErrorCode code = InFieldInitializer ? ErrorCode.ERR_FieldInitRefNonstatic : ErrorCode.ERR_ObjectRequired; diagnostics.Add(code, errorNode.Location, memberSymbol); return true; } // If we could access the member through implicit "this" the receiver would be a BoundThisReference. // If it is null it means that the instance member is inaccessible. if (receiverOpt == null || ContainingMember().IsStatic) { Error(diagnostics, ErrorCode.ERR_ObjectRequired, node, memberSymbol); return true; } } var containingType = this.ContainingType; if (containingType is object) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); bool isAccessible = this.IsSymbolAccessibleConditional(memberSymbol.GetTypeOrReturnType().Type, containingType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!isAccessible) { // In the presence of non-transitive [InternalsVisibleTo] in source, or obnoxious symbols from metadata, it is possible // to select a method through overload resolution in which the type is not accessible. In this case a method cannot // be called through normal IL, so we give an error. Neither [InternalsVisibleTo] nor the need for this diagnostic is // described by the language specification. // // Dev11 perform different access checks. See bug #530360 and tests AccessCheckTests.InaccessibleReturnType. Error(diagnostics, ErrorCode.ERR_BadAccess, node, memberSymbol); return true; } } return false; } private static bool IsMemberAccessedThroughVariableOrValue(BoundExpression? receiverOpt) { if (receiverOpt == null) { return false; } return !IsMemberAccessedThroughType(receiverOpt); } internal static bool IsMemberAccessedThroughType([NotNullWhen(true)] BoundExpression? receiverOpt) { if (receiverOpt == null) { return false; } while (receiverOpt.Kind == BoundKind.QueryClause) { receiverOpt = ((BoundQueryClause)receiverOpt).Value; } return receiverOpt.Kind == BoundKind.TypeExpression; } /// <summary> /// Was the receiver expression compiler-generated? /// </summary> internal static bool WasImplicitReceiver([NotNullWhen(false)] BoundExpression? receiverOpt) { if (receiverOpt == null) return true; if (!receiverOpt.WasCompilerGenerated) return false; switch (receiverOpt.Kind) { case BoundKind.ThisReference: case BoundKind.HostObjectMemberReference: case BoundKind.PreviousSubmissionReference: return true; default: return false; } } /// <summary> /// This method implements the checks in spec section 15.2. /// </summary> internal bool MethodIsCompatibleWithDelegateOrFunctionPointer(BoundExpression? receiverOpt, bool isExtensionMethod, MethodSymbol method, TypeSymbol delegateType, Location errorLocation, BindingDiagnosticBag diagnostics) { Debug.Assert(delegateType is NamedTypeSymbol { TypeKind: TypeKind.Delegate, DelegateInvokeMethod: { HasUseSiteError: false } } || delegateType.TypeKind == TypeKind.FunctionPointer, "This method should only be called for valid delegate or function pointer types."); MethodSymbol delegateOrFuncPtrMethod = delegateType switch { NamedTypeSymbol { DelegateInvokeMethod: { } invokeMethod } => invokeMethod, FunctionPointerTypeSymbol { Signature: { } signature } => signature, _ => throw ExceptionUtilities.UnexpectedValue(delegateType), }; Debug.Assert(!isExtensionMethod || (receiverOpt != null)); // - Argument types "match", and var delegateOrFuncPtrParameters = delegateOrFuncPtrMethod.Parameters; var methodParameters = method.Parameters; int numParams = delegateOrFuncPtrParameters.Length; if (methodParameters.Length != numParams + (isExtensionMethod ? 1 : 0)) { // This can happen if "method" has optional parameters. Debug.Assert(methodParameters.Length > numParams + (isExtensionMethod ? 1 : 0)); Error(diagnostics, getMethodMismatchErrorCode(delegateType.TypeKind), errorLocation, method, delegateType); return false; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); // If this is an extension method delegate, the caller should have verified the // receiver is compatible with the "this" parameter of the extension method. Debug.Assert(!isExtensionMethod || (Conversions.ConvertExtensionMethodThisArg(methodParameters[0].Type, receiverOpt!.Type, ref useSiteInfo).Exists && useSiteInfo.Diagnostics.IsNullOrEmpty())); useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(useSiteInfo); for (int i = 0; i < numParams; i++) { var delegateParameter = delegateOrFuncPtrParameters[i]; var methodParameter = methodParameters[isExtensionMethod ? i + 1 : i]; // The delegate compatibility checks are stricter than the checks on applicable functions: it's possible // to get here with a method that, while all the parameters are applicable, is not actually delegate // compatible. This is because the Applicable function member spec requires that: // * Every value parameter (non-ref or similar) from the delegate type has an implicit conversion to the corresponding // target parameter // * Every ref or similar parameter has an identity conversion to the corresponding target parameter // However, the delegate compatibility requirements are stricter: // * Every value parameter (non-ref or similar) from the delegate type has an implicit _reference_ conversion to the // corresponding target parameter. // * Every ref or similar parameter has an identity conversion to the corresponding target parameter // Note the addition of the reference requirement: it means that for delegate type void D(int i), void M(long l) is // _applicable_, but not _compatible_. if (!hasConversion(delegateType.TypeKind, Conversions, delegateParameter.Type, methodParameter.Type, delegateParameter.RefKind, methodParameter.RefKind, ref useSiteInfo)) { // No overload for '{0}' matches delegate '{1}' Error(diagnostics, getMethodMismatchErrorCode(delegateType.TypeKind), errorLocation, method, delegateType); diagnostics.Add(errorLocation, useSiteInfo); return false; } } if (delegateOrFuncPtrMethod.RefKind != method.RefKind) { Error(diagnostics, getRefMismatchErrorCode(delegateType.TypeKind), errorLocation, method, delegateType); diagnostics.Add(errorLocation, useSiteInfo); return false; } var methodReturnType = method.ReturnType; var delegateReturnType = delegateOrFuncPtrMethod.ReturnType; bool returnsMatch = delegateOrFuncPtrMethod switch { { RefKind: RefKind.None, ReturnsVoid: true } => method.ReturnsVoid, { RefKind: var destinationRefKind } => hasConversion(delegateType.TypeKind, Conversions, methodReturnType, delegateReturnType, method.RefKind, destinationRefKind, ref useSiteInfo), }; if (!returnsMatch) { Error(diagnostics, ErrorCode.ERR_BadRetType, errorLocation, method, method.ReturnType); diagnostics.Add(errorLocation, useSiteInfo); return false; } if (delegateType.IsFunctionPointer()) { if (isExtensionMethod) { Error(diagnostics, ErrorCode.ERR_CannotUseReducedExtensionMethodInAddressOf, errorLocation); diagnostics.Add(errorLocation, useSiteInfo); return false; } if (!method.IsStatic) { // This check is here purely for completeness of implementing the spec. It should // never be hit, as static methods should be eliminated as candidates in overload // resolution and should never make it to this point. Debug.Fail("This method should have been eliminated in overload resolution!"); Error(diagnostics, ErrorCode.ERR_FuncPtrMethMustBeStatic, errorLocation, method); diagnostics.Add(errorLocation, useSiteInfo); return false; } } diagnostics.Add(errorLocation, useSiteInfo); return true; static bool hasConversion(TypeKind targetKind, Conversions conversions, TypeSymbol source, TypeSymbol destination, RefKind sourceRefKind, RefKind destinationRefKind, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (sourceRefKind != destinationRefKind) { return false; } if (sourceRefKind != RefKind.None) { return ConversionsBase.HasIdentityConversion(source, destination); } if (conversions.HasIdentityOrImplicitReferenceConversion(source, destination, ref useSiteInfo)) { return true; } return targetKind == TypeKind.FunctionPointer && (ConversionsBase.HasImplicitPointerToVoidConversion(source, destination) || conversions.HasImplicitPointerConversion(source, destination, ref useSiteInfo)); } static ErrorCode getMethodMismatchErrorCode(TypeKind type) => type switch { TypeKind.Delegate => ErrorCode.ERR_MethDelegateMismatch, TypeKind.FunctionPointer => ErrorCode.ERR_MethFuncPtrMismatch, _ => throw ExceptionUtilities.UnexpectedValue(type) }; static ErrorCode getRefMismatchErrorCode(TypeKind type) => type switch { TypeKind.Delegate => ErrorCode.ERR_DelegateRefMismatch, TypeKind.FunctionPointer => ErrorCode.ERR_FuncPtrRefMismatch, _ => throw ExceptionUtilities.UnexpectedValue(type) }; } /// <summary> /// This method combines final validation (section 7.6.5.1) and delegate compatibility (section 15.2). /// </summary> /// <param name="syntax">CSharpSyntaxNode of the expression requiring method group conversion.</param> /// <param name="conversion">Conversion to be performed.</param> /// <param name="receiverOpt">Optional receiver.</param> /// <param name="isExtensionMethod">Method invoked as extension method.</param> /// <param name="delegateOrFuncPtrType">Target delegate type.</param> /// <param name="diagnostics">Where diagnostics should be added.</param> /// <returns>True if a diagnostic has been added.</returns> private bool MethodGroupConversionHasErrors( SyntaxNode syntax, Conversion conversion, BoundExpression? receiverOpt, bool isExtensionMethod, bool isAddressOf, TypeSymbol delegateOrFuncPtrType, BindingDiagnosticBag diagnostics) { Debug.Assert(delegateOrFuncPtrType.SpecialType == SpecialType.System_Delegate || delegateOrFuncPtrType.TypeKind == TypeKind.Delegate || delegateOrFuncPtrType.TypeKind == TypeKind.FunctionPointer); Debug.Assert(conversion.Method is object); MethodSymbol selectedMethod = conversion.Method; var location = syntax.Location; if (delegateOrFuncPtrType.SpecialType != SpecialType.System_Delegate) { if (!MethodIsCompatibleWithDelegateOrFunctionPointer(receiverOpt, isExtensionMethod, selectedMethod, delegateOrFuncPtrType, location, diagnostics) || MemberGroupFinalValidation(receiverOpt, selectedMethod, syntax, diagnostics, isExtensionMethod)) { return true; } } if (selectedMethod.IsConditional) { // CS1618: Cannot create delegate with '{0}' because it has a Conditional attribute Error(diagnostics, ErrorCode.ERR_DelegateOnConditional, location, selectedMethod); return true; } var sourceMethod = selectedMethod as SourceOrdinaryMethodSymbol; if (sourceMethod is object && sourceMethod.IsPartialWithoutImplementation) { // CS0762: Cannot create delegate from method '{0}' because it is a partial method without an implementing declaration Error(diagnostics, ErrorCode.ERR_PartialMethodToDelegate, location, selectedMethod); return true; } if ((selectedMethod.HasUnsafeParameter() || selectedMethod.ReturnType.IsUnsafe()) && ReportUnsafeIfNotAllowed(syntax, diagnostics)) { return true; } if (!isAddressOf) { ReportDiagnosticsIfUnmanagedCallersOnly(diagnostics, selectedMethod, location, isDelegateConversion: true); } ReportDiagnosticsIfObsolete(diagnostics, selectedMethod, syntax, hasBaseReceiver: false); // No use site errors, but there could be use site warnings. // If there are use site warnings, they were reported during the overload resolution process // that chose selectedMethod. Debug.Assert(!selectedMethod.HasUseSiteError, "Shouldn't have reached this point if there were use site errors."); return false; } /// <summary> /// This method is a wrapper around MethodGroupConversionHasErrors. As a preliminary step, /// it checks whether a conversion exists. /// </summary> private bool MethodGroupConversionDoesNotExistOrHasErrors( BoundMethodGroup boundMethodGroup, NamedTypeSymbol delegateType, Location delegateMismatchLocation, BindingDiagnosticBag diagnostics, out Conversion conversion) { if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, delegateType, delegateMismatchLocation)) { conversion = Conversion.NoConversion; return true; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); conversion = Conversions.GetMethodGroupDelegateConversion(boundMethodGroup, delegateType, ref useSiteInfo); diagnostics.Add(delegateMismatchLocation, useSiteInfo); if (!conversion.Exists) { if (!Conversions.ReportDelegateOrFunctionPointerMethodGroupDiagnostics(this, boundMethodGroup, delegateType, diagnostics)) { // No overload for '{0}' matches delegate '{1}' diagnostics.Add(ErrorCode.ERR_MethDelegateMismatch, delegateMismatchLocation, boundMethodGroup.Name, delegateType); } return true; } else { Debug.Assert(conversion.IsValid); // i.e. if it exists, then it is valid. // Only cares about nullness and type of receiver, so no need to worry about BoundTypeOrValueExpression. return this.MethodGroupConversionHasErrors(boundMethodGroup.Syntax, conversion, boundMethodGroup.ReceiverOpt, conversion.IsExtensionMethod, isAddressOf: false, delegateType, diagnostics); } } public ConstantValue? FoldConstantConversion( SyntaxNode syntax, BoundExpression source, Conversion conversion, TypeSymbol destination, BindingDiagnosticBag diagnostics) { RoslynDebug.Assert(source != null); RoslynDebug.Assert((object)destination != null); // The diagnostics bag can be null in cases where we know ahead of time that the // conversion will succeed without error or warning. (For example, if we have a valid // implicit numeric conversion on a constant of numeric type.) // SPEC: A constant expression must be the null literal or a value with one of // SPEC: the following types: sbyte, byte, short, ushort, int, uint, long, // SPEC: ulong, char, float, double, decimal, bool, string, or any enumeration type. // SPEC: The following conversions are permitted in constant expressions: // SPEC: Identity conversions // SPEC: Numeric conversions // SPEC: Enumeration conversions // SPEC: Constant expression conversions // SPEC: Implicit and explicit reference conversions, provided that the source of the conversions // SPEC: is a constant expression that evaluates to the null value. // SPEC VIOLATION: C# has always allowed the following, even though this does violate the rule that // SPEC VIOLATION: a constant expression must be either the null literal, or an expression of one // SPEC VIOLATION: of the given types. // SPEC VIOLATION: const C c = (C)null; // TODO: Some conversions can produce errors or warnings depending on checked/unchecked. // TODO: Fold conversions on enums and strings too. var sourceConstantValue = source.ConstantValue; if (sourceConstantValue == null) { if (conversion.Kind == ConversionKind.DefaultLiteral) { return destination.GetDefaultValue(); } else { return sourceConstantValue; } } else if (sourceConstantValue.IsBad) { return sourceConstantValue; } if (source.HasAnyErrors) { return null; } switch (conversion.Kind) { case ConversionKind.Identity: // An identity conversion to a floating-point type (for example from a cast in // source code) changes the internal representation of the constant value // to precisely the required precision. switch (destination.SpecialType) { case SpecialType.System_Single: return ConstantValue.Create(sourceConstantValue.SingleValue); case SpecialType.System_Double: return ConstantValue.Create(sourceConstantValue.DoubleValue); default: return sourceConstantValue; } case ConversionKind.NullLiteral: return sourceConstantValue; case ConversionKind.ImplicitConstant: return FoldConstantNumericConversion(syntax, sourceConstantValue, destination, diagnostics); case ConversionKind.ExplicitNumeric: case ConversionKind.ImplicitNumeric: case ConversionKind.ExplicitEnumeration: case ConversionKind.ImplicitEnumeration: // The C# specification categorizes conversion from literal zero to nullable enum as // an Implicit Enumeration Conversion. Such a thing should not be constant folded // because nullable enums are never constants. if (destination.IsNullableType()) { return null; } return FoldConstantNumericConversion(syntax, sourceConstantValue, destination, diagnostics); case ConversionKind.ExplicitReference: case ConversionKind.ImplicitReference: return sourceConstantValue.IsNull ? sourceConstantValue : null; } return null; } private ConstantValue? FoldConstantNumericConversion( SyntaxNode syntax, ConstantValue sourceValue, TypeSymbol destination, BindingDiagnosticBag diagnostics) { RoslynDebug.Assert(sourceValue != null); Debug.Assert(!sourceValue.IsBad); SpecialType destinationType; if ((object)destination != null && destination.IsEnumType()) { var underlyingType = ((NamedTypeSymbol)destination).EnumUnderlyingType; RoslynDebug.Assert((object)underlyingType != null); Debug.Assert(underlyingType.SpecialType != SpecialType.None); destinationType = underlyingType.SpecialType; } else { destinationType = destination.GetSpecialTypeSafe(); } // In an unchecked context we ignore overflowing conversions on conversions from any // integral type, float and double to any integral type. "unchecked" actually does not // affect conversions from decimal to any integral type; if those are out of bounds then // we always give an error regardless. if (sourceValue.IsDecimal) { if (!CheckConstantBounds(destinationType, sourceValue, out _)) { // NOTE: Dev10 puts a suffix, "M", on the constant value. Error(diagnostics, ErrorCode.ERR_ConstOutOfRange, syntax, sourceValue.Value + "M", destination!); return ConstantValue.Bad; } } else if (destinationType == SpecialType.System_Decimal) { if (!CheckConstantBounds(destinationType, sourceValue, out _)) { Error(diagnostics, ErrorCode.ERR_ConstOutOfRange, syntax, sourceValue.Value!, destination!); return ConstantValue.Bad; } } else if (CheckOverflowAtCompileTime) { if (!CheckConstantBounds(destinationType, sourceValue, out bool maySucceedAtRuntime)) { if (maySucceedAtRuntime) { // Can be calculated at runtime, but is not a compile-time constant. Error(diagnostics, ErrorCode.WRN_ConstOutOfRangeChecked, syntax, sourceValue.Value!, destination!); return null; } else { Error(diagnostics, ErrorCode.ERR_ConstOutOfRangeChecked, syntax, sourceValue.Value!, destination!); return ConstantValue.Bad; } } } else if (destinationType == SpecialType.System_IntPtr || destinationType == SpecialType.System_UIntPtr) { if (!CheckConstantBounds(destinationType, sourceValue, out _)) { // Can be calculated at runtime, but is not a compile-time constant. return null; } } return ConstantValue.Create(DoUncheckedConversion(destinationType, sourceValue), destinationType); } private static object DoUncheckedConversion(SpecialType destinationType, ConstantValue value) { // Note that we keep "single" floats as doubles internally to maintain higher precision. However, // we do not do so in an entirely "lossless" manner. When *converting* to a float, we do lose // the precision lost due to the conversion. But when doing arithmetic, we do the arithmetic on // the double values. // // An example will help. Suppose we have: // // const float cf1 = 1.0f; // const float cf2 = 1.0e-15f; // const double cd3 = cf1 - cf2; // // We first take the double-precision values for 1.0 and 1.0e-15 and round them to floats, // and then turn them back into doubles. Then when we do the subtraction, we do the subtraction // in doubles, not in floats. Had we done the subtraction in floats, we'd get 1.0; but instead we // do it in doubles and get 0.99999999999999. // // Similarly, if we have // // const int i4 = int.MaxValue; // 2147483647 // const float cf5 = int.MaxValue; // 2147483648.0 // const double cd6 = cf5; // 2147483648.0 // // The int is converted to float and stored internally as the double 214783648, even though the // fully precise int would fit into a double. unchecked { switch (value.Discriminator) { case ConstantValueTypeDiscriminator.Byte: byte byteValue = value.ByteValue; switch (destinationType) { case SpecialType.System_Byte: return (byte)byteValue; case SpecialType.System_Char: return (char)byteValue; case SpecialType.System_UInt16: return (ushort)byteValue; case SpecialType.System_UInt32: return (uint)byteValue; case SpecialType.System_UInt64: return (ulong)byteValue; case SpecialType.System_SByte: return (sbyte)byteValue; case SpecialType.System_Int16: return (short)byteValue; case SpecialType.System_Int32: return (int)byteValue; case SpecialType.System_Int64: return (long)byteValue; case SpecialType.System_IntPtr: return (int)byteValue; case SpecialType.System_UIntPtr: return (uint)byteValue; case SpecialType.System_Single: case SpecialType.System_Double: return (double)byteValue; case SpecialType.System_Decimal: return (decimal)byteValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.Char: char charValue = value.CharValue; switch (destinationType) { case SpecialType.System_Byte: return (byte)charValue; case SpecialType.System_Char: return (char)charValue; case SpecialType.System_UInt16: return (ushort)charValue; case SpecialType.System_UInt32: return (uint)charValue; case SpecialType.System_UInt64: return (ulong)charValue; case SpecialType.System_SByte: return (sbyte)charValue; case SpecialType.System_Int16: return (short)charValue; case SpecialType.System_Int32: return (int)charValue; case SpecialType.System_Int64: return (long)charValue; case SpecialType.System_IntPtr: return (int)charValue; case SpecialType.System_UIntPtr: return (uint)charValue; case SpecialType.System_Single: case SpecialType.System_Double: return (double)charValue; case SpecialType.System_Decimal: return (decimal)charValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.UInt16: ushort uint16Value = value.UInt16Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)uint16Value; case SpecialType.System_Char: return (char)uint16Value; case SpecialType.System_UInt16: return (ushort)uint16Value; case SpecialType.System_UInt32: return (uint)uint16Value; case SpecialType.System_UInt64: return (ulong)uint16Value; case SpecialType.System_SByte: return (sbyte)uint16Value; case SpecialType.System_Int16: return (short)uint16Value; case SpecialType.System_Int32: return (int)uint16Value; case SpecialType.System_Int64: return (long)uint16Value; case SpecialType.System_IntPtr: return (int)uint16Value; case SpecialType.System_UIntPtr: return (uint)uint16Value; case SpecialType.System_Single: case SpecialType.System_Double: return (double)uint16Value; case SpecialType.System_Decimal: return (decimal)uint16Value; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.UInt32: uint uint32Value = value.UInt32Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)uint32Value; case SpecialType.System_Char: return (char)uint32Value; case SpecialType.System_UInt16: return (ushort)uint32Value; case SpecialType.System_UInt32: return (uint)uint32Value; case SpecialType.System_UInt64: return (ulong)uint32Value; case SpecialType.System_SByte: return (sbyte)uint32Value; case SpecialType.System_Int16: return (short)uint32Value; case SpecialType.System_Int32: return (int)uint32Value; case SpecialType.System_Int64: return (long)uint32Value; case SpecialType.System_IntPtr: return (int)uint32Value; case SpecialType.System_UIntPtr: return (uint)uint32Value; case SpecialType.System_Single: return (double)(float)uint32Value; case SpecialType.System_Double: return (double)uint32Value; case SpecialType.System_Decimal: return (decimal)uint32Value; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.UInt64: ulong uint64Value = value.UInt64Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)uint64Value; case SpecialType.System_Char: return (char)uint64Value; case SpecialType.System_UInt16: return (ushort)uint64Value; case SpecialType.System_UInt32: return (uint)uint64Value; case SpecialType.System_UInt64: return (ulong)uint64Value; case SpecialType.System_SByte: return (sbyte)uint64Value; case SpecialType.System_Int16: return (short)uint64Value; case SpecialType.System_Int32: return (int)uint64Value; case SpecialType.System_Int64: return (long)uint64Value; case SpecialType.System_IntPtr: return (int)uint64Value; case SpecialType.System_UIntPtr: return (uint)uint64Value; case SpecialType.System_Single: return (double)(float)uint64Value; case SpecialType.System_Double: return (double)uint64Value; case SpecialType.System_Decimal: return (decimal)uint64Value; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.NUInt: uint nuintValue = value.UInt32Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)nuintValue; case SpecialType.System_Char: return (char)nuintValue; case SpecialType.System_UInt16: return (ushort)nuintValue; case SpecialType.System_UInt32: return (uint)nuintValue; case SpecialType.System_UInt64: return (ulong)nuintValue; case SpecialType.System_SByte: return (sbyte)nuintValue; case SpecialType.System_Int16: return (short)nuintValue; case SpecialType.System_Int32: return (int)nuintValue; case SpecialType.System_Int64: return (long)nuintValue; case SpecialType.System_IntPtr: return (int)nuintValue; case SpecialType.System_Single: return (double)(float)nuintValue; case SpecialType.System_Double: return (double)nuintValue; case SpecialType.System_Decimal: return (decimal)nuintValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.SByte: sbyte sbyteValue = value.SByteValue; switch (destinationType) { case SpecialType.System_Byte: return (byte)sbyteValue; case SpecialType.System_Char: return (char)sbyteValue; case SpecialType.System_UInt16: return (ushort)sbyteValue; case SpecialType.System_UInt32: return (uint)sbyteValue; case SpecialType.System_UInt64: return (ulong)sbyteValue; case SpecialType.System_SByte: return (sbyte)sbyteValue; case SpecialType.System_Int16: return (short)sbyteValue; case SpecialType.System_Int32: return (int)sbyteValue; case SpecialType.System_Int64: return (long)sbyteValue; case SpecialType.System_IntPtr: return (int)sbyteValue; case SpecialType.System_UIntPtr: return (uint)sbyteValue; case SpecialType.System_Single: case SpecialType.System_Double: return (double)sbyteValue; case SpecialType.System_Decimal: return (decimal)sbyteValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.Int16: short int16Value = value.Int16Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)int16Value; case SpecialType.System_Char: return (char)int16Value; case SpecialType.System_UInt16: return (ushort)int16Value; case SpecialType.System_UInt32: return (uint)int16Value; case SpecialType.System_UInt64: return (ulong)int16Value; case SpecialType.System_SByte: return (sbyte)int16Value; case SpecialType.System_Int16: return (short)int16Value; case SpecialType.System_Int32: return (int)int16Value; case SpecialType.System_Int64: return (long)int16Value; case SpecialType.System_IntPtr: return (int)int16Value; case SpecialType.System_UIntPtr: return (uint)int16Value; case SpecialType.System_Single: case SpecialType.System_Double: return (double)int16Value; case SpecialType.System_Decimal: return (decimal)int16Value; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.Int32: int int32Value = value.Int32Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)int32Value; case SpecialType.System_Char: return (char)int32Value; case SpecialType.System_UInt16: return (ushort)int32Value; case SpecialType.System_UInt32: return (uint)int32Value; case SpecialType.System_UInt64: return (ulong)int32Value; case SpecialType.System_SByte: return (sbyte)int32Value; case SpecialType.System_Int16: return (short)int32Value; case SpecialType.System_Int32: return (int)int32Value; case SpecialType.System_Int64: return (long)int32Value; case SpecialType.System_IntPtr: return (int)int32Value; case SpecialType.System_UIntPtr: return (uint)int32Value; case SpecialType.System_Single: return (double)(float)int32Value; case SpecialType.System_Double: return (double)int32Value; case SpecialType.System_Decimal: return (decimal)int32Value; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.Int64: long int64Value = value.Int64Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)int64Value; case SpecialType.System_Char: return (char)int64Value; case SpecialType.System_UInt16: return (ushort)int64Value; case SpecialType.System_UInt32: return (uint)int64Value; case SpecialType.System_UInt64: return (ulong)int64Value; case SpecialType.System_SByte: return (sbyte)int64Value; case SpecialType.System_Int16: return (short)int64Value; case SpecialType.System_Int32: return (int)int64Value; case SpecialType.System_Int64: return (long)int64Value; case SpecialType.System_IntPtr: return (int)int64Value; case SpecialType.System_UIntPtr: return (uint)int64Value; case SpecialType.System_Single: return (double)(float)int64Value; case SpecialType.System_Double: return (double)int64Value; case SpecialType.System_Decimal: return (decimal)int64Value; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.NInt: int nintValue = value.Int32Value; switch (destinationType) { case SpecialType.System_Byte: return (byte)nintValue; case SpecialType.System_Char: return (char)nintValue; case SpecialType.System_UInt16: return (ushort)nintValue; case SpecialType.System_UInt32: return (uint)nintValue; case SpecialType.System_UInt64: return (ulong)nintValue; case SpecialType.System_SByte: return (sbyte)nintValue; case SpecialType.System_Int16: return (short)nintValue; case SpecialType.System_Int32: return (int)nintValue; case SpecialType.System_Int64: return (long)nintValue; case SpecialType.System_IntPtr: return (int)nintValue; case SpecialType.System_UIntPtr: return (uint)nintValue; case SpecialType.System_Single: return (double)(float)nintValue; case SpecialType.System_Double: return (double)nintValue; case SpecialType.System_Decimal: return (decimal)nintValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.Single: case ConstantValueTypeDiscriminator.Double: // When converting from a floating-point type to an integral type, if the checked conversion would // throw an overflow exception, then the unchecked conversion is undefined. So that we have // identical behavior on every host platform, we yield a result of zero in that case. double doubleValue = CheckConstantBounds(destinationType, value.DoubleValue, out _) ? value.DoubleValue : 0D; switch (destinationType) { case SpecialType.System_Byte: return (byte)doubleValue; case SpecialType.System_Char: return (char)doubleValue; case SpecialType.System_UInt16: return (ushort)doubleValue; case SpecialType.System_UInt32: return (uint)doubleValue; case SpecialType.System_UInt64: return (ulong)doubleValue; case SpecialType.System_SByte: return (sbyte)doubleValue; case SpecialType.System_Int16: return (short)doubleValue; case SpecialType.System_Int32: return (int)doubleValue; case SpecialType.System_Int64: return (long)doubleValue; case SpecialType.System_IntPtr: return (int)doubleValue; case SpecialType.System_UIntPtr: return (uint)doubleValue; case SpecialType.System_Single: return (double)(float)doubleValue; case SpecialType.System_Double: return (double)doubleValue; case SpecialType.System_Decimal: return (value.Discriminator == ConstantValueTypeDiscriminator.Single) ? (decimal)(float)doubleValue : (decimal)doubleValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } case ConstantValueTypeDiscriminator.Decimal: decimal decimalValue = CheckConstantBounds(destinationType, value.DecimalValue, out _) ? value.DecimalValue : 0m; switch (destinationType) { case SpecialType.System_Byte: return (byte)decimalValue; case SpecialType.System_Char: return (char)decimalValue; case SpecialType.System_UInt16: return (ushort)decimalValue; case SpecialType.System_UInt32: return (uint)decimalValue; case SpecialType.System_UInt64: return (ulong)decimalValue; case SpecialType.System_SByte: return (sbyte)decimalValue; case SpecialType.System_Int16: return (short)decimalValue; case SpecialType.System_Int32: return (int)decimalValue; case SpecialType.System_Int64: return (long)decimalValue; case SpecialType.System_IntPtr: return (int)decimalValue; case SpecialType.System_UIntPtr: return (uint)decimalValue; case SpecialType.System_Single: return (double)(float)decimalValue; case SpecialType.System_Double: return (double)decimalValue; case SpecialType.System_Decimal: return (decimal)decimalValue; default: throw ExceptionUtilities.UnexpectedValue(destinationType); } default: throw ExceptionUtilities.UnexpectedValue(value.Discriminator); } } // all cases should have been handled in the switch above. // return value.Value; } public static bool CheckConstantBounds(SpecialType destinationType, ConstantValue value, out bool maySucceedAtRuntime) { if (value.IsBad) { //assume that the constant was intended to be in bounds maySucceedAtRuntime = false; return true; } // Compute whether the value fits into the bounds of the given destination type without // error. We know that the constant will fit into either a double or a decimal, so // convert it to one of those and then check the bounds on that. var canonicalValue = CanonicalizeConstant(value); return canonicalValue is decimal ? CheckConstantBounds(destinationType, (decimal)canonicalValue, out maySucceedAtRuntime) : CheckConstantBounds(destinationType, (double)canonicalValue, out maySucceedAtRuntime); } private static bool CheckConstantBounds(SpecialType destinationType, double value, out bool maySucceedAtRuntime) { maySucceedAtRuntime = false; // Dev10 checks (minValue - 1) < value < (maxValue + 1). // See ExpressionBinder::isConstantInRange. switch (destinationType) { case SpecialType.System_Byte: return (byte.MinValue - 1D) < value && value < (byte.MaxValue + 1D); case SpecialType.System_Char: return (char.MinValue - 1D) < value && value < (char.MaxValue + 1D); case SpecialType.System_UInt16: return (ushort.MinValue - 1D) < value && value < (ushort.MaxValue + 1D); case SpecialType.System_UInt32: return (uint.MinValue - 1D) < value && value < (uint.MaxValue + 1D); case SpecialType.System_UInt64: return (ulong.MinValue - 1D) < value && value < (ulong.MaxValue + 1D); case SpecialType.System_SByte: return (sbyte.MinValue - 1D) < value && value < (sbyte.MaxValue + 1D); case SpecialType.System_Int16: return (short.MinValue - 1D) < value && value < (short.MaxValue + 1D); case SpecialType.System_Int32: return (int.MinValue - 1D) < value && value < (int.MaxValue + 1D); // Note: Using <= to compare the min value matches the native compiler. case SpecialType.System_Int64: return (long.MinValue - 1D) <= value && value < (long.MaxValue + 1D); case SpecialType.System_Decimal: return ((double)decimal.MinValue - 1D) < value && value < ((double)decimal.MaxValue + 1D); case SpecialType.System_IntPtr: maySucceedAtRuntime = (long.MinValue - 1D) < value && value < (long.MaxValue + 1D); return (int.MinValue - 1D) < value && value < (int.MaxValue + 1D); case SpecialType.System_UIntPtr: maySucceedAtRuntime = (ulong.MinValue - 1D) < value && value < (ulong.MaxValue + 1D); return (uint.MinValue - 1D) < value && value < (uint.MaxValue + 1D); } return true; } private static bool CheckConstantBounds(SpecialType destinationType, decimal value, out bool maySucceedAtRuntime) { maySucceedAtRuntime = false; // Dev10 checks (minValue - 1) < value < (maxValue + 1). // See ExpressionBinder::isConstantInRange. switch (destinationType) { case SpecialType.System_Byte: return (byte.MinValue - 1M) < value && value < (byte.MaxValue + 1M); case SpecialType.System_Char: return (char.MinValue - 1M) < value && value < (char.MaxValue + 1M); case SpecialType.System_UInt16: return (ushort.MinValue - 1M) < value && value < (ushort.MaxValue + 1M); case SpecialType.System_UInt32: return (uint.MinValue - 1M) < value && value < (uint.MaxValue + 1M); case SpecialType.System_UInt64: return (ulong.MinValue - 1M) < value && value < (ulong.MaxValue + 1M); case SpecialType.System_SByte: return (sbyte.MinValue - 1M) < value && value < (sbyte.MaxValue + 1M); case SpecialType.System_Int16: return (short.MinValue - 1M) < value && value < (short.MaxValue + 1M); case SpecialType.System_Int32: return (int.MinValue - 1M) < value && value < (int.MaxValue + 1M); case SpecialType.System_Int64: return (long.MinValue - 1M) < value && value < (long.MaxValue + 1M); case SpecialType.System_IntPtr: maySucceedAtRuntime = (long.MinValue - 1M) < value && value < (long.MaxValue + 1M); return (int.MinValue - 1M) < value && value < (int.MaxValue + 1M); case SpecialType.System_UIntPtr: maySucceedAtRuntime = (ulong.MinValue - 1M) < value && value < (ulong.MaxValue + 1M); return (uint.MinValue - 1M) < value && value < (uint.MaxValue + 1M); } return true; } // Takes in a constant of any kind and returns the constant as either a double or decimal private static object CanonicalizeConstant(ConstantValue value) { switch (value.Discriminator) { case ConstantValueTypeDiscriminator.SByte: return (decimal)value.SByteValue; case ConstantValueTypeDiscriminator.Int16: return (decimal)value.Int16Value; case ConstantValueTypeDiscriminator.Int32: return (decimal)value.Int32Value; case ConstantValueTypeDiscriminator.Int64: return (decimal)value.Int64Value; case ConstantValueTypeDiscriminator.NInt: return (decimal)value.Int32Value; case ConstantValueTypeDiscriminator.Byte: return (decimal)value.ByteValue; case ConstantValueTypeDiscriminator.Char: return (decimal)value.CharValue; case ConstantValueTypeDiscriminator.UInt16: return (decimal)value.UInt16Value; case ConstantValueTypeDiscriminator.UInt32: return (decimal)value.UInt32Value; case ConstantValueTypeDiscriminator.UInt64: return (decimal)value.UInt64Value; case ConstantValueTypeDiscriminator.NUInt: return (decimal)value.UInt32Value; case ConstantValueTypeDiscriminator.Single: case ConstantValueTypeDiscriminator.Double: return value.DoubleValue; case ConstantValueTypeDiscriminator.Decimal: return value.DecimalValue; default: throw ExceptionUtilities.UnexpectedValue(value.Discriminator); } // all cases handled in the switch, above. } } }
1
dotnet/roslyn
55,125
Don't use DefaultInterpolatedStringHandler in expression trees
Introduces a binder flag to track whether we are currently in an expression tree or not. Fixes https://github.com/dotnet/roslyn/issues/55114.
333fred
2021-07-26T22:08:39Z
2021-07-27T19:33:24Z
5840335153dcca42570a853cdacd06d660fe9596
cfc12ce93ce377c4b9581ccf88403e6740d63977
Don't use DefaultInterpolatedStringHandler in expression trees. Introduces a binder flag to track whether we are currently in an expression tree or not. Fixes https://github.com/dotnet/roslyn/issues/55114.
./src/Compilers/CSharp/Portable/Binder/Binder_Expressions.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.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This portion of the binder converts an <see cref="ExpressionSyntax"/> into a <see cref="BoundExpression"/>. /// </summary> internal partial class Binder { /// <summary> /// Determines whether "this" reference is available within the current context. /// </summary> /// <param name="isExplicit">The reference was explicitly specified in syntax.</param> /// <param name="inStaticContext">True if "this" is not available due to the current method/property/field initializer being static.</param> /// <returns>True if a reference to "this" is available.</returns> internal bool HasThis(bool isExplicit, out bool inStaticContext) { var memberOpt = this.ContainingMemberOrLambda?.ContainingNonLambdaMember(); if (memberOpt?.IsStatic == true) { inStaticContext = memberOpt.Kind == SymbolKind.Field || memberOpt.Kind == SymbolKind.Method || memberOpt.Kind == SymbolKind.Property; return false; } inStaticContext = false; if (InConstructorInitializer || InAttributeArgument) { return false; } var containingType = memberOpt?.ContainingType; bool inTopLevelScriptMember = (object)containingType != null && containingType.IsScriptClass; // "this" is not allowed in field initializers (that are not script variable initializers): if (InFieldInitializer && !inTopLevelScriptMember) { return false; } // top-level script code only allows implicit "this" reference: return !inTopLevelScriptMember || !isExplicit; } internal bool InFieldInitializer { get { return this.Flags.Includes(BinderFlags.FieldInitializer); } } internal bool InParameterDefaultValue { get { return this.Flags.Includes(BinderFlags.ParameterDefaultValue); } } protected bool InConstructorInitializer { get { return this.Flags.Includes(BinderFlags.ConstructorInitializer); } } internal bool InAttributeArgument { get { return this.Flags.Includes(BinderFlags.AttributeArgument); } } internal bool InCref { get { return this.Flags.Includes(BinderFlags.Cref); } } protected bool InCrefButNotParameterOrReturnType { get { return InCref && !this.Flags.Includes(BinderFlags.CrefParameterOrReturnType); } } /// <summary> /// Returns true if the node is in a position where an unbound type /// such as (C&lt;,&gt;) is allowed. /// </summary> protected virtual bool IsUnboundTypeAllowed(GenericNameSyntax syntax) { return Next.IsUnboundTypeAllowed(syntax); } /// <summary> /// Generates a new <see cref="BoundBadExpression"/> with no known type /// </summary> private BoundBadExpression BadExpression(SyntaxNode syntax) { return BadExpression(syntax, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty); } /// <summary> /// Generates a new <see cref="BoundBadExpression"/> with no known type, and the given bound child. /// </summary> private BoundBadExpression BadExpression(SyntaxNode syntax, BoundExpression childNode) { return BadExpression(syntax, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, childNode); } /// <summary> /// Generates a new <see cref="BoundBadExpression"/> with no known type, and the given bound children. /// </summary> private BoundBadExpression BadExpression(SyntaxNode syntax, ImmutableArray<BoundExpression> childNodes) { return BadExpression(syntax, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, childNodes); } /// <summary> /// Generates a new <see cref="BoundBadExpression"/> with no known type, given lookup resultKind. /// </summary> protected BoundBadExpression BadExpression(SyntaxNode syntax, LookupResultKind lookupResultKind) { return BadExpression(syntax, lookupResultKind, ImmutableArray<Symbol>.Empty); } /// <summary> /// Generates a new <see cref="BoundBadExpression"/> with no known type, given lookup resultKind and the given bound child. /// </summary> protected BoundBadExpression BadExpression(SyntaxNode syntax, LookupResultKind lookupResultKind, BoundExpression childNode) { return BadExpression(syntax, lookupResultKind, ImmutableArray<Symbol>.Empty, childNode); } /// <summary> /// Generates a new <see cref="BoundBadExpression"/> with no known type, given lookupResultKind and given symbols for GetSemanticInfo API. /// </summary> private BoundBadExpression BadExpression(SyntaxNode syntax, LookupResultKind resultKind, ImmutableArray<Symbol> symbols) { return new BoundBadExpression(syntax, resultKind, symbols, ImmutableArray<BoundExpression>.Empty, CreateErrorType()); } /// <summary> /// Generates a new <see cref="BoundBadExpression"/> with no known type, given lookupResultKind and given symbols for GetSemanticInfo API, /// and the given bound child. /// </summary> private BoundBadExpression BadExpression(SyntaxNode syntax, LookupResultKind resultKind, ImmutableArray<Symbol> symbols, BoundExpression childNode) { return new BoundBadExpression(syntax, resultKind, symbols, ImmutableArray.Create(BindToTypeForErrorRecovery(childNode)), CreateErrorType()); } /// <summary> /// Generates a new <see cref="BoundBadExpression"/> with no known type, given lookupResultKind and given symbols for GetSemanticInfo API, /// and the given bound children. /// </summary> private BoundBadExpression BadExpression(SyntaxNode syntax, LookupResultKind resultKind, ImmutableArray<Symbol> symbols, ImmutableArray<BoundExpression> childNodes, bool wasCompilerGenerated = false) { return new BoundBadExpression(syntax, resultKind, symbols, childNodes.SelectAsArray((e, self) => self.BindToTypeForErrorRecovery(e), this), CreateErrorType()) { WasCompilerGenerated = wasCompilerGenerated }; } /// <summary> /// Helper method to generate a bound expression with HasErrors set to true. /// Returned bound expression is guaranteed to have a non-null type, except when <paramref name="expr"/> is an unbound lambda. /// If <paramref name="expr"/> already has errors and meets the above type requirements, then it is returned unchanged. /// Otherwise, if <paramref name="expr"/> is a BoundBadExpression, then it is updated with the <paramref name="resultKind"/> and non-null type. /// Otherwise, a new <see cref="BoundBadExpression"/> wrapping <paramref name="expr"/> is returned. /// </summary> /// <remarks> /// Returned expression need not be a <see cref="BoundBadExpression"/>, but is guaranteed to have HasErrors set to true. /// </remarks> private BoundExpression ToBadExpression(BoundExpression expr, LookupResultKind resultKind = LookupResultKind.Empty) { Debug.Assert(expr != null); Debug.Assert(resultKind != LookupResultKind.Viable); TypeSymbol resultType = expr.Type; BoundKind exprKind = expr.Kind; if (expr.HasAnyErrors && ((object)resultType != null || exprKind == BoundKind.UnboundLambda || exprKind == BoundKind.DefaultLiteral)) { return expr; } if (exprKind == BoundKind.BadExpression) { var badExpression = (BoundBadExpression)expr; return badExpression.Update(resultKind, badExpression.Symbols, badExpression.ChildBoundNodes, resultType); } else { ArrayBuilder<Symbol> symbols = ArrayBuilder<Symbol>.GetInstance(); expr.GetExpressionSymbols(symbols, parent: null, binder: this); return new BoundBadExpression( expr.Syntax, resultKind, symbols.ToImmutableAndFree(), ImmutableArray.Create(BindToTypeForErrorRecovery(expr)), resultType ?? CreateErrorType()); } } internal NamedTypeSymbol CreateErrorType(string name = "") { return new ExtendedErrorTypeSymbol(this.Compilation, name, arity: 0, errorInfo: null, unreported: false); } /// <summary> /// Bind the expression and verify the expression matches the combination of lvalue and /// rvalue requirements given by valueKind. If the expression was bound successfully, but /// did not meet the requirements, the return value will be a <see cref="BoundBadExpression"/> that /// (typically) wraps the subexpression. /// </summary> internal BoundExpression BindValue(ExpressionSyntax node, BindingDiagnosticBag diagnostics, BindValueKind valueKind) { var result = this.BindExpression(node, diagnostics: diagnostics, invoked: false, indexed: false); return CheckValue(result, valueKind, diagnostics); } internal BoundExpression BindRValueWithoutTargetType(ExpressionSyntax node, BindingDiagnosticBag diagnostics, bool reportNoTargetType = true) { return BindToNaturalType(BindValue(node, diagnostics, BindValueKind.RValue), diagnostics, reportNoTargetType); } /// <summary> /// When binding a switch case's expression, it is possible that it resolves to a type (technically, a type pattern). /// This implementation permits either an rvalue or a BoundTypeExpression. /// </summary> internal BoundExpression BindTypeOrRValue(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { var valueOrType = BindExpression(node, diagnostics: diagnostics, invoked: false, indexed: false); if (valueOrType.Kind == BoundKind.TypeExpression) { // In the Color Color case (Kind == BoundKind.TypeOrValueExpression), we treat it as a value // by not entering this if statement return valueOrType; } return CheckValue(valueOrType, BindValueKind.RValue, diagnostics); } internal BoundExpression BindToTypeForErrorRecovery(BoundExpression expression, TypeSymbol type = null) { if (expression is null) return null; var result = !expression.NeedsToBeConverted() ? expression : type is null ? BindToNaturalType(expression, BindingDiagnosticBag.Discarded, reportNoTargetType: false) : GenerateConversionForAssignment(type, expression, BindingDiagnosticBag.Discarded); return result; } /// <summary> /// Bind an rvalue expression to its natural type. For example, a switch expression that has not been /// converted to another type has to be converted to its own natural type by applying a conversion to /// that type to each of the arms of the switch expression. This method is a bottleneck for ensuring /// that such a conversion occurs when needed. It also handles tuple expressions which need to be /// converted to their own natural type because they may contain switch expressions. /// </summary> internal BoundExpression BindToNaturalType(BoundExpression expression, BindingDiagnosticBag diagnostics, bool reportNoTargetType = true) { if (!expression.NeedsToBeConverted()) return expression; BoundExpression result; switch (expression) { case BoundUnconvertedSwitchExpression expr: { var commonType = expr.Type; var exprSyntax = (SwitchExpressionSyntax)expr.Syntax; bool hasErrors = expression.HasErrors; if (commonType is null) { diagnostics.Add(ErrorCode.ERR_SwitchExpressionNoBestType, exprSyntax.SwitchKeyword.GetLocation()); commonType = CreateErrorType(); hasErrors = true; } result = ConvertSwitchExpression(expr, commonType, conversionIfTargetTyped: null, diagnostics, hasErrors); } break; case BoundUnconvertedConditionalOperator op: { TypeSymbol type = op.Type; bool hasErrors = op.HasErrors; if (type is null) { Debug.Assert(op.NoCommonTypeError != 0); type = CreateErrorType(); hasErrors = true; object trueArg = op.Consequence.Display; object falseArg = op.Alternative.Display; if (op.NoCommonTypeError == ErrorCode.ERR_InvalidQM && trueArg is Symbol trueSymbol && falseArg is Symbol falseSymbol) { // ERR_InvalidQM is an error that there is no conversion between the two types. They might be the same // type name from different assemblies, so we disambiguate the display. SymbolDistinguisher distinguisher = new SymbolDistinguisher(this.Compilation, trueSymbol, falseSymbol); trueArg = distinguisher.First; falseArg = distinguisher.Second; } diagnostics.Add(op.NoCommonTypeError, op.Syntax.Location, trueArg, falseArg); } result = ConvertConditionalExpression(op, type, conversionIfTargetTyped: null, diagnostics, hasErrors); } break; case BoundTupleLiteral sourceTuple: { var boundArgs = ArrayBuilder<BoundExpression>.GetInstance(sourceTuple.Arguments.Length); foreach (var arg in sourceTuple.Arguments) { boundArgs.Add(BindToNaturalType(arg, diagnostics, reportNoTargetType)); } result = new BoundConvertedTupleLiteral( sourceTuple.Syntax, sourceTuple, wasTargetTyped: false, boundArgs.ToImmutableAndFree(), sourceTuple.ArgumentNamesOpt, sourceTuple.InferredNamesOpt, sourceTuple.Type, // same type to keep original element names sourceTuple.HasErrors).WithSuppression(sourceTuple.IsSuppressed); } break; case BoundDefaultLiteral defaultExpr: { if (reportNoTargetType) { // In some cases, we let the caller report the error diagnostics.Add(ErrorCode.ERR_DefaultLiteralNoTargetType, defaultExpr.Syntax.GetLocation()); } result = new BoundDefaultExpression( defaultExpr.Syntax, targetType: null, defaultExpr.ConstantValue, CreateErrorType(), hasErrors: true).WithSuppression(defaultExpr.IsSuppressed); } break; case BoundStackAllocArrayCreation { Type: null } boundStackAlloc: { // This is a context in which the stackalloc could be either a pointer // or a span. For backward compatibility we treat it as a pointer. var type = new PointerTypeSymbol(TypeWithAnnotations.Create(boundStackAlloc.ElementType)); result = GenerateConversionForAssignment(type, boundStackAlloc, diagnostics); } break; case BoundUnconvertedObjectCreationExpression expr: { if (reportNoTargetType && !expr.HasAnyErrors) { diagnostics.Add(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, expr.Syntax.GetLocation(), expr.Display); } result = BindObjectCreationForErrorRecovery(expr, diagnostics); } break; case BoundUnconvertedInterpolatedString unconvertedInterpolatedString: { result = BindUnconvertedInterpolatedStringToString(unconvertedInterpolatedString, diagnostics); } break; default: result = expression; break; } return result?.WithWasConverted(); } private BoundExpression BindToInferredDelegateType(BoundExpression expr, BindingDiagnosticBag diagnostics) { var syntax = expr.Syntax; CheckFeatureAvailability(syntax, MessageID.IDS_FeatureInferredDelegateType, diagnostics); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var delegateType = expr switch { UnboundLambda unboundLambda => unboundLambda.InferDelegateType(ref useSiteInfo), BoundMethodGroup methodGroup => GetMethodGroupDelegateType(methodGroup, ref useSiteInfo), _ => throw ExceptionUtilities.UnexpectedValue(expr), }; diagnostics.Add(syntax, useSiteInfo); if (delegateType is null) { diagnostics.Add(ErrorCode.ERR_CannotInferDelegateType, syntax.GetLocation()); delegateType = CreateErrorType(); } return GenerateConversionForAssignment(delegateType, expr, diagnostics); } internal BoundExpression BindValueAllowArgList(ExpressionSyntax node, BindingDiagnosticBag diagnostics, BindValueKind valueKind) { var result = this.BindExpressionAllowArgList(node, diagnostics: diagnostics); return CheckValue(result, valueKind, diagnostics); } internal BoundFieldEqualsValue BindFieldInitializer( FieldSymbol field, EqualsValueClauseSyntax initializerOpt, BindingDiagnosticBag diagnostics) { Debug.Assert((object)this.ContainingMemberOrLambda == field); if (initializerOpt == null) { return null; } Binder initializerBinder = this.GetBinder(initializerOpt); Debug.Assert(initializerBinder != null); BoundExpression result = initializerBinder.BindVariableOrAutoPropInitializerValue(initializerOpt, RefKind.None, field.GetFieldType(initializerBinder.FieldsBeingBound).Type, diagnostics); return new BoundFieldEqualsValue(initializerOpt, field, initializerBinder.GetDeclaredLocalsForScope(initializerOpt), result); } internal BoundExpression BindVariableOrAutoPropInitializerValue( EqualsValueClauseSyntax initializerOpt, RefKind refKind, TypeSymbol varType, BindingDiagnosticBag diagnostics) { if (initializerOpt == null) { return null; } BindValueKind valueKind; ExpressionSyntax value; IsInitializerRefKindValid(initializerOpt, initializerOpt, refKind, diagnostics, out valueKind, out value); BoundExpression initializer = BindPossibleArrayInitializer(value, varType, valueKind, diagnostics); initializer = GenerateConversionForAssignment(varType, initializer, diagnostics); return initializer; } internal Binder CreateBinderForParameterDefaultValue( ParameterSymbol parameter, EqualsValueClauseSyntax defaultValueSyntax) { var binder = new LocalScopeBinder(this.WithContainingMemberOrLambda(parameter.ContainingSymbol).WithAdditionalFlags(BinderFlags.ParameterDefaultValue)); return new ExecutableCodeBinder(defaultValueSyntax, parameter.ContainingSymbol, binder); } internal BoundParameterEqualsValue BindParameterDefaultValue( EqualsValueClauseSyntax defaultValueSyntax, ParameterSymbol parameter, BindingDiagnosticBag diagnostics, out BoundExpression valueBeforeConversion) { Debug.Assert(this.InParameterDefaultValue); Debug.Assert(this.ContainingMemberOrLambda.Kind == SymbolKind.Method || this.ContainingMemberOrLambda.Kind == SymbolKind.Property); // UNDONE: The binding and conversion has to be executed in a checked context. Binder defaultValueBinder = this.GetBinder(defaultValueSyntax); Debug.Assert(defaultValueBinder != null); valueBeforeConversion = defaultValueBinder.BindValue(defaultValueSyntax.Value, diagnostics, BindValueKind.RValue); // Always generate the conversion, even if the expression is not convertible to the given type. // We want the erroneous conversion in the tree. var result = new BoundParameterEqualsValue(defaultValueSyntax, parameter, defaultValueBinder.GetDeclaredLocalsForScope(defaultValueSyntax), defaultValueBinder.GenerateConversionForAssignment(parameter.Type, valueBeforeConversion, diagnostics, isDefaultParameter: true)); return result; } internal BoundFieldEqualsValue BindEnumConstantInitializer( SourceEnumConstantSymbol symbol, EqualsValueClauseSyntax equalsValueSyntax, BindingDiagnosticBag diagnostics) { Binder initializerBinder = this.GetBinder(equalsValueSyntax); Debug.Assert(initializerBinder != null); var initializer = initializerBinder.BindValue(equalsValueSyntax.Value, diagnostics, BindValueKind.RValue); initializer = initializerBinder.GenerateConversionForAssignment(symbol.ContainingType.EnumUnderlyingType, initializer, diagnostics); return new BoundFieldEqualsValue(equalsValueSyntax, symbol, initializerBinder.GetDeclaredLocalsForScope(equalsValueSyntax), initializer); } public BoundExpression BindExpression(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { return BindExpression(node, diagnostics: diagnostics, invoked: false, indexed: false); } protected BoundExpression BindExpression(ExpressionSyntax node, BindingDiagnosticBag diagnostics, bool invoked, bool indexed) { BoundExpression expr = BindExpressionInternal(node, diagnostics, invoked, indexed); VerifyUnchecked(node, diagnostics, expr); if (expr.Kind == BoundKind.ArgListOperator) { // CS0226: An __arglist expression may only appear inside of a call or new expression Error(diagnostics, ErrorCode.ERR_IllegalArglist, node); expr = ToBadExpression(expr); } return expr; } // PERF: allowArgList is not a parameter because it is fairly uncommon case where arglists are allowed // so we do not want to pass that argument to every BindExpression which is often recursive // and extra arguments contribute to the stack size. protected BoundExpression BindExpressionAllowArgList(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression expr = BindExpressionInternal(node, diagnostics, invoked: false, indexed: false); VerifyUnchecked(node, diagnostics, expr); return expr; } private void VerifyUnchecked(ExpressionSyntax node, BindingDiagnosticBag diagnostics, BoundExpression expr) { if (!expr.HasAnyErrors && !IsInsideNameof) { TypeSymbol exprType = expr.Type; if ((object)exprType != null && exprType.IsUnsafe()) { ReportUnsafeIfNotAllowed(node, diagnostics); //CONSIDER: Return a bad expression so that HasErrors is true? } } } private BoundExpression BindExpressionInternal(ExpressionSyntax node, BindingDiagnosticBag diagnostics, bool invoked, bool indexed) { if (IsEarlyAttributeBinder && !EarlyWellKnownAttributeBinder.CanBeValidAttributeArgument(node, this)) { return BadExpression(node, LookupResultKind.NotAValue); } Debug.Assert(node != null); switch (node.Kind()) { case SyntaxKind.AnonymousMethodExpression: case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: return BindAnonymousFunction((AnonymousFunctionExpressionSyntax)node, diagnostics); case SyntaxKind.ThisExpression: return BindThis((ThisExpressionSyntax)node, diagnostics); case SyntaxKind.BaseExpression: return BindBase((BaseExpressionSyntax)node, diagnostics); case SyntaxKind.InvocationExpression: return BindInvocationExpression((InvocationExpressionSyntax)node, diagnostics); case SyntaxKind.ArrayInitializerExpression: return BindUnexpectedArrayInitializer((InitializerExpressionSyntax)node, diagnostics, ErrorCode.ERR_ArrayInitInBadPlace); case SyntaxKind.ArrayCreationExpression: return BindArrayCreationExpression((ArrayCreationExpressionSyntax)node, diagnostics); case SyntaxKind.ImplicitArrayCreationExpression: return BindImplicitArrayCreationExpression((ImplicitArrayCreationExpressionSyntax)node, diagnostics); case SyntaxKind.StackAllocArrayCreationExpression: return BindStackAllocArrayCreationExpression((StackAllocArrayCreationExpressionSyntax)node, diagnostics); case SyntaxKind.ImplicitStackAllocArrayCreationExpression: return BindImplicitStackAllocArrayCreationExpression((ImplicitStackAllocArrayCreationExpressionSyntax)node, diagnostics); case SyntaxKind.ObjectCreationExpression: return BindObjectCreationExpression((ObjectCreationExpressionSyntax)node, diagnostics); case SyntaxKind.ImplicitObjectCreationExpression: return BindImplicitObjectCreationExpression((ImplicitObjectCreationExpressionSyntax)node, diagnostics); case SyntaxKind.IdentifierName: case SyntaxKind.GenericName: return BindIdentifier((SimpleNameSyntax)node, invoked, indexed, diagnostics); case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: return BindMemberAccess((MemberAccessExpressionSyntax)node, invoked, indexed, diagnostics: diagnostics); case SyntaxKind.SimpleAssignmentExpression: return BindAssignment((AssignmentExpressionSyntax)node, diagnostics); case SyntaxKind.CastExpression: return BindCast((CastExpressionSyntax)node, diagnostics); case SyntaxKind.ElementAccessExpression: return BindElementAccess((ElementAccessExpressionSyntax)node, diagnostics); case SyntaxKind.AddExpression: case SyntaxKind.MultiplyExpression: case SyntaxKind.SubtractExpression: case SyntaxKind.DivideExpression: case SyntaxKind.ModuloExpression: case SyntaxKind.EqualsExpression: case SyntaxKind.NotEqualsExpression: case SyntaxKind.GreaterThanExpression: case SyntaxKind.LessThanExpression: case SyntaxKind.GreaterThanOrEqualExpression: case SyntaxKind.LessThanOrEqualExpression: case SyntaxKind.BitwiseAndExpression: case SyntaxKind.BitwiseOrExpression: case SyntaxKind.ExclusiveOrExpression: case SyntaxKind.LeftShiftExpression: case SyntaxKind.RightShiftExpression: return BindSimpleBinaryOperator((BinaryExpressionSyntax)node, diagnostics); case SyntaxKind.LogicalAndExpression: case SyntaxKind.LogicalOrExpression: return BindConditionalLogicalOperator((BinaryExpressionSyntax)node, diagnostics); case SyntaxKind.CoalesceExpression: return BindNullCoalescingOperator((BinaryExpressionSyntax)node, diagnostics); case SyntaxKind.ConditionalAccessExpression: return BindConditionalAccessExpression((ConditionalAccessExpressionSyntax)node, diagnostics); case SyntaxKind.MemberBindingExpression: return BindMemberBindingExpression((MemberBindingExpressionSyntax)node, invoked, indexed, diagnostics); case SyntaxKind.ElementBindingExpression: return BindElementBindingExpression((ElementBindingExpressionSyntax)node, diagnostics); case SyntaxKind.IsExpression: return BindIsOperator((BinaryExpressionSyntax)node, diagnostics); case SyntaxKind.AsExpression: return BindAsOperator((BinaryExpressionSyntax)node, diagnostics); case SyntaxKind.UnaryPlusExpression: case SyntaxKind.UnaryMinusExpression: case SyntaxKind.LogicalNotExpression: case SyntaxKind.BitwiseNotExpression: return BindUnaryOperator((PrefixUnaryExpressionSyntax)node, diagnostics); case SyntaxKind.IndexExpression: return BindFromEndIndexExpression((PrefixUnaryExpressionSyntax)node, diagnostics); case SyntaxKind.RangeExpression: return BindRangeExpression((RangeExpressionSyntax)node, diagnostics); case SyntaxKind.AddressOfExpression: return BindAddressOfExpression((PrefixUnaryExpressionSyntax)node, diagnostics); case SyntaxKind.PointerIndirectionExpression: return BindPointerIndirectionExpression((PrefixUnaryExpressionSyntax)node, diagnostics); case SyntaxKind.PostIncrementExpression: case SyntaxKind.PostDecrementExpression: return BindIncrementOperator(node, ((PostfixUnaryExpressionSyntax)node).Operand, ((PostfixUnaryExpressionSyntax)node).OperatorToken, diagnostics); case SyntaxKind.PreIncrementExpression: case SyntaxKind.PreDecrementExpression: return BindIncrementOperator(node, ((PrefixUnaryExpressionSyntax)node).Operand, ((PrefixUnaryExpressionSyntax)node).OperatorToken, diagnostics); case SyntaxKind.ConditionalExpression: return BindConditionalOperator((ConditionalExpressionSyntax)node, diagnostics); case SyntaxKind.SwitchExpression: return BindSwitchExpression((SwitchExpressionSyntax)node, diagnostics); case SyntaxKind.NumericLiteralExpression: case SyntaxKind.StringLiteralExpression: case SyntaxKind.CharacterLiteralExpression: case SyntaxKind.TrueLiteralExpression: case SyntaxKind.FalseLiteralExpression: case SyntaxKind.NullLiteralExpression: return BindLiteralConstant((LiteralExpressionSyntax)node, diagnostics); case SyntaxKind.DefaultLiteralExpression: return new BoundDefaultLiteral(node); case SyntaxKind.ParenthesizedExpression: // Parenthesis tokens are ignored, and operand is bound in the context of parent // expression. return BindParenthesizedExpression(((ParenthesizedExpressionSyntax)node).Expression, diagnostics); case SyntaxKind.UncheckedExpression: case SyntaxKind.CheckedExpression: return BindCheckedExpression((CheckedExpressionSyntax)node, diagnostics); case SyntaxKind.DefaultExpression: return BindDefaultExpression((DefaultExpressionSyntax)node, diagnostics); case SyntaxKind.TypeOfExpression: return BindTypeOf((TypeOfExpressionSyntax)node, diagnostics); case SyntaxKind.SizeOfExpression: return BindSizeOf((SizeOfExpressionSyntax)node, diagnostics); 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: return BindCompoundAssignment((AssignmentExpressionSyntax)node, diagnostics); case SyntaxKind.CoalesceAssignmentExpression: return BindNullCoalescingAssignmentOperator((AssignmentExpressionSyntax)node, diagnostics); case SyntaxKind.AliasQualifiedName: case SyntaxKind.PredefinedType: return this.BindNamespaceOrType(node, diagnostics); case SyntaxKind.QueryExpression: return this.BindQuery((QueryExpressionSyntax)node, diagnostics); case SyntaxKind.AnonymousObjectCreationExpression: return BindAnonymousObjectCreation((AnonymousObjectCreationExpressionSyntax)node, diagnostics); case SyntaxKind.QualifiedName: return BindQualifiedName((QualifiedNameSyntax)node, diagnostics); case SyntaxKind.ComplexElementInitializerExpression: return BindUnexpectedComplexElementInitializer((InitializerExpressionSyntax)node, diagnostics); case SyntaxKind.ArgListExpression: return BindArgList(node, diagnostics); case SyntaxKind.RefTypeExpression: return BindRefType((RefTypeExpressionSyntax)node, diagnostics); case SyntaxKind.MakeRefExpression: return BindMakeRef((MakeRefExpressionSyntax)node, diagnostics); case SyntaxKind.RefValueExpression: return BindRefValue((RefValueExpressionSyntax)node, diagnostics); case SyntaxKind.AwaitExpression: return BindAwait((AwaitExpressionSyntax)node, diagnostics); case SyntaxKind.OmittedArraySizeExpression: case SyntaxKind.OmittedTypeArgument: case SyntaxKind.ObjectInitializerExpression: // Not reachable during method body binding, but // may be used by SemanticModel for error cases. return BadExpression(node); case SyntaxKind.NullableType: // Not reachable during method body binding, but // may be used by SemanticModel for error cases. // NOTE: This happens when there's a problem with the Nullable<T> type (e.g. it's missing). // There is no corresponding problem for array or pointer types (which seem analogous), since // they are not constructed types; the element type can be an error type, but the array/pointer // type cannot. return BadExpression(node); case SyntaxKind.InterpolatedStringExpression: return BindInterpolatedString((InterpolatedStringExpressionSyntax)node, diagnostics); case SyntaxKind.IsPatternExpression: return BindIsPatternExpression((IsPatternExpressionSyntax)node, diagnostics); case SyntaxKind.TupleExpression: return BindTupleExpression((TupleExpressionSyntax)node, diagnostics); case SyntaxKind.ThrowExpression: return BindThrowExpression((ThrowExpressionSyntax)node, diagnostics); case SyntaxKind.RefType: return BindRefType(node, diagnostics); case SyntaxKind.RefExpression: return BindRefExpression(node, diagnostics); case SyntaxKind.DeclarationExpression: return BindDeclarationExpressionAsError((DeclarationExpressionSyntax)node, diagnostics); case SyntaxKind.SuppressNullableWarningExpression: return BindSuppressNullableWarningExpression((PostfixUnaryExpressionSyntax)node, diagnostics); case SyntaxKind.WithExpression: return BindWithExpression((WithExpressionSyntax)node, diagnostics); default: // NOTE: We could probably throw an exception here, but it's conceivable // that a non-parser syntax tree could reach this point with an unexpected // SyntaxKind and we don't want to throw if that occurs. Debug.Assert(false, "Unexpected SyntaxKind " + node.Kind()); diagnostics.Add(ErrorCode.ERR_InternalError, node.Location); return BadExpression(node); } } #nullable enable internal virtual BoundSwitchExpressionArm BindSwitchExpressionArm(SwitchExpressionArmSyntax node, TypeSymbol switchGoverningType, uint switchGoverningValEscape, BindingDiagnosticBag diagnostics) { return this.NextRequired.BindSwitchExpressionArm(node, switchGoverningType, switchGoverningValEscape, diagnostics); } #nullable disable private BoundExpression BindRefExpression(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { var firstToken = node.GetFirstToken(); diagnostics.Add(ErrorCode.ERR_UnexpectedToken, firstToken.GetLocation(), firstToken.ValueText); return new BoundBadExpression( node, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, ImmutableArray<BoundExpression>.Empty, CreateErrorType("ref")); } private BoundExpression BindRefType(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { var firstToken = node.GetFirstToken(); diagnostics.Add(ErrorCode.ERR_UnexpectedToken, firstToken.GetLocation(), firstToken.ValueText); return new BoundTypeExpression(node, null, CreateErrorType("ref")); } private BoundExpression BindThrowExpression(ThrowExpressionSyntax node, BindingDiagnosticBag diagnostics) { bool hasErrors = node.HasErrors; if (!IsThrowExpressionInProperContext(node)) { diagnostics.Add(ErrorCode.ERR_ThrowMisplaced, node.ThrowKeyword.GetLocation()); hasErrors = true; } var thrownExpression = BindThrownExpression(node.Expression, diagnostics, ref hasErrors); return new BoundThrowExpression(node, thrownExpression, null, hasErrors); } private static bool IsThrowExpressionInProperContext(ThrowExpressionSyntax node) { var parent = node.Parent; if (parent == null || node.HasErrors) { return true; } switch (parent.Kind()) { case SyntaxKind.ConditionalExpression: // ?: { var conditionalParent = (ConditionalExpressionSyntax)parent; return node == conditionalParent.WhenTrue || node == conditionalParent.WhenFalse; } case SyntaxKind.CoalesceExpression: // ?? { var binaryParent = (BinaryExpressionSyntax)parent; return node == binaryParent.Right; } case SyntaxKind.SwitchExpressionArm: case SyntaxKind.ArrowExpressionClause: case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: return true; // We do not support && and || because // 1. The precedence would not syntactically allow it // 2. It isn't clear what the semantics should be // 3. It isn't clear what use cases would motivate us to change the precedence to support it default: return false; } } // Bind a declaration expression where it isn't permitted. private BoundExpression BindDeclarationExpressionAsError(DeclarationExpressionSyntax node, BindingDiagnosticBag diagnostics) { // This is an error, as declaration expressions are handled specially in every context in which // they are permitted. So we have a context in which they are *not* permitted. Nevertheless, we // bind it and then give one nice message. bool isVar; bool isConst = false; AliasSymbol alias; var declType = BindVariableTypeWithAnnotations(node.Designation, diagnostics, node.Type, ref isConst, out isVar, out alias); Error(diagnostics, ErrorCode.ERR_DeclarationExpressionNotPermitted, node); return BindDeclarationVariablesForErrorRecovery(declType, node.Designation, node, diagnostics); } /// <summary> /// Bind a declaration variable where it isn't permitted. The caller is expected to produce a diagnostic. /// </summary> private BoundExpression BindDeclarationVariablesForErrorRecovery(TypeWithAnnotations declTypeWithAnnotations, VariableDesignationSyntax node, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) { declTypeWithAnnotations = declTypeWithAnnotations.HasType ? declTypeWithAnnotations : TypeWithAnnotations.Create(CreateErrorType("var")); switch (node.Kind()) { case SyntaxKind.SingleVariableDesignation: { var single = (SingleVariableDesignationSyntax)node; var result = BindDeconstructionVariable(declTypeWithAnnotations, single, syntax, diagnostics); return BindToTypeForErrorRecovery(result); } case SyntaxKind.DiscardDesignation: { return BindDiscardExpression(syntax, declTypeWithAnnotations); } case SyntaxKind.ParenthesizedVariableDesignation: { var tuple = (ParenthesizedVariableDesignationSyntax)node; int count = tuple.Variables.Count; var builder = ArrayBuilder<BoundExpression>.GetInstance(count); var namesBuilder = ArrayBuilder<string>.GetInstance(count); foreach (var n in tuple.Variables) { builder.Add(BindDeclarationVariablesForErrorRecovery(declTypeWithAnnotations, n, n, diagnostics)); namesBuilder.Add(InferTupleElementName(n)); } ImmutableArray<BoundExpression> subExpressions = builder.ToImmutableAndFree(); var uniqueFieldNames = PooledHashSet<string>.GetInstance(); RemoveDuplicateInferredTupleNamesAndFreeIfEmptied(ref namesBuilder, uniqueFieldNames); uniqueFieldNames.Free(); ImmutableArray<string> tupleNames = namesBuilder is null ? default : namesBuilder.ToImmutableAndFree(); ImmutableArray<bool> inferredPositions = tupleNames.IsDefault ? default : tupleNames.SelectAsArray(n => n != null); bool disallowInferredNames = this.Compilation.LanguageVersion.DisallowInferredTupleElementNames(); // We will not check constraints at this point as this code path // is failure-only and the caller is expected to produce a diagnostic. var tupleType = NamedTypeSymbol.CreateTuple( locationOpt: null, subExpressions.SelectAsArray(e => TypeWithAnnotations.Create(e.Type)), elementLocations: default, tupleNames, Compilation, shouldCheckConstraints: false, includeNullability: false, errorPositions: disallowInferredNames ? inferredPositions : default); return new BoundConvertedTupleLiteral(syntax, sourceTuple: null, wasTargetTyped: true, subExpressions, tupleNames, inferredPositions, tupleType); } default: throw ExceptionUtilities.UnexpectedValue(node.Kind()); } } private BoundExpression BindTupleExpression(TupleExpressionSyntax node, BindingDiagnosticBag diagnostics) { SeparatedSyntaxList<ArgumentSyntax> arguments = node.Arguments; int numElements = arguments.Count; if (numElements < 2) { // this should be a parse error already. var args = numElements == 1 ? ImmutableArray.Create(BindValue(arguments[0].Expression, diagnostics, BindValueKind.RValue)) : ImmutableArray<BoundExpression>.Empty; return BadExpression(node, args); } bool hasNaturalType = true; var boundArguments = ArrayBuilder<BoundExpression>.GetInstance(arguments.Count); var elementTypesWithAnnotations = ArrayBuilder<TypeWithAnnotations>.GetInstance(arguments.Count); var elementLocations = ArrayBuilder<Location>.GetInstance(arguments.Count); // prepare names var (elementNames, inferredPositions, hasErrors) = ExtractTupleElementNames(arguments, diagnostics); // prepare types and locations for (int i = 0; i < numElements; i++) { ArgumentSyntax argumentSyntax = arguments[i]; IdentifierNameSyntax nameSyntax = argumentSyntax.NameColon?.Name; if (nameSyntax != null) { elementLocations.Add(nameSyntax.Location); } else { elementLocations.Add(argumentSyntax.Location); } BoundExpression boundArgument = BindValue(argumentSyntax.Expression, diagnostics, BindValueKind.RValue); if (boundArgument.Type?.SpecialType == SpecialType.System_Void) { diagnostics.Add(ErrorCode.ERR_VoidInTuple, argumentSyntax.Location); boundArgument = new BoundBadExpression( argumentSyntax, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, ImmutableArray.Create<BoundExpression>(boundArgument), CreateErrorType("void")); } boundArguments.Add(boundArgument); var elementTypeWithAnnotations = TypeWithAnnotations.Create(boundArgument.Type); elementTypesWithAnnotations.Add(elementTypeWithAnnotations); if (!elementTypeWithAnnotations.HasType) { hasNaturalType = false; } } NamedTypeSymbol tupleTypeOpt = null; var elements = elementTypesWithAnnotations.ToImmutableAndFree(); var locations = elementLocations.ToImmutableAndFree(); if (hasNaturalType) { bool disallowInferredNames = this.Compilation.LanguageVersion.DisallowInferredTupleElementNames(); tupleTypeOpt = NamedTypeSymbol.CreateTuple(node.Location, elements, locations, elementNames, this.Compilation, syntax: node, diagnostics: diagnostics, shouldCheckConstraints: true, includeNullability: false, errorPositions: disallowInferredNames ? inferredPositions : default(ImmutableArray<bool>)); } else { NamedTypeSymbol.VerifyTupleTypePresent(elements.Length, node, this.Compilation, diagnostics); } // Always track the inferred positions in the bound node, so that conversions don't produce a warning // for "dropped names" on tuple literal when the name was inferred. return new BoundTupleLiteral(node, boundArguments.ToImmutableAndFree(), elementNames, inferredPositions, tupleTypeOpt, hasErrors); } private static (ImmutableArray<string> elementNamesArray, ImmutableArray<bool> inferredArray, bool hasErrors) ExtractTupleElementNames( SeparatedSyntaxList<ArgumentSyntax> arguments, BindingDiagnosticBag diagnostics) { bool hasErrors = false; int numElements = arguments.Count; var uniqueFieldNames = PooledHashSet<string>.GetInstance(); ArrayBuilder<string> elementNames = null; ArrayBuilder<string> inferredElementNames = null; for (int i = 0; i < numElements; i++) { ArgumentSyntax argumentSyntax = arguments[i]; IdentifierNameSyntax nameSyntax = argumentSyntax.NameColon?.Name; string name = null; string inferredName = null; if (nameSyntax != null) { name = nameSyntax.Identifier.ValueText; if (diagnostics != null && !CheckTupleMemberName(name, i, argumentSyntax.NameColon.Name, diagnostics, uniqueFieldNames)) { hasErrors = true; } } else { inferredName = InferTupleElementName(argumentSyntax.Expression); } CollectTupleFieldMemberName(name, i, numElements, ref elementNames); CollectTupleFieldMemberName(inferredName, i, numElements, ref inferredElementNames); } RemoveDuplicateInferredTupleNamesAndFreeIfEmptied(ref inferredElementNames, uniqueFieldNames); uniqueFieldNames.Free(); var result = MergeTupleElementNames(elementNames, inferredElementNames); elementNames?.Free(); inferredElementNames?.Free(); return (result.names, result.inferred, hasErrors); } private static (ImmutableArray<string> names, ImmutableArray<bool> inferred) MergeTupleElementNames( ArrayBuilder<string> elementNames, ArrayBuilder<string> inferredElementNames) { if (elementNames == null) { if (inferredElementNames == null) { return (default(ImmutableArray<string>), default(ImmutableArray<bool>)); } else { var finalNames = inferredElementNames.ToImmutable(); return (finalNames, finalNames.SelectAsArray(n => n != null)); } } if (inferredElementNames == null) { return (elementNames.ToImmutable(), default(ImmutableArray<bool>)); } Debug.Assert(elementNames.Count == inferredElementNames.Count); var builder = ArrayBuilder<bool>.GetInstance(elementNames.Count); for (int i = 0; i < elementNames.Count; i++) { string inferredName = inferredElementNames[i]; if (elementNames[i] == null && inferredName != null) { elementNames[i] = inferredName; builder.Add(true); } else { builder.Add(false); } } return (elementNames.ToImmutable(), builder.ToImmutableAndFree()); } /// <summary> /// Removes duplicate entries in <paramref name="inferredElementNames"/> and frees it if only nulls remain. /// </summary> private static void RemoveDuplicateInferredTupleNamesAndFreeIfEmptied(ref ArrayBuilder<string> inferredElementNames, HashSet<string> uniqueFieldNames) { if (inferredElementNames == null) { return; } // Inferred names that duplicate an explicit name or a previous inferred name are tagged for removal var toRemove = PooledHashSet<string>.GetInstance(); foreach (var name in inferredElementNames) { if (name != null && !uniqueFieldNames.Add(name)) { toRemove.Add(name); } } for (int i = 0; i < inferredElementNames.Count; i++) { var inferredName = inferredElementNames[i]; if (inferredName != null && toRemove.Contains(inferredName)) { inferredElementNames[i] = null; } } toRemove.Free(); if (inferredElementNames.All(n => n is null)) { inferredElementNames.Free(); inferredElementNames = null; } } private static string InferTupleElementName(SyntaxNode syntax) { string name = syntax.TryGetInferredMemberName(); // Reserved names are never candidates to be inferred names, at any position if (name == null || NamedTypeSymbol.IsTupleElementNameReserved(name) != -1) { return null; } return name; } private BoundExpression BindRefValue(RefValueExpressionSyntax node, BindingDiagnosticBag diagnostics) { // __refvalue(tr, T) requires that tr be a TypedReference and T be a type. // The result is a *variable* of type T. BoundExpression argument = BindValue(node.Expression, diagnostics, BindValueKind.RValue); bool hasErrors = argument.HasAnyErrors; TypeSymbol typedReferenceType = this.Compilation.GetSpecialType(SpecialType.System_TypedReference); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = this.Conversions.ClassifyConversionFromExpression(argument, typedReferenceType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!conversion.IsImplicit || !conversion.IsValid) { hasErrors = true; GenerateImplicitConversionError(diagnostics, node, conversion, argument, typedReferenceType); } argument = CreateConversion(argument, conversion, typedReferenceType, diagnostics); TypeWithAnnotations typeWithAnnotations = BindType(node.Type, diagnostics); return new BoundRefValueOperator(node, typeWithAnnotations.NullableAnnotation, argument, typeWithAnnotations.Type, hasErrors); } private BoundExpression BindMakeRef(MakeRefExpressionSyntax node, BindingDiagnosticBag diagnostics) { // __makeref(x) requires that x be a variable, and not be of a restricted type. BoundExpression argument = this.BindValue(node.Expression, diagnostics, BindValueKind.RefOrOut); bool hasErrors = argument.HasAnyErrors; TypeSymbol typedReferenceType = GetSpecialType(SpecialType.System_TypedReference, diagnostics, node); if ((object)argument.Type != null && argument.Type.IsRestrictedType()) { // CS1601: Cannot make reference to variable of type '{0}' Error(diagnostics, ErrorCode.ERR_MethodArgCantBeRefAny, node, argument.Type); hasErrors = true; } // UNDONE: We do not yet implement warnings anywhere for: // UNDONE: * taking a ref to a volatile field // UNDONE: * taking a ref to a "non-agile" field // UNDONE: We should do so here when we implement this feature for regular out/ref parameters. return new BoundMakeRefOperator(node, argument, typedReferenceType, hasErrors); } private BoundExpression BindRefType(RefTypeExpressionSyntax node, BindingDiagnosticBag diagnostics) { // __reftype(x) requires that x be implicitly convertible to TypedReference. BoundExpression argument = BindValue(node.Expression, diagnostics, BindValueKind.RValue); bool hasErrors = argument.HasAnyErrors; TypeSymbol typedReferenceType = this.Compilation.GetSpecialType(SpecialType.System_TypedReference); TypeSymbol typeType = this.GetWellKnownType(WellKnownType.System_Type, diagnostics, node); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = this.Conversions.ClassifyConversionFromExpression(argument, typedReferenceType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!conversion.IsImplicit || !conversion.IsValid) { hasErrors = true; GenerateImplicitConversionError(diagnostics, node, conversion, argument, typedReferenceType); } argument = CreateConversion(argument, conversion, typedReferenceType, diagnostics); return new BoundRefTypeOperator(node, argument, null, typeType, hasErrors); } private BoundExpression BindArgList(CSharpSyntaxNode node, BindingDiagnosticBag diagnostics) { // There are two forms of __arglist expression. In a method with an __arglist parameter, // it is legal to use __arglist as an expression of type RuntimeArgumentHandle. In // a call to such a method, it is legal to use __arglist(x, y, z) as the final argument. // This method only handles the first usage; the second usage is parsed as a call syntax. // The native compiler allows __arglist in a lambda: // // class C // { // delegate int D(RuntimeArgumentHandle r); // static void M(__arglist) // { // D f = null; // f = r=>f(__arglist); // } // } // // This is clearly wrong. Either the developer intends __arglist to refer to the // arg list of the *lambda*, or to the arg list of *M*. The former makes no sense; // lambdas cannot have an arg list. The latter we have no way to generate code for; // you cannot hoist the arg list to a field of a closure class. // // The native compiler allows this and generates code as though the developer // was attempting to access the arg list of the lambda! We should simply disallow it. TypeSymbol runtimeArgumentHandleType = GetSpecialType(SpecialType.System_RuntimeArgumentHandle, diagnostics, node); MethodSymbol method = this.ContainingMember() as MethodSymbol; bool hasError = false; if ((object)method == null || !method.IsVararg) { // CS0190: The __arglist construct is valid only within a variable argument method Error(diagnostics, ErrorCode.ERR_ArgsInvalid, node); hasError = true; } else { // We're in a varargs method; are we also inside a lambda? Symbol container = this.ContainingMemberOrLambda; if (container != method) { // We also need to report this any time a local variable of a restricted type // would be hoisted into a closure for an anonymous function, iterator or async method. // We do that during the actual rewrites. // CS4013: Instance of type '{0}' cannot be used inside an anonymous function, query expression, iterator block or async method Error(diagnostics, ErrorCode.ERR_SpecialByRefInLambda, node, runtimeArgumentHandleType); hasError = true; } } return new BoundArgList(node, runtimeArgumentHandleType, hasError); } /// <summary> /// This can be reached for the qualified name on the right-hand-side of an `is` operator. /// For compatibility we parse it as a qualified name, as the is-type expression only permitted /// a type on the right-hand-side in C# 6. But the same syntax now, in C# 7 and later, can /// refer to a constant, which would normally be represented as a *simple member access expression*. /// Since the parser cannot distinguish, it parses it as before and depends on the binder /// to handle a qualified name appearing as an expression. /// </summary> private BoundExpression BindQualifiedName(QualifiedNameSyntax node, BindingDiagnosticBag diagnostics) { return BindMemberAccessWithBoundLeft(node, this.BindLeftOfPotentialColorColorMemberAccess(node.Left, diagnostics), node.Right, node.DotToken, invoked: false, indexed: false, diagnostics: diagnostics); } private BoundExpression BindParenthesizedExpression(ExpressionSyntax innerExpression, BindingDiagnosticBag diagnostics) { var result = BindExpression(innerExpression, diagnostics); // A parenthesized expression may not be a namespace or a type. If it is a parenthesized // namespace or type then report the error but let it go; we'll just ignore the // parenthesis and keep on trucking. CheckNotNamespaceOrType(result, diagnostics); return result; } #nullable enable private BoundExpression BindTypeOf(TypeOfExpressionSyntax node, BindingDiagnosticBag diagnostics) { ExpressionSyntax typeSyntax = node.Type; TypeofBinder typeofBinder = new TypeofBinder(typeSyntax, this); //has special handling for unbound types AliasSymbol alias; TypeWithAnnotations typeWithAnnotations = typeofBinder.BindType(typeSyntax, diagnostics, out alias); TypeSymbol type = typeWithAnnotations.Type; bool hasError = false; // NB: Dev10 has an error for typeof(dynamic), but allows typeof(dynamic[]), // typeof(C<dynamic>), etc. if (type.IsDynamic()) { diagnostics.Add(ErrorCode.ERR_BadDynamicTypeof, node.Location); hasError = true; } else if (typeWithAnnotations.NullableAnnotation.IsAnnotated() && type.IsReferenceType) { // error: cannot take the `typeof` a nullable reference type. diagnostics.Add(ErrorCode.ERR_BadNullableTypeof, node.Location); hasError = true; } else if (this.InAttributeArgument && type.ContainsFunctionPointer()) { // https://github.com/dotnet/roslyn/issues/48765 tracks removing this error and properly supporting function // pointers in attribute types. Until then, we don't know how serialize them, so error instead of crashing // during emit. diagnostics.Add(ErrorCode.ERR_FunctionPointerTypesInAttributeNotSupported, node.Location); hasError = true; } BoundTypeExpression boundType = new BoundTypeExpression(typeSyntax, alias, typeWithAnnotations, type.IsErrorType()); return new BoundTypeOfOperator(node, boundType, null, this.GetWellKnownType(WellKnownType.System_Type, diagnostics, node), hasError); } private BoundExpression BindSizeOf(SizeOfExpressionSyntax node, BindingDiagnosticBag diagnostics) { ExpressionSyntax typeSyntax = node.Type; AliasSymbol alias; TypeWithAnnotations typeWithAnnotations = this.BindType(typeSyntax, diagnostics, out alias); TypeSymbol type = typeWithAnnotations.Type; bool typeHasErrors = type.IsErrorType() || CheckManagedAddr(Compilation, type, node.Location, diagnostics); BoundTypeExpression boundType = new BoundTypeExpression(typeSyntax, alias, typeWithAnnotations, typeHasErrors); ConstantValue constantValue = GetConstantSizeOf(type); bool hasErrors = constantValue is null && ReportUnsafeIfNotAllowed(node, diagnostics, type); return new BoundSizeOfOperator(node, boundType, constantValue, this.GetSpecialType(SpecialType.System_Int32, diagnostics, node), hasErrors); } /// <returns>true if managed type-related errors were found, otherwise false.</returns> internal static bool CheckManagedAddr(CSharpCompilation compilation, TypeSymbol type, Location location, BindingDiagnosticBag diagnostics) { var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, compilation.Assembly); var managedKind = type.GetManagedKind(ref useSiteInfo); diagnostics.Add(location, useSiteInfo); return CheckManagedAddr(compilation, type, managedKind, location, diagnostics); } /// <returns>true if managed type-related errors were found, otherwise false.</returns> internal static bool CheckManagedAddr(CSharpCompilation compilation, TypeSymbol type, ManagedKind managedKind, Location location, BindingDiagnosticBag diagnostics) { switch (managedKind) { case ManagedKind.Managed: diagnostics.Add(ErrorCode.ERR_ManagedAddr, location, type); return true; case ManagedKind.UnmanagedWithGenerics when MessageID.IDS_FeatureUnmanagedConstructedTypes.GetFeatureAvailabilityDiagnosticInfo(compilation) is CSDiagnosticInfo diagnosticInfo: diagnostics.Add(diagnosticInfo, location); return true; case ManagedKind.Unknown: throw ExceptionUtilities.UnexpectedValue(managedKind); default: return false; } } #nullable disable internal static ConstantValue GetConstantSizeOf(TypeSymbol type) { return ConstantValue.CreateSizeOf((type.GetEnumUnderlyingType() ?? type).SpecialType); } private BoundExpression BindDefaultExpression(DefaultExpressionSyntax node, BindingDiagnosticBag diagnostics) { TypeWithAnnotations typeWithAnnotations = this.BindType(node.Type, diagnostics, out AliasSymbol alias); var typeExpression = new BoundTypeExpression(node.Type, aliasOpt: alias, typeWithAnnotations); TypeSymbol type = typeWithAnnotations.Type; return new BoundDefaultExpression(node, typeExpression, constantValueOpt: type.GetDefaultValue(), type); } /// <summary> /// Binds a simple identifier. /// </summary> private BoundExpression BindIdentifier( SimpleNameSyntax node, bool invoked, bool indexed, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); // If the syntax tree is ill-formed and the identifier is missing then we've already // given a parse error. Just return an error local and continue with analysis. if (node.IsMissing) { return BadExpression(node); } // A simple-name is either of the form I or of the form I<A1, ..., AK>, where I is a // single identifier and <A1, ..., AK> is an optional type-argument-list. When no // type-argument-list is specified, consider K to be zero. The simple-name is evaluated // and classified as follows: // If K is zero and the simple-name appears within a block and if the block's (or an // enclosing block's) local variable declaration space contains a local variable, // parameter or constant with name I, then the simple-name refers to that local // variable, parameter or constant and is classified as a variable or value. // If K is zero and the simple-name appears within the body of a generic method // declaration and if that declaration includes a type parameter with name I, then the // simple-name refers to that type parameter. BoundExpression expression; // It's possible that the argument list is malformed; if so, do not attempt to bind it; // just use the null array. int arity = node.Arity; bool hasTypeArguments = arity > 0; SeparatedSyntaxList<TypeSyntax> typeArgumentList = node.Kind() == SyntaxKind.GenericName ? ((GenericNameSyntax)node).TypeArgumentList.Arguments : default(SeparatedSyntaxList<TypeSyntax>); Debug.Assert(arity == typeArgumentList.Count); var typeArgumentsWithAnnotations = hasTypeArguments ? BindTypeArguments(typeArgumentList, diagnostics) : default(ImmutableArray<TypeWithAnnotations>); var lookupResult = LookupResult.GetInstance(); LookupOptions options = LookupOptions.AllMethodsOnArityZero; if (invoked) { options |= LookupOptions.MustBeInvocableIfMember; } if (!IsInMethodBody && !IsInsideNameof) { Debug.Assert((options & LookupOptions.NamespacesOrTypesOnly) == 0); options |= LookupOptions.MustNotBeMethodTypeParameter; } var name = node.Identifier.ValueText; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupSymbolsWithFallback(lookupResult, name, arity: arity, useSiteInfo: ref useSiteInfo, options: options); diagnostics.Add(node, useSiteInfo); if (lookupResult.Kind != LookupResultKind.Empty) { // have we detected an error with the current node? bool isError; var members = ArrayBuilder<Symbol>.GetInstance(); Symbol symbol = GetSymbolOrMethodOrPropertyGroup(lookupResult, node, name, node.Arity, members, diagnostics, out isError, qualifierOpt: null); // reports diagnostics in result. if ((object)symbol == null) { Debug.Assert(members.Count > 0); var receiver = SynthesizeMethodGroupReceiver(node, members); expression = ConstructBoundMemberGroupAndReportOmittedTypeArguments( node, typeArgumentList, typeArgumentsWithAnnotations, receiver, name, members, lookupResult, receiver != null ? BoundMethodGroupFlags.HasImplicitReceiver : BoundMethodGroupFlags.None, isError, diagnostics); ReportSimpleProgramLocalReferencedOutsideOfTopLevelStatement(node, members[0], diagnostics); } else { bool isNamedType = (symbol.Kind == SymbolKind.NamedType) || (symbol.Kind == SymbolKind.ErrorType); if (hasTypeArguments && isNamedType) { symbol = ConstructNamedTypeUnlessTypeArgumentOmitted(node, (NamedTypeSymbol)symbol, typeArgumentList, typeArgumentsWithAnnotations, diagnostics); } expression = BindNonMethod(node, symbol, diagnostics, lookupResult.Kind, indexed, isError); if (!isNamedType && (hasTypeArguments || node.Kind() == SyntaxKind.GenericName)) { Debug.Assert(isError); // Should have been reported by GetSymbolOrMethodOrPropertyGroup. expression = new BoundBadExpression( syntax: node, resultKind: LookupResultKind.WrongArity, symbols: ImmutableArray.Create(symbol), childBoundNodes: ImmutableArray.Create(BindToTypeForErrorRecovery(expression)), type: expression.Type, hasErrors: isError); } } members.Free(); } else { expression = null; if (node is IdentifierNameSyntax identifier) { var type = BindNativeIntegerSymbolIfAny(identifier, diagnostics); if (type is { }) { expression = new BoundTypeExpression(node, null, type); } else if (FallBackOnDiscard(identifier, diagnostics)) { expression = new BoundDiscardExpression(node, type: null); } } // Otherwise, the simple-name is undefined and a compile-time error occurs. if (expression is null) { expression = BadExpression(node); if (lookupResult.Error != null) { Error(diagnostics, lookupResult.Error, node); } else if (IsJoinRangeVariableInLeftKey(node)) { Error(diagnostics, ErrorCode.ERR_QueryOuterKey, node, name); } else if (IsInJoinRightKey(node)) { Error(diagnostics, ErrorCode.ERR_QueryInnerKey, node, name); } else { Error(diagnostics, ErrorCode.ERR_NameNotInContext, node, name); } } } lookupResult.Free(); return expression; } /// <summary> /// Is this is an _ identifier in a context where discards are allowed? /// </summary> private static bool FallBackOnDiscard(IdentifierNameSyntax node, BindingDiagnosticBag diagnostics) { if (!node.Identifier.IsUnderscoreToken()) { return false; } CSharpSyntaxNode containingDeconstruction = node.GetContainingDeconstruction(); bool isDiscard = containingDeconstruction != null || IsOutVarDiscardIdentifier(node); if (isDiscard) { CheckFeatureAvailability(node, MessageID.IDS_FeatureDiscards, diagnostics); } return isDiscard; } private static bool IsOutVarDiscardIdentifier(SimpleNameSyntax node) { Debug.Assert(node.Identifier.IsUnderscoreToken()); CSharpSyntaxNode parent = node.Parent; return (parent?.Kind() == SyntaxKind.Argument && ((ArgumentSyntax)parent).RefOrOutKeyword.Kind() == SyntaxKind.OutKeyword); } private BoundExpression SynthesizeMethodGroupReceiver(CSharpSyntaxNode syntax, ArrayBuilder<Symbol> members) { // SPEC: For each instance type T starting with the instance type of the immediately // SPEC: enclosing type declaration, and continuing with the instance type of each // SPEC: enclosing class or struct declaration, [do a lot of things to find a match]. // SPEC: ... // SPEC: If T is the instance type of the immediately enclosing class or struct type // SPEC: and the lookup identifies one or more methods, the result is a method group // SPEC: with an associated instance expression of this. // Explanation of spec: // // We are looping over a set of types, from inner to outer, attempting to resolve the // meaning of a simple name; for example "M(123)". // // There are a number of possibilities: // // If the lookup finds M in an outer class: // // class Outer { // static void M(int x) {} // class Inner { // void X() { M(123); } // } // } // // or the base class of an outer class: // // class Base { // public static void M(int x) {} // } // class Outer : Base { // class Inner { // void X() { M(123); } // } // } // // Then there is no "associated instance expression" of the method group. That is, there // is no possibility of there being an "implicit this". // // If the lookup finds M on the class that triggered the lookup on the other hand, or // one of its base classes: // // class Base { // public static void M(int x) {} // } // class Derived : Base { // void X() { M(123); } // } // // Then the associated instance expression is "this" *even if one or more methods in the // method group are static*. If it turns out that the method was static, then we'll // check later to determine if there was a receiver actually present in the source code // or not. (That happens during the "final validation" phase of overload resolution. // Implementation explanation: // // If we're here, then lookup has identified one or more methods. Debug.Assert(members.Count > 0); // The lookup implementation loops over the set of types from inner to outer, and stops // when it makes a match. (This is correct because any matches found on more-outer types // would be hidden, and discarded.) This means that we only find members associated with // one containing class or struct. The method is possibly on that type directly, or via // inheritance from a base type of the type. // // The question then is what the "associated instance expression" is; is it "this" or // nothing at all? If the type that we found the method on is the current type, or is a // base type of the current type, then there should be a "this" associated with the // method group. Otherwise, it should be null. var currentType = this.ContainingType; if ((object)currentType == null) { // This may happen if there is no containing type, // e.g. we are binding an expression in an assembly-level attribute return null; } var declaringType = members[0].ContainingType; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; if (currentType.IsEqualToOrDerivedFrom(declaringType, TypeCompareKind.ConsiderEverything, useSiteInfo: ref discardedUseSiteInfo) || (currentType.IsInterface && (declaringType.IsObjectType() || currentType.AllInterfacesNoUseSiteDiagnostics.Contains(declaringType)))) { return ThisReference(syntax, currentType, wasCompilerGenerated: true); } else { return TryBindInteractiveReceiver(syntax, declaringType); } } private bool IsBadLocalOrParameterCapture(Symbol symbol, TypeSymbol type, RefKind refKind) { if (refKind != RefKind.None || type.IsRefLikeType) { var containingMethod = this.ContainingMemberOrLambda as MethodSymbol; if ((object)containingMethod != null && (object)symbol.ContainingSymbol != (object)containingMethod) { // Not expecting symbol from constructed method. Debug.Assert(!symbol.ContainingSymbol.Equals(containingMethod)); // Captured in a lambda. return (containingMethod.MethodKind == MethodKind.AnonymousFunction || containingMethod.MethodKind == MethodKind.LocalFunction) && !IsInsideNameof; // false in EE evaluation method } } return false; } private BoundExpression BindNonMethod(SimpleNameSyntax node, Symbol symbol, BindingDiagnosticBag diagnostics, LookupResultKind resultKind, bool indexed, bool isError) { // Events are handled later as we don't know yet if we are binding to the event or it's backing field. if (symbol.Kind != SymbolKind.Event) { ReportDiagnosticsIfObsolete(diagnostics, symbol, node, hasBaseReceiver: false); } switch (symbol.Kind) { case SymbolKind.Local: { var localSymbol = (LocalSymbol)symbol; TypeSymbol type; bool isNullableUnknown; if (ReportSimpleProgramLocalReferencedOutsideOfTopLevelStatement(node, localSymbol, diagnostics)) { type = new ExtendedErrorTypeSymbol( this.Compilation, name: "var", arity: 0, errorInfo: null, variableUsedBeforeDeclaration: true); isNullableUnknown = true; } else if (isUsedBeforeDeclaration(node, localSymbol)) { // Here we report a local variable being used before its declaration // // There are two possible diagnostics for this: // // CS0841: ERR_VariableUsedBeforeDeclaration // Cannot use local variable 'x' before it is declared // // CS0844: ERR_VariableUsedBeforeDeclarationAndHidesField // Cannot use local variable 'x' before it is declared. The // declaration of the local variable hides the field 'C.x'. // // There are two situations in which we give these errors. // // First, the scope of a local variable -- that is, the region of program // text in which it can be looked up by name -- is throughout the entire // block which declares it. It is therefore possible to use a local // before it is declared, which is an error. // // As an additional help to the user, we give a special error for this // scenario: // // class C { // int x; // void M() { // Print(x); // int x = 5; // } } // // Because a too-clever C++ user might be attempting to deliberately // bind to "this.x" in the "Print". (In C++ the local does not come // into scope until its declaration.) // FieldSymbol possibleField = null; var lookupResult = LookupResult.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupMembersInType( lookupResult, ContainingType, localSymbol.Name, arity: 0, basesBeingResolved: null, options: LookupOptions.Default, originalBinder: this, diagnose: false, useSiteInfo: ref useSiteInfo); diagnostics.Add(node, useSiteInfo); possibleField = lookupResult.SingleSymbolOrDefault as FieldSymbol; lookupResult.Free(); if ((object)possibleField != null) { Error(diagnostics, ErrorCode.ERR_VariableUsedBeforeDeclarationAndHidesField, node, node, possibleField); } else { Error(diagnostics, ErrorCode.ERR_VariableUsedBeforeDeclaration, node, node); } type = new ExtendedErrorTypeSymbol( this.Compilation, name: "var", arity: 0, errorInfo: null, variableUsedBeforeDeclaration: true); isNullableUnknown = true; } else if ((localSymbol as SourceLocalSymbol)?.IsVar == true && localSymbol.ForbiddenZone?.Contains(node) == true) { // A var (type-inferred) local variable has been used in its own initialization (the "forbidden zone"). // There are many cases where this occurs, including: // // 1. var x = M(out x); // 2. M(out var x, out x); // 3. var (x, y) = (y, x); // // localSymbol.ForbiddenDiagnostic provides a suitable diagnostic for whichever case applies. // diagnostics.Add(localSymbol.ForbiddenDiagnostic, node.Location, node); type = new ExtendedErrorTypeSymbol( this.Compilation, name: "var", arity: 0, errorInfo: null, variableUsedBeforeDeclaration: true); isNullableUnknown = true; } else { type = localSymbol.Type; isNullableUnknown = false; if (IsBadLocalOrParameterCapture(localSymbol, type, localSymbol.RefKind)) { isError = true; Error(diagnostics, ErrorCode.ERR_AnonDelegateCantUseLocal, node, localSymbol); } } var constantValueOpt = localSymbol.IsConst && !IsInsideNameof && !type.IsErrorType() ? localSymbol.GetConstantValue(node, this.LocalInProgress, diagnostics) : null; return new BoundLocal(node, localSymbol, BoundLocalDeclarationKind.None, constantValueOpt: constantValueOpt, isNullableUnknown: isNullableUnknown, type: type, hasErrors: isError); } case SymbolKind.Parameter: { var parameter = (ParameterSymbol)symbol; if (IsBadLocalOrParameterCapture(parameter, parameter.Type, parameter.RefKind)) { isError = true; Error(diagnostics, ErrorCode.ERR_AnonDelegateCantUse, node, parameter.Name); } return new BoundParameter(node, parameter, hasErrors: isError); } case SymbolKind.NamedType: case SymbolKind.ErrorType: case SymbolKind.TypeParameter: // If I identifies a type, then the result is that type constructed with the // given type arguments. UNDONE: Construct the child type if it is generic! return new BoundTypeExpression(node, null, (TypeSymbol)symbol, hasErrors: isError); case SymbolKind.Property: { BoundExpression receiver = SynthesizeReceiver(node, symbol, diagnostics); return BindPropertyAccess(node, receiver, (PropertySymbol)symbol, diagnostics, resultKind, hasErrors: isError); } case SymbolKind.Event: { BoundExpression receiver = SynthesizeReceiver(node, symbol, diagnostics); return BindEventAccess(node, receiver, (EventSymbol)symbol, diagnostics, resultKind, hasErrors: isError); } case SymbolKind.Field: { BoundExpression receiver = SynthesizeReceiver(node, symbol, diagnostics); return BindFieldAccess(node, receiver, (FieldSymbol)symbol, diagnostics, resultKind, indexed, hasErrors: isError); } case SymbolKind.Namespace: return new BoundNamespaceExpression(node, (NamespaceSymbol)symbol, hasErrors: isError); case SymbolKind.Alias: { var alias = (AliasSymbol)symbol; symbol = alias.Target; switch (symbol.Kind) { case SymbolKind.NamedType: case SymbolKind.ErrorType: return new BoundTypeExpression(node, alias, (NamedTypeSymbol)symbol, hasErrors: isError); case SymbolKind.Namespace: return new BoundNamespaceExpression(node, (NamespaceSymbol)symbol, alias, hasErrors: isError); default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } } case SymbolKind.RangeVariable: return BindRangeVariable(node, (RangeVariableSymbol)symbol, diagnostics); default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } bool isUsedBeforeDeclaration(SimpleNameSyntax node, LocalSymbol localSymbol) { Location localSymbolLocation = localSymbol.Locations[0]; if (node.SyntaxTree == localSymbolLocation.SourceTree) { return node.SpanStart < localSymbolLocation.SourceSpan.Start; } return false; } } private static bool ReportSimpleProgramLocalReferencedOutsideOfTopLevelStatement(SimpleNameSyntax node, Symbol symbol, BindingDiagnosticBag diagnostics) { if (symbol.ContainingSymbol is SynthesizedSimpleProgramEntryPointSymbol) { if (!SyntaxFacts.IsTopLevelStatement(node.Ancestors(ascendOutOfTrivia: false).OfType<GlobalStatementSyntax>().FirstOrDefault())) { Error(diagnostics, ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, node, node); return true; } } return false; } protected virtual BoundExpression BindRangeVariable(SimpleNameSyntax node, RangeVariableSymbol qv, BindingDiagnosticBag diagnostics) { return Next.BindRangeVariable(node, qv, diagnostics); } private BoundExpression SynthesizeReceiver(SyntaxNode node, Symbol member, BindingDiagnosticBag diagnostics) { // SPEC: Otherwise, if T is the instance type of the immediately enclosing class or // struct type, if the lookup identifies an instance member, and if the reference occurs // within the block of an instance constructor, an instance method, or an instance // accessor, the result is the same as a member access of the form this.I. This can only // happen when K is zero. if (!member.RequiresInstanceReceiver()) { return null; } var currentType = this.ContainingType; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; NamedTypeSymbol declaringType = member.ContainingType; if (currentType.IsEqualToOrDerivedFrom(declaringType, TypeCompareKind.ConsiderEverything, useSiteInfo: ref discardedUseSiteInfo) || (currentType.IsInterface && (declaringType.IsObjectType() || currentType.AllInterfacesNoUseSiteDiagnostics.Contains(declaringType)))) { bool hasErrors = false; if (EnclosingNameofArgument != node) { if (InFieldInitializer && !currentType.IsScriptClass) { //can't access "this" in field initializers Error(diagnostics, ErrorCode.ERR_FieldInitRefNonstatic, node, member); hasErrors = true; } else if (InConstructorInitializer || InAttributeArgument) { //can't access "this" in constructor initializers or attribute arguments Error(diagnostics, ErrorCode.ERR_ObjectRequired, node, member); hasErrors = true; } else { // not an instance member if the container is a type, like when binding default parameter values. var containingMember = ContainingMember(); bool locationIsInstanceMember = !containingMember.IsStatic && (containingMember.Kind != SymbolKind.NamedType || currentType.IsScriptClass); if (!locationIsInstanceMember) { // error CS0120: An object reference is required for the non-static field, method, or property '{0}' Error(diagnostics, ErrorCode.ERR_ObjectRequired, node, member); hasErrors = true; } } hasErrors = hasErrors || IsRefOrOutThisParameterCaptured(node, diagnostics); } return ThisReference(node, currentType, hasErrors, wasCompilerGenerated: true); } else { return TryBindInteractiveReceiver(node, declaringType); } } internal Symbol ContainingMember() { return this.ContainingMemberOrLambda.ContainingNonLambdaMember(); } private BoundExpression TryBindInteractiveReceiver(SyntaxNode syntax, NamedTypeSymbol memberDeclaringType) { if (this.ContainingType.TypeKind == TypeKind.Submission // check we have access to `this` && isInstanceContext()) { if (memberDeclaringType.TypeKind == TypeKind.Submission) { return new BoundPreviousSubmissionReference(syntax, memberDeclaringType) { WasCompilerGenerated = true }; } else { TypeSymbol hostObjectType = Compilation.GetHostObjectTypeSymbol(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; if ((object)hostObjectType != null && hostObjectType.IsEqualToOrDerivedFrom(memberDeclaringType, TypeCompareKind.ConsiderEverything, useSiteInfo: ref discardedUseSiteInfo)) { return new BoundHostObjectMemberReference(syntax, hostObjectType) { WasCompilerGenerated = true }; } } } return null; bool isInstanceContext() { var containingMember = this.ContainingMemberOrLambda; do { if (containingMember.IsStatic) { return false; } if (containingMember.Kind == SymbolKind.NamedType) { break; } containingMember = containingMember.ContainingSymbol; } while ((object)containingMember != null); return true; } } public BoundExpression BindNamespaceOrTypeOrExpression(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { if (node.Kind() == SyntaxKind.PredefinedType) { return this.BindNamespaceOrType(node, diagnostics); } if (SyntaxFacts.IsName(node.Kind())) { if (SyntaxFacts.IsNamespaceAliasQualifier(node)) { return this.BindNamespaceAlias((IdentifierNameSyntax)node, diagnostics); } else if (SyntaxFacts.IsInNamespaceOrTypeContext(node)) { return this.BindNamespaceOrType(node, diagnostics); } } else if (SyntaxFacts.IsTypeSyntax(node.Kind())) { return this.BindNamespaceOrType(node, diagnostics); } return this.BindExpression(node, diagnostics, SyntaxFacts.IsInvoked(node), SyntaxFacts.IsIndexed(node)); } public BoundExpression BindLabel(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { var name = node as IdentifierNameSyntax; if (name == null) { Debug.Assert(node.ContainsDiagnostics); return BadExpression(node, LookupResultKind.NotLabel); } var result = LookupResult.GetInstance(); string labelName = name.Identifier.ValueText; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupSymbolsWithFallback(result, labelName, arity: 0, useSiteInfo: ref useSiteInfo, options: LookupOptions.LabelsOnly); diagnostics.Add(node, useSiteInfo); if (!result.IsMultiViable) { Error(diagnostics, ErrorCode.ERR_LabelNotFound, node, labelName); result.Free(); return BadExpression(node, result.Kind); } Debug.Assert(result.IsSingleViable, "If this happens, we need to deal with multiple label definitions."); var symbol = (LabelSymbol)result.Symbols.First(); result.Free(); return new BoundLabel(node, symbol, null); } public BoundExpression BindNamespaceOrType(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { var symbol = this.BindNamespaceOrTypeOrAliasSymbol(node, diagnostics, null, false); return CreateBoundNamespaceOrTypeExpression(node, symbol.Symbol); } public BoundExpression BindNamespaceAlias(IdentifierNameSyntax node, BindingDiagnosticBag diagnostics) { var symbol = this.BindNamespaceAliasSymbol(node, diagnostics); return CreateBoundNamespaceOrTypeExpression(node, symbol); } private static BoundExpression CreateBoundNamespaceOrTypeExpression(ExpressionSyntax node, Symbol symbol) { var alias = symbol as AliasSymbol; if ((object)alias != null) { symbol = alias.Target; } var type = symbol as TypeSymbol; if ((object)type != null) { return new BoundTypeExpression(node, alias, type); } var namespaceSymbol = symbol as NamespaceSymbol; if ((object)namespaceSymbol != null) { return new BoundNamespaceExpression(node, namespaceSymbol, alias); } throw ExceptionUtilities.UnexpectedValue(symbol); } private BoundThisReference BindThis(ThisExpressionSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); bool hasErrors = true; bool inStaticContext; if (!HasThis(isExplicit: true, inStaticContext: out inStaticContext)) { //this error is returned in the field initializer case Error(diagnostics, inStaticContext ? ErrorCode.ERR_ThisInStaticMeth : ErrorCode.ERR_ThisInBadContext, node); } else { hasErrors = IsRefOrOutThisParameterCaptured(node.Token, diagnostics); } return ThisReference(node, this.ContainingType, hasErrors); } private BoundThisReference ThisReference(SyntaxNode node, NamedTypeSymbol thisTypeOpt, bool hasErrors = false, bool wasCompilerGenerated = false) { return new BoundThisReference(node, thisTypeOpt ?? CreateErrorType(), hasErrors) { WasCompilerGenerated = wasCompilerGenerated }; } private bool IsRefOrOutThisParameterCaptured(SyntaxNodeOrToken thisOrBaseToken, BindingDiagnosticBag diagnostics) { ParameterSymbol thisSymbol = this.ContainingMemberOrLambda.EnclosingThisSymbol(); // If there is no this parameter, then it is definitely not captured and // any diagnostic would be cascading. if ((object)thisSymbol != null && thisSymbol.ContainingSymbol != ContainingMemberOrLambda && thisSymbol.RefKind != RefKind.None) { Error(diagnostics, ErrorCode.ERR_ThisStructNotInAnonMeth, thisOrBaseToken); return true; } return false; } private BoundBaseReference BindBase(BaseExpressionSyntax node, BindingDiagnosticBag diagnostics) { bool hasErrors = false; TypeSymbol baseType = this.ContainingType is null ? null : this.ContainingType.BaseTypeNoUseSiteDiagnostics; bool inStaticContext; if (!HasThis(isExplicit: true, inStaticContext: out inStaticContext)) { //this error is returned in the field initializer case Error(diagnostics, inStaticContext ? ErrorCode.ERR_BaseInStaticMeth : ErrorCode.ERR_BaseInBadContext, node.Token); hasErrors = true; } else if ((object)baseType == null) // e.g. in System.Object { Error(diagnostics, ErrorCode.ERR_NoBaseClass, node); hasErrors = true; } else if (this.ContainingType is null || node.Parent is null || (node.Parent.Kind() != SyntaxKind.SimpleMemberAccessExpression && node.Parent.Kind() != SyntaxKind.ElementAccessExpression)) { Error(diagnostics, ErrorCode.ERR_BaseIllegal, node.Token); hasErrors = true; } else if (IsRefOrOutThisParameterCaptured(node.Token, diagnostics)) { // error has been reported by IsRefOrOutThisParameterCaptured hasErrors = true; } return new BoundBaseReference(node, baseType, hasErrors); } private BoundExpression BindCast(CastExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression operand = this.BindValue(node.Expression, diagnostics, BindValueKind.RValue); TypeWithAnnotations targetTypeWithAnnotations = this.BindType(node.Type, diagnostics); TypeSymbol targetType = targetTypeWithAnnotations.Type; if (targetType.IsNullableType() && !operand.HasAnyErrors && (object)operand.Type != null && !operand.Type.IsNullableType() && !TypeSymbol.Equals(targetType.GetNullableUnderlyingType(), operand.Type, TypeCompareKind.ConsiderEverything2)) { return BindExplicitNullableCastFromNonNullable(node, operand, targetTypeWithAnnotations, diagnostics); } return BindCastCore(node, operand, targetTypeWithAnnotations, wasCompilerGenerated: operand.WasCompilerGenerated, diagnostics: diagnostics); } private BoundExpression BindFromEndIndexExpression(PrefixUnaryExpressionSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node.OperatorToken.IsKind(SyntaxKind.CaretToken)); CheckFeatureAvailability(node, MessageID.IDS_FeatureIndexOperator, diagnostics); // Used in lowering as the second argument to the constructor. Example: new Index(value, fromEnd: true) GetSpecialType(SpecialType.System_Boolean, diagnostics, node); BoundExpression boundOperand = BindValue(node.Operand, diagnostics, BindValueKind.RValue); TypeSymbol intType = GetSpecialType(SpecialType.System_Int32, diagnostics, node); TypeSymbol indexType = GetWellKnownType(WellKnownType.System_Index, diagnostics, node); if ((object)boundOperand.Type != null && boundOperand.Type.IsNullableType()) { // Used in lowering to construct the nullable GetSpecialTypeMember(SpecialMember.System_Nullable_T__ctor, diagnostics, node); NamedTypeSymbol nullableType = GetSpecialType(SpecialType.System_Nullable_T, diagnostics, node); if (!indexType.IsNonNullableValueType()) { Error(diagnostics, ErrorCode.ERR_ValConstraintNotSatisfied, node, nullableType, nullableType.TypeParameters.Single(), indexType); } intType = nullableType.Construct(intType); indexType = nullableType.Construct(indexType); } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = this.Conversions.ClassifyImplicitConversionFromExpression(boundOperand, intType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!conversion.IsValid) { GenerateImplicitConversionError(diagnostics, node, conversion, boundOperand, intType); } BoundExpression boundConversion = CreateConversion(boundOperand, conversion, intType, diagnostics); MethodSymbol symbolOpt = GetWellKnownTypeMember(WellKnownMember.System_Index__ctor, diagnostics, syntax: node) as MethodSymbol; return new BoundFromEndIndexExpression(node, boundConversion, symbolOpt, indexType); } private BoundExpression BindRangeExpression(RangeExpressionSyntax node, BindingDiagnosticBag diagnostics) { CheckFeatureAvailability(node, MessageID.IDS_FeatureRangeOperator, diagnostics); TypeSymbol rangeType = GetWellKnownType(WellKnownType.System_Range, diagnostics, node); MethodSymbol symbolOpt = null; if (!rangeType.IsErrorType()) { // Depending on the available arguments to the range expression, there are four // possible well-known members we could bind to. The constructor is always the // fallback member, usable in any situation. However, if any of the other members // are available and applicable, we will prefer that. WellKnownMember? memberOpt = null; if (node.LeftOperand is null && node.RightOperand is null) { memberOpt = WellKnownMember.System_Range__get_All; } else if (node.LeftOperand is null) { memberOpt = WellKnownMember.System_Range__EndAt; } else if (node.RightOperand is null) { memberOpt = WellKnownMember.System_Range__StartAt; } if (memberOpt is object) { symbolOpt = (MethodSymbol)GetWellKnownTypeMember( memberOpt.GetValueOrDefault(), diagnostics, syntax: node, isOptional: true); } if (symbolOpt is null) { symbolOpt = (MethodSymbol)GetWellKnownTypeMember( WellKnownMember.System_Range__ctor, diagnostics, syntax: node); } } BoundExpression left = BindRangeExpressionOperand(node.LeftOperand, diagnostics); BoundExpression right = BindRangeExpressionOperand(node.RightOperand, diagnostics); if (left?.Type.IsNullableType() == true || right?.Type.IsNullableType() == true) { // Used in lowering to construct the nullable GetSpecialType(SpecialType.System_Boolean, diagnostics, node); GetSpecialTypeMember(SpecialMember.System_Nullable_T__ctor, diagnostics, node); NamedTypeSymbol nullableType = GetSpecialType(SpecialType.System_Nullable_T, diagnostics, node); if (!rangeType.IsNonNullableValueType()) { Error(diagnostics, ErrorCode.ERR_ValConstraintNotSatisfied, node, nullableType, nullableType.TypeParameters.Single(), rangeType); } rangeType = nullableType.Construct(rangeType); } return new BoundRangeExpression(node, left, right, symbolOpt, rangeType); } private BoundExpression BindRangeExpressionOperand(ExpressionSyntax operand, BindingDiagnosticBag diagnostics) { if (operand is null) { return null; } BoundExpression boundOperand = BindValue(operand, diagnostics, BindValueKind.RValue); TypeSymbol indexType = GetWellKnownType(WellKnownType.System_Index, diagnostics, operand); if (boundOperand.Type?.IsNullableType() == true) { // Used in lowering to construct the nullable GetSpecialTypeMember(SpecialMember.System_Nullable_T__ctor, diagnostics, operand); NamedTypeSymbol nullableType = GetSpecialType(SpecialType.System_Nullable_T, diagnostics, operand); if (!indexType.IsNonNullableValueType()) { Error(diagnostics, ErrorCode.ERR_ValConstraintNotSatisfied, operand, nullableType, nullableType.TypeParameters.Single(), indexType); } indexType = nullableType.Construct(indexType); } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = this.Conversions.ClassifyImplicitConversionFromExpression(boundOperand, indexType, ref useSiteInfo); diagnostics.Add(operand, useSiteInfo); if (!conversion.IsValid) { GenerateImplicitConversionError(diagnostics, operand, conversion, boundOperand, indexType); } return CreateConversion(boundOperand, conversion, indexType, diagnostics); } private BoundExpression BindCastCore(ExpressionSyntax node, BoundExpression operand, TypeWithAnnotations targetTypeWithAnnotations, bool wasCompilerGenerated, BindingDiagnosticBag diagnostics) { TypeSymbol targetType = targetTypeWithAnnotations.Type; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = this.Conversions.ClassifyConversionFromExpression(operand, targetType, ref useSiteInfo, forCast: true); diagnostics.Add(node, useSiteInfo); var conversionGroup = new ConversionGroup(conversion, targetTypeWithAnnotations); bool suppressErrors = operand.HasAnyErrors || targetType.IsErrorType(); bool hasErrors = !conversion.IsValid || targetType.IsStatic; if (hasErrors && !suppressErrors) { GenerateExplicitConversionErrors(diagnostics, node, conversion, operand, targetType); } return CreateConversion(node, operand, conversion, isCast: true, conversionGroupOpt: conversionGroup, wasCompilerGenerated: wasCompilerGenerated, destination: targetType, diagnostics: diagnostics, hasErrors: hasErrors | suppressErrors); } private void GenerateExplicitConversionErrors( BindingDiagnosticBag diagnostics, SyntaxNode syntax, Conversion conversion, BoundExpression operand, TypeSymbol targetType) { // Make sure that errors within the unbound lambda don't get lost. if (operand.Kind == BoundKind.UnboundLambda) { GenerateAnonymousFunctionConversionError(diagnostics, operand.Syntax, (UnboundLambda)operand, targetType); return; } if (operand.HasAnyErrors || targetType.IsErrorType()) { // an error has already been reported elsewhere return; } if (targetType.IsStatic) { // The specification states in the section titled "Referencing Static // Class Types" that it is always illegal to have a static class in a // cast operator. diagnostics.Add(ErrorCode.ERR_ConvertToStaticClass, syntax.Location, targetType); return; } if (!targetType.IsReferenceType && !targetType.IsNullableType() && operand.IsLiteralNull()) { diagnostics.Add(ErrorCode.ERR_ValueCantBeNull, syntax.Location, targetType); return; } if (conversion.ResultKind == LookupResultKind.OverloadResolutionFailure) { Debug.Assert(conversion.IsUserDefined); ImmutableArray<MethodSymbol> originalUserDefinedConversions = conversion.OriginalUserDefinedConversions; if (originalUserDefinedConversions.Length > 1) { diagnostics.Add(ErrorCode.ERR_AmbigUDConv, syntax.Location, originalUserDefinedConversions[0], originalUserDefinedConversions[1], operand.Display, targetType); } else { Debug.Assert(originalUserDefinedConversions.Length == 0, "How can there be exactly one applicable user-defined conversion if the conversion doesn't exist?"); SymbolDistinguisher distinguisher1 = new SymbolDistinguisher(this.Compilation, operand.Type, targetType); diagnostics.Add(ErrorCode.ERR_NoExplicitConv, syntax.Location, distinguisher1.First, distinguisher1.Second); } return; } switch (operand.Kind) { case BoundKind.MethodGroup: { if (targetType.TypeKind != TypeKind.Delegate || !MethodGroupConversionDoesNotExistOrHasErrors((BoundMethodGroup)operand, (NamedTypeSymbol)targetType, syntax.Location, diagnostics, out _)) { diagnostics.Add(ErrorCode.ERR_NoExplicitConv, syntax.Location, MessageID.IDS_SK_METHOD.Localize(), targetType); } return; } case BoundKind.TupleLiteral: { var tuple = (BoundTupleLiteral)operand; var targetElementTypesWithAnnotations = default(ImmutableArray<TypeWithAnnotations>); // If target is a tuple or compatible type with the same number of elements, // report errors for tuple arguments that failed to convert, which would be more useful. if (targetType.TryGetElementTypesWithAnnotationsIfTupleType(out targetElementTypesWithAnnotations) && targetElementTypesWithAnnotations.Length == tuple.Arguments.Length) { GenerateExplicitConversionErrorsForTupleLiteralArguments(diagnostics, tuple.Arguments, targetElementTypesWithAnnotations); return; } // target is not compatible with source and source does not have a type if ((object)tuple.Type == null) { Error(diagnostics, ErrorCode.ERR_ConversionNotTupleCompatible, syntax, tuple.Arguments.Length, targetType); return; } // Otherwise it is just a regular conversion failure from T1 to T2. break; } case BoundKind.StackAllocArrayCreation: { var stackAllocExpression = (BoundStackAllocArrayCreation)operand; Error(diagnostics, ErrorCode.ERR_StackAllocConversionNotPossible, syntax, stackAllocExpression.ElementType, targetType); return; } case BoundKind.UnconvertedConditionalOperator when operand.Type is null: case BoundKind.UnconvertedSwitchExpression when operand.Type is null: { GenerateImplicitConversionError(diagnostics, operand.Syntax, conversion, operand, targetType); return; } case BoundKind.UnconvertedAddressOfOperator: { var errorCode = targetType.TypeKind switch { TypeKind.FunctionPointer => ErrorCode.ERR_MethFuncPtrMismatch, TypeKind.Delegate => ErrorCode.ERR_CannotConvertAddressOfToDelegate, _ => ErrorCode.ERR_AddressOfToNonFunctionPointer }; diagnostics.Add(errorCode, syntax.Location, ((BoundUnconvertedAddressOfOperator)operand).Operand.Name, targetType); return; } } Debug.Assert((object)operand.Type != null); SymbolDistinguisher distinguisher = new SymbolDistinguisher(this.Compilation, operand.Type, targetType); diagnostics.Add(ErrorCode.ERR_NoExplicitConv, syntax.Location, distinguisher.First, distinguisher.Second); } private void GenerateExplicitConversionErrorsForTupleLiteralArguments( BindingDiagnosticBag diagnostics, ImmutableArray<BoundExpression> tupleArguments, ImmutableArray<TypeWithAnnotations> targetElementTypesWithAnnotations) { // report all leaf elements of the tuple literal that failed to convert // NOTE: we are not responsible for reporting use site errors here, just the failed leaf conversions. // By the time we get here we have done analysis and know we have failed the cast in general, and diagnostics collected in the process is already in the bag. // The only thing left is to form a diagnostics about the actually failing conversion(s). // This whole method does not itself collect any usesite diagnostics. Its only purpose is to produce an error better than "conversion failed here" var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; for (int i = 0; i < targetElementTypesWithAnnotations.Length; i++) { var argument = tupleArguments[i]; var targetElementType = targetElementTypesWithAnnotations[i].Type; var elementConversion = Conversions.ClassifyConversionFromExpression(argument, targetElementType, ref discardedUseSiteInfo); if (!elementConversion.IsValid) { GenerateExplicitConversionErrors(diagnostics, argument.Syntax, elementConversion, argument, targetElementType); } } } /// <summary> /// This implements the casting behavior described in section 6.2.3 of the spec: /// /// - If the nullable conversion is from S to T?, the conversion is evaluated as the underlying conversion /// from S to T followed by a wrapping from T to T?. /// /// This particular check is done in the binder because it involves conversion processing rules (like overflow /// checking and constant folding) which are not handled by Conversions. /// </summary> private BoundExpression BindExplicitNullableCastFromNonNullable(ExpressionSyntax node, BoundExpression operand, TypeWithAnnotations targetTypeWithAnnotations, BindingDiagnosticBag diagnostics) { Debug.Assert(targetTypeWithAnnotations.HasType && targetTypeWithAnnotations.IsNullableType()); Debug.Assert((object)operand.Type != null && !operand.Type.IsNullableType()); // Section 6.2.3 of the spec only applies when the non-null version of the types involved have a // built in conversion. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; TypeWithAnnotations underlyingTargetTypeWithAnnotations = targetTypeWithAnnotations.Type.GetNullableUnderlyingTypeWithAnnotations(); var underlyingConversion = Conversions.ClassifyBuiltInConversion(operand.Type, underlyingTargetTypeWithAnnotations.Type, ref discardedUseSiteInfo); if (!underlyingConversion.Exists) { return BindCastCore(node, operand, targetTypeWithAnnotations, wasCompilerGenerated: operand.WasCompilerGenerated, diagnostics: diagnostics); } var bag = new BindingDiagnosticBag(DiagnosticBag.GetInstance(), diagnostics.DependenciesBag); try { var underlyingExpr = BindCastCore(node, operand, underlyingTargetTypeWithAnnotations, wasCompilerGenerated: false, diagnostics: bag); if (underlyingExpr.HasErrors || bag.HasAnyErrors()) { Error(diagnostics, ErrorCode.ERR_NoExplicitConv, node, operand.Type, targetTypeWithAnnotations.Type); return new BoundConversion( node, operand, Conversion.NoConversion, @checked: CheckOverflowAtRuntime, explicitCastInCode: true, conversionGroupOpt: new ConversionGroup(Conversion.NoConversion, explicitType: targetTypeWithAnnotations), constantValueOpt: ConstantValue.NotAvailable, type: targetTypeWithAnnotations.Type, hasErrors: true); } // It's possible for the S -> T conversion to produce a 'better' constant value. If this // constant value is produced place it in the tree so that it gets emitted. This maintains // parity with the native compiler which also evaluated the conversion at compile time. if (underlyingExpr.ConstantValue != null) { underlyingExpr.WasCompilerGenerated = true; return BindCastCore(node, underlyingExpr, targetTypeWithAnnotations, wasCompilerGenerated: operand.WasCompilerGenerated, diagnostics: diagnostics); } return BindCastCore(node, operand, targetTypeWithAnnotations, wasCompilerGenerated: operand.WasCompilerGenerated, diagnostics: diagnostics); } finally { bag.DiagnosticBag.Free(); } } private static NameSyntax GetNameSyntax(SyntaxNode syntax) { string nameString; return GetNameSyntax(syntax, out nameString); } /// <summary> /// Gets the NameSyntax associated with the syntax node /// If no syntax is attached it sets the nameString to plain text /// name and returns a null NameSyntax /// </summary> /// <param name="syntax">Syntax node</param> /// <param name="nameString">Plain text name</param> internal static NameSyntax GetNameSyntax(SyntaxNode syntax, out string nameString) { nameString = string.Empty; while (true) { switch (syntax.Kind()) { case SyntaxKind.PredefinedType: nameString = ((PredefinedTypeSyntax)syntax).Keyword.ValueText; return null; case SyntaxKind.SimpleLambdaExpression: nameString = MessageID.IDS_Lambda.Localize().ToString(); return null; case SyntaxKind.ParenthesizedExpression: syntax = ((ParenthesizedExpressionSyntax)syntax).Expression; continue; case SyntaxKind.CastExpression: syntax = ((CastExpressionSyntax)syntax).Expression; continue; case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: return ((MemberAccessExpressionSyntax)syntax).Name; case SyntaxKind.MemberBindingExpression: return ((MemberBindingExpressionSyntax)syntax).Name; default: return syntax as NameSyntax; } } } /// <summary> /// Gets the plain text name associated with the expression syntax node /// </summary> /// <param name="syntax">Expression syntax node</param> /// <returns>Plain text name</returns> private static string GetName(ExpressionSyntax syntax) { string nameString; var nameSyntax = GetNameSyntax(syntax, out nameString); if (nameSyntax != null) { return nameSyntax.GetUnqualifiedName().Identifier.ValueText; } return nameString; } // Given a list of arguments, create arrays of the bound arguments and the names of those // arguments. private void BindArgumentsAndNames(ArgumentListSyntax argumentListOpt, BindingDiagnosticBag diagnostics, AnalyzedArguments result, bool allowArglist = false, bool isDelegateCreation = false) { if (argumentListOpt != null) { BindArgumentsAndNames(argumentListOpt.Arguments, diagnostics, result, allowArglist, isDelegateCreation: isDelegateCreation); } } private void BindArgumentsAndNames(BracketedArgumentListSyntax argumentListOpt, BindingDiagnosticBag diagnostics, AnalyzedArguments result) { if (argumentListOpt != null) { BindArgumentsAndNames(argumentListOpt.Arguments, diagnostics, result, allowArglist: false); } } private void BindArgumentsAndNames( SeparatedSyntaxList<ArgumentSyntax> arguments, BindingDiagnosticBag diagnostics, AnalyzedArguments result, bool allowArglist, bool isDelegateCreation = false) { // Only report the first "duplicate name" or "named before positional" error, // so as to avoid "cascading" errors. bool hadError = false; // Only report the first "non-trailing named args required C# 7.2" error, // so as to avoid "cascading" errors. bool hadLangVersionError = false; foreach (var argumentSyntax in arguments) { BindArgumentAndName(result, diagnostics, ref hadError, ref hadLangVersionError, argumentSyntax, allowArglist, isDelegateCreation: isDelegateCreation); } } private bool RefMustBeObeyed(bool isDelegateCreation, ArgumentSyntax argumentSyntax) { if (Compilation.FeatureStrictEnabled || !isDelegateCreation) { return true; } switch (argumentSyntax.Expression.Kind()) { // The next 3 cases should never be allowed as they cannot be ref/out. Assuming a bug in legacy compiler. case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.AnonymousMethodExpression: case SyntaxKind.InvocationExpression: case SyntaxKind.ObjectCreationExpression: case SyntaxKind.ImplicitObjectCreationExpression: case SyntaxKind.ParenthesizedExpression: // this is never allowed in legacy compiler case SyntaxKind.DeclarationExpression: // A property/indexer is also invalid as it cannot be ref/out, but cannot be checked here. Assuming a bug in legacy compiler. return true; default: // The only ones that concern us here for compat is: locals, params, fields // BindArgumentAndName correctly rejects all other cases, except for properties and indexers. // They are handled after BindArgumentAndName returns and the binding can be checked. return false; } } private void BindArgumentAndName( AnalyzedArguments result, BindingDiagnosticBag diagnostics, ref bool hadError, ref bool hadLangVersionError, ArgumentSyntax argumentSyntax, bool allowArglist, bool isDelegateCreation = false) { RefKind origRefKind = argumentSyntax.RefOrOutKeyword.Kind().GetRefKind(); // The old native compiler ignores ref/out in a delegate creation expression. // For compatibility we implement the same bug except in strict mode. // Note: Some others should still be rejected when ref/out present. See RefMustBeObeyed. RefKind refKind = origRefKind == RefKind.None || RefMustBeObeyed(isDelegateCreation, argumentSyntax) ? origRefKind : RefKind.None; BoundExpression boundArgument = BindArgumentValue(diagnostics, argumentSyntax, allowArglist, refKind); BindArgumentAndName( result, diagnostics, ref hadLangVersionError, argumentSyntax, boundArgument, argumentSyntax.NameColon, refKind); // check for ref/out property/indexer, only needed for 1 parameter version if (!hadError && isDelegateCreation && origRefKind != RefKind.None && result.Arguments.Count == 1) { var arg = result.Argument(0); switch (arg.Kind) { case BoundKind.PropertyAccess: case BoundKind.IndexerAccess: var requiredValueKind = origRefKind == RefKind.In ? BindValueKind.ReadonlyRef : BindValueKind.RefOrOut; hadError = !CheckValueKind(argumentSyntax, arg, requiredValueKind, false, diagnostics); return; } } if (argumentSyntax.RefOrOutKeyword.Kind() != SyntaxKind.None) { argumentSyntax.Expression.CheckDeconstructionCompatibleArgument(diagnostics); } } private BoundExpression BindArgumentValue(BindingDiagnosticBag diagnostics, ArgumentSyntax argumentSyntax, bool allowArglist, RefKind refKind) { if (argumentSyntax.Expression.Kind() == SyntaxKind.DeclarationExpression) { var declarationExpression = (DeclarationExpressionSyntax)argumentSyntax.Expression; if (declarationExpression.IsOutDeclaration()) { return BindOutDeclarationArgument(declarationExpression, diagnostics); } } return BindArgumentExpression(diagnostics, argumentSyntax.Expression, refKind, allowArglist); } private BoundExpression BindOutDeclarationArgument(DeclarationExpressionSyntax declarationExpression, BindingDiagnosticBag diagnostics) { TypeSyntax typeSyntax = declarationExpression.Type; VariableDesignationSyntax designation = declarationExpression.Designation; if (typeSyntax.GetRefKind() != RefKind.None) { diagnostics.Add(ErrorCode.ERR_OutVariableCannotBeByRef, declarationExpression.Type.Location); } switch (designation.Kind()) { case SyntaxKind.DiscardDesignation: { bool isVar; bool isConst = false; AliasSymbol alias; var declType = BindVariableTypeWithAnnotations(designation, diagnostics, typeSyntax, ref isConst, out isVar, out alias); Debug.Assert(isVar != declType.HasType); return new BoundDiscardExpression(declarationExpression, declType.Type); } case SyntaxKind.SingleVariableDesignation: return BindOutVariableDeclarationArgument(declarationExpression, diagnostics); default: throw ExceptionUtilities.UnexpectedValue(designation.Kind()); } } private BoundExpression BindOutVariableDeclarationArgument( DeclarationExpressionSyntax declarationExpression, BindingDiagnosticBag diagnostics) { Debug.Assert(declarationExpression.IsOutVarDeclaration()); bool isVar; var designation = (SingleVariableDesignationSyntax)declarationExpression.Designation; TypeSyntax typeSyntax = declarationExpression.Type; // Is this a local? SourceLocalSymbol localSymbol = this.LookupLocal(designation.Identifier); if ((object)localSymbol != null) { Debug.Assert(localSymbol.DeclarationKind == LocalDeclarationKind.OutVariable); if ((InConstructorInitializer || InFieldInitializer) && ContainingMemberOrLambda.ContainingSymbol.Kind == SymbolKind.NamedType) { CheckFeatureAvailability(declarationExpression, MessageID.IDS_FeatureExpressionVariablesInQueriesAndInitializers, diagnostics); } bool isConst = false; AliasSymbol alias; var declType = BindVariableTypeWithAnnotations(declarationExpression, diagnostics, typeSyntax, ref isConst, out isVar, out alias); localSymbol.ScopeBinder.ValidateDeclarationNameConflictsInScope(localSymbol, diagnostics); if (isVar) { return new OutVariablePendingInference(declarationExpression, localSymbol, null); } CheckRestrictedTypeInAsyncMethod(this.ContainingMemberOrLambda, declType.Type, diagnostics, typeSyntax); return new BoundLocal(declarationExpression, localSymbol, BoundLocalDeclarationKind.WithExplicitType, constantValueOpt: null, isNullableUnknown: false, type: declType.Type); } // Is this a field? GlobalExpressionVariable expressionVariableField = LookupDeclaredField(designation); if ((object)expressionVariableField == null) { // We should have the right binder in the chain, cannot continue otherwise. throw ExceptionUtilities.Unreachable; } BoundExpression receiver = SynthesizeReceiver(designation, expressionVariableField, diagnostics); if (typeSyntax.IsVar) { BindTypeOrAliasOrVarKeyword(typeSyntax, BindingDiagnosticBag.Discarded, out isVar); if (isVar) { return new OutVariablePendingInference(declarationExpression, expressionVariableField, receiver); } } TypeSymbol fieldType = expressionVariableField.GetFieldType(this.FieldsBeingBound).Type; return new BoundFieldAccess(declarationExpression, receiver, expressionVariableField, null, LookupResultKind.Viable, isDeclaration: true, type: fieldType); } /// <summary> /// Returns true if a bad special by ref local was found. /// </summary> internal static bool CheckRestrictedTypeInAsyncMethod(Symbol containingSymbol, TypeSymbol type, BindingDiagnosticBag diagnostics, SyntaxNode syntax) { if (containingSymbol.Kind == SymbolKind.Method && ((MethodSymbol)containingSymbol).IsAsync && type.IsRestrictedType()) { Error(diagnostics, ErrorCode.ERR_BadSpecialByRefLocal, syntax, type); return true; } return false; } internal GlobalExpressionVariable LookupDeclaredField(SingleVariableDesignationSyntax variableDesignator) { return LookupDeclaredField(variableDesignator, variableDesignator.Identifier.ValueText); } internal GlobalExpressionVariable LookupDeclaredField(SyntaxNode node, string identifier) { foreach (Symbol member in ContainingType?.GetMembers(identifier) ?? ImmutableArray<Symbol>.Empty) { GlobalExpressionVariable field; if (member.Kind == SymbolKind.Field && (field = member as GlobalExpressionVariable)?.SyntaxTree == node.SyntaxTree && field.SyntaxNode == node) { return field; } } return null; } // Bind a named/positional argument. // Prevent cascading diagnostic by considering the previous // error state and returning the updated error state. private void BindArgumentAndName( AnalyzedArguments result, BindingDiagnosticBag diagnostics, ref bool hadLangVersionError, CSharpSyntaxNode argumentSyntax, BoundExpression boundArgumentExpression, NameColonSyntax nameColonSyntax, RefKind refKind) { Debug.Assert(argumentSyntax is ArgumentSyntax || argumentSyntax is AttributeArgumentSyntax); bool hasRefKinds = result.RefKinds.Any(); if (refKind != RefKind.None) { // The common case is no ref or out arguments. So we defer all work until the first one is seen. if (!hasRefKinds) { hasRefKinds = true; int argCount = result.Arguments.Count; for (int i = 0; i < argCount; ++i) { result.RefKinds.Add(RefKind.None); } } } if (hasRefKinds) { result.RefKinds.Add(refKind); } bool hasNames = result.Names.Any(); if (nameColonSyntax != null) { // The common case is no named arguments. So we defer all work until the first named argument is seen. if (!hasNames) { hasNames = true; int argCount = result.Arguments.Count; for (int i = 0; i < argCount; ++i) { result.Names.Add(null); } } result.AddName(nameColonSyntax.Name); } else if (hasNames) { // We just saw a fixed-position argument after a named argument. if (!hadLangVersionError && !Compilation.LanguageVersion.AllowNonTrailingNamedArguments()) { // CS1738: Named argument specifications must appear after all fixed arguments have been specified Error(diagnostics, ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, argumentSyntax, new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureNonTrailingNamedArguments.RequiredVersion())); hadLangVersionError = true; } result.Names.Add(null); } result.Arguments.Add(boundArgumentExpression); } /// <summary> /// Bind argument and verify argument matches rvalue or out param requirements. /// </summary> private BoundExpression BindArgumentExpression(BindingDiagnosticBag diagnostics, ExpressionSyntax argumentExpression, RefKind refKind, bool allowArglist) { BindValueKind valueKind = refKind == RefKind.None ? BindValueKind.RValue : refKind == RefKind.In ? BindValueKind.ReadonlyRef : BindValueKind.RefOrOut; BoundExpression argument; if (allowArglist) { argument = this.BindValueAllowArgList(argumentExpression, diagnostics, valueKind); } else { argument = this.BindValue(argumentExpression, diagnostics, valueKind); } return argument; } #nullable enable private void CoerceArguments<TMember>( MemberResolutionResult<TMember> methodResult, ArrayBuilder<BoundExpression> arguments, BindingDiagnosticBag diagnostics, TypeSymbol? receiverType, RefKind? receiverRefKind, uint receiverEscapeScope) where TMember : Symbol { var result = methodResult.Result; // Parameter types should be taken from the least overridden member: var parameters = methodResult.LeastOverriddenMember.GetParameters(); for (int arg = 0; arg < arguments.Count; ++arg) { var kind = result.ConversionForArg(arg); BoundExpression argument = arguments[arg]; if (kind.IsInterpolatedStringHandler) { Debug.Assert(argument is BoundUnconvertedInterpolatedString); TypeWithAnnotations parameterTypeWithAnnotations = GetCorrespondingParameterTypeWithAnnotations(ref result, parameters, arg); reportUnsafeIfNeeded(methodResult, diagnostics, argument, parameterTypeWithAnnotations); arguments[arg] = BindInterpolatedStringHandlerInMemberCall((BoundUnconvertedInterpolatedString)argument, arguments, parameters, ref result, arg, receiverType, receiverRefKind, receiverEscapeScope, diagnostics); } // https://github.com/dotnet/roslyn/issues/37119 : should we create an (Identity) conversion when the kind is Identity but the types differ? else if (!kind.IsIdentity) { TypeWithAnnotations parameterTypeWithAnnotations = GetCorrespondingParameterTypeWithAnnotations(ref result, parameters, arg); reportUnsafeIfNeeded(methodResult, diagnostics, argument, parameterTypeWithAnnotations); arguments[arg] = CreateConversion(argument.Syntax, argument, kind, isCast: false, conversionGroupOpt: null, parameterTypeWithAnnotations.Type, diagnostics); } else if (argument.Kind == BoundKind.OutVariablePendingInference) { TypeWithAnnotations parameterTypeWithAnnotations = GetCorrespondingParameterTypeWithAnnotations(ref result, parameters, arg); arguments[arg] = ((OutVariablePendingInference)argument).SetInferredTypeWithAnnotations(parameterTypeWithAnnotations, diagnostics); } else if (argument.Kind == BoundKind.OutDeconstructVarPendingInference) { TypeWithAnnotations parameterTypeWithAnnotations = GetCorrespondingParameterTypeWithAnnotations(ref result, parameters, arg); arguments[arg] = ((OutDeconstructVarPendingInference)argument).SetInferredTypeWithAnnotations(parameterTypeWithAnnotations, this, success: true); } else if (argument.Kind == BoundKind.DiscardExpression && !argument.HasExpressionType()) { TypeWithAnnotations parameterTypeWithAnnotations = GetCorrespondingParameterTypeWithAnnotations(ref result, parameters, arg); Debug.Assert(parameterTypeWithAnnotations.HasType); arguments[arg] = ((BoundDiscardExpression)argument).SetInferredTypeWithAnnotations(parameterTypeWithAnnotations); } else if (argument.NeedsToBeConverted()) { Debug.Assert(kind.IsIdentity); if (argument is BoundTupleLiteral) { TypeWithAnnotations parameterTypeWithAnnotations = GetCorrespondingParameterTypeWithAnnotations(ref result, parameters, arg); // CreateConversion reports tuple literal name mismatches, and constructs the expected pattern of bound nodes. arguments[arg] = CreateConversion(argument.Syntax, argument, kind, isCast: false, conversionGroupOpt: null, parameterTypeWithAnnotations.Type, diagnostics); } else { arguments[arg] = BindToNaturalType(argument, diagnostics); } } } void reportUnsafeIfNeeded(MemberResolutionResult<TMember> methodResult, BindingDiagnosticBag diagnostics, BoundExpression argument, TypeWithAnnotations parameterTypeWithAnnotations) { // NOTE: for some reason, dev10 doesn't report this for indexer accesses. if (!methodResult.Member.IsIndexer() && !argument.HasAnyErrors && parameterTypeWithAnnotations.Type.IsUnsafe()) { // CONSIDER: dev10 uses the call syntax, but this seems clearer. ReportUnsafeIfNotAllowed(argument.Syntax, diagnostics); //CONSIDER: Return a bad expression so that HasErrors is true? } } } private static ParameterSymbol GetCorrespondingParameter(ref MemberAnalysisResult result, ImmutableArray<ParameterSymbol> parameters, int arg) { int paramNum = result.ParameterFromArgument(arg); return parameters[paramNum]; } #nullable disable private static TypeWithAnnotations GetCorrespondingParameterTypeWithAnnotations(ref MemberAnalysisResult result, ImmutableArray<ParameterSymbol> parameters, int arg) { int paramNum = result.ParameterFromArgument(arg); var type = parameters[paramNum].TypeWithAnnotations; if (paramNum == parameters.Length - 1 && result.Kind == MemberResolutionKind.ApplicableInExpandedForm) { type = ((ArrayTypeSymbol)type.Type).ElementTypeWithAnnotations; } return type; } private BoundExpression BindArrayCreationExpression(ArrayCreationExpressionSyntax node, BindingDiagnosticBag diagnostics) { // SPEC begins // // An array-creation-expression is used to create a new instance of an array-type. // // array-creation-expression: // new non-array-type[expression-list] rank-specifiersopt array-initializeropt // new array-type array-initializer // new rank-specifier array-initializer // // An array creation expression of the first form allocates an array instance of the // type that results from deleting each of the individual expressions from the // expression list. For example, the array creation expression new int[10, 20] produces // an array instance of type int[,], and the array creation expression new int[10][,] // produces an array of type int[][,]. Each expression in the expression list must be of // type int, uint, long, or ulong, or implicitly convertible to one or more of these // types. The value of each expression determines the length of the corresponding // dimension in the newly allocated array instance. Since the length of an array // dimension must be nonnegative, it is a compile-time error to have a // constant-expression with a negative value in the expression list. // // If an array creation expression of the first form includes an array initializer, each // expression in the expression list must be a constant and the rank and dimension // lengths specified by the expression list must match those of the array initializer. // // In an array creation expression of the second or third form, the rank of the // specified array type or rank specifier must match that of the array initializer. The // individual dimension lengths are inferred from the number of elements in each of the // corresponding nesting levels of the array initializer. Thus, the expression new // int[,] {{0, 1}, {2, 3}, {4, 5}} exactly corresponds to new int[3, 2] {{0, 1}, {2, 3}, // {4, 5}} // // An array creation expression of the third form is referred to as an implicitly typed // array creation expression. It is similar to the second form, except that the element // type of the array is not explicitly given, but determined as the best common type // (7.5.2.14) of the set of expressions in the array initializer. For a multidimensional // array, i.e., one where the rank-specifier contains at least one comma, this set // comprises all expressions found in nested array-initializers. // // An array creation expression permits instantiation of an array with elements of an // array type, but the elements of such an array must be manually initialized. For // example, the statement // // int[][] a = new int[100][]; // // creates a single-dimensional array with 100 elements of type int[]. The initial value // of each element is null. It is not possible for the same array creation expression to // also instantiate the sub-arrays, and the statement // // int[][] a = new int[100][5]; // Error // // results in a compile-time error. // // The following are examples of implicitly typed array creation expressions: // // var a = new[] { 1, 10, 100, 1000 }; // int[] // var b = new[] { 1, 1.5, 2, 2.5 }; // double[] // var c = new[,] { { "hello", null }, { "world", "!" } }; // string[,] // var d = new[] { 1, "one", 2, "two" }; // Error // // The last expression causes a compile-time error because neither int nor string is // implicitly convertible to the other, and so there is no best common type. An // explicitly typed array creation expression must be used in this case, for example // specifying the type to be object[]. Alternatively, one of the elements can be cast to // a common base type, which would then become the inferred element type. // // SPEC ends var type = (ArrayTypeSymbol)BindArrayType(node.Type, diagnostics, permitDimensions: true, basesBeingResolved: null, disallowRestrictedTypes: true).Type; // CONSIDER: // // There may be erroneous rank specifiers in the source code, for example: // // int y = 123; // int[][] z = new int[10][y]; // // The "10" is legal but the "y" is not. If we are in such a situation we do have the // "y" expression syntax stashed away in the syntax tree. However, we do *not* perform // semantic analysis. This means that "go to definition" on "y" does not work, and so // on. We might consider doing a semantic analysis here (with error suppression; a parse // error has already been reported) so that "go to definition" works. ArrayBuilder<BoundExpression> sizes = ArrayBuilder<BoundExpression>.GetInstance(); ArrayRankSpecifierSyntax firstRankSpecifier = node.Type.RankSpecifiers[0]; bool hasErrors = false; foreach (var arg in firstRankSpecifier.Sizes) { var size = BindArrayDimension(arg, diagnostics, ref hasErrors); if (size != null) { sizes.Add(size); } else if (node.Initializer is null && arg == firstRankSpecifier.Sizes[0]) { Error(diagnostics, ErrorCode.ERR_MissingArraySize, firstRankSpecifier); hasErrors = true; } } // produce errors for additional sizes in the ranks for (int additionalRankIndex = 1; additionalRankIndex < node.Type.RankSpecifiers.Count; additionalRankIndex++) { var rank = node.Type.RankSpecifiers[additionalRankIndex]; var dimension = rank.Sizes; foreach (var arg in dimension) { if (arg.Kind() != SyntaxKind.OmittedArraySizeExpression) { var size = BindRValueWithoutTargetType(arg, diagnostics); Error(diagnostics, ErrorCode.ERR_InvalidArray, arg); hasErrors = true; // Capture the invalid sizes for `SemanticModel` and `IOperation` sizes.Add(size); } } } ImmutableArray<BoundExpression> arraySizes = sizes.ToImmutableAndFree(); return node.Initializer == null ? new BoundArrayCreation(node, arraySizes, null, type, hasErrors) : BindArrayCreationWithInitializer(diagnostics, node, node.Initializer, type, arraySizes, hasErrors: hasErrors); } private BoundExpression BindArrayDimension(ExpressionSyntax dimension, BindingDiagnosticBag diagnostics, ref bool hasErrors) { // These make the parse tree nicer, but they shouldn't actually appear in the bound tree. if (dimension.Kind() != SyntaxKind.OmittedArraySizeExpression) { var size = BindValue(dimension, diagnostics, BindValueKind.RValue); if (!size.HasAnyErrors) { size = ConvertToArrayIndex(size, diagnostics, allowIndexAndRange: false); if (IsNegativeConstantForArraySize(size)) { Error(diagnostics, ErrorCode.ERR_NegativeArraySize, dimension); hasErrors = true; } } else { size = BindToTypeForErrorRecovery(size); } return size; } return null; } private BoundExpression BindImplicitArrayCreationExpression(ImplicitArrayCreationExpressionSyntax node, BindingDiagnosticBag diagnostics) { // See BindArrayCreationExpression method above for implicitly typed array creation SPEC. InitializerExpressionSyntax initializer = node.Initializer; int rank = node.Commas.Count + 1; ImmutableArray<BoundExpression> boundInitializerExpressions = BindArrayInitializerExpressions(initializer, diagnostics, dimension: 1, rank: rank); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); TypeSymbol bestType = BestTypeInferrer.InferBestType(boundInitializerExpressions, this.Conversions, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if ((object)bestType == null || bestType.IsVoidType()) // Dev10 also reports ERR_ImplicitlyTypedArrayNoBestType for void. { Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, node); bestType = CreateErrorType(); } if (bestType.IsRestrictedType()) { // CS0611: Array elements cannot be of type '{0}' Error(diagnostics, ErrorCode.ERR_ArrayElementCantBeRefAny, node, bestType); } // Element type nullability will be inferred in flow analysis and does not need to be set here. var arrayType = ArrayTypeSymbol.CreateCSharpArray(Compilation.Assembly, TypeWithAnnotations.Create(bestType), rank); return BindArrayCreationWithInitializer(diagnostics, node, initializer, arrayType, sizes: ImmutableArray<BoundExpression>.Empty, boundInitExprOpt: boundInitializerExpressions); } private BoundExpression BindImplicitStackAllocArrayCreationExpression(ImplicitStackAllocArrayCreationExpressionSyntax node, BindingDiagnosticBag diagnostics) { InitializerExpressionSyntax initializer = node.Initializer; ImmutableArray<BoundExpression> boundInitializerExpressions = BindArrayInitializerExpressions(initializer, diagnostics, dimension: 1, rank: 1); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); TypeSymbol bestType = BestTypeInferrer.InferBestType(boundInitializerExpressions, this.Conversions, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if ((object)bestType == null || bestType.IsVoidType()) { Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, node); bestType = CreateErrorType(); } if (!bestType.IsErrorType()) { CheckManagedAddr(Compilation, bestType, node.Location, diagnostics); } return BindStackAllocWithInitializer( node, initializer, type: GetStackAllocType(node, TypeWithAnnotations.Create(bestType), diagnostics, out bool hasErrors), elementType: bestType, sizeOpt: null, diagnostics, hasErrors: hasErrors, boundInitializerExpressions); } // This method binds all the array initializer expressions. // NOTE: It doesn't convert the bound initializer expressions to array's element type. // NOTE: This is done separately in ConvertAndBindArrayInitialization method below. private ImmutableArray<BoundExpression> BindArrayInitializerExpressions(InitializerExpressionSyntax initializer, BindingDiagnosticBag diagnostics, int dimension, int rank) { var exprBuilder = ArrayBuilder<BoundExpression>.GetInstance(); BindArrayInitializerExpressions(initializer, exprBuilder, diagnostics, dimension, rank); return exprBuilder.ToImmutableAndFree(); } /// <summary> /// This method walks through the array's InitializerExpressionSyntax and binds all the initializer expressions recursively. /// NOTE: It doesn't convert the bound initializer expressions to array's element type. /// NOTE: This is done separately in ConvertAndBindArrayInitialization method below. /// </summary> /// <param name="initializer">Initializer Syntax.</param> /// <param name="exprBuilder">Bound expression builder.</param> /// <param name="diagnostics">Diagnostics.</param> /// <param name="dimension">Current array dimension being processed.</param> /// <param name="rank">Rank of the array type.</param> private void BindArrayInitializerExpressions(InitializerExpressionSyntax initializer, ArrayBuilder<BoundExpression> exprBuilder, BindingDiagnosticBag diagnostics, int dimension, int rank) { Debug.Assert(rank > 0); Debug.Assert(dimension > 0 && dimension <= rank); Debug.Assert(exprBuilder != null); if (dimension == rank) { // We are processing the nth dimension of a rank-n array. We expect that these will // only be values, not array initializers. foreach (var expression in initializer.Expressions) { var boundExpression = BindValue(expression, diagnostics, BindValueKind.RValue); exprBuilder.Add(boundExpression); } } else { // Inductive case; we'd better have another array initializer foreach (var expression in initializer.Expressions) { if (expression.Kind() == SyntaxKind.ArrayInitializerExpression) { BindArrayInitializerExpressions((InitializerExpressionSyntax)expression, exprBuilder, diagnostics, dimension + 1, rank); } else { // We have non-array initializer expression, but we expected an array initializer expression. var boundExpression = BindValue(expression, diagnostics, BindValueKind.RValue); if ((object)boundExpression.Type == null || !boundExpression.Type.IsErrorType()) { if (!boundExpression.HasAnyErrors) { Error(diagnostics, ErrorCode.ERR_ArrayInitializerExpected, expression); } // Wrap the expression with a bound bad expression with error type. boundExpression = BadExpression( expression, LookupResultKind.Empty, ImmutableArray.Create(boundExpression.ExpressionSymbol), ImmutableArray.Create(boundExpression)); } exprBuilder.Add(boundExpression); } } } } /// <summary> /// Given an array of bound initializer expressions, this method converts these bound expressions /// to array's element type and generates a BoundArrayInitialization with the converted initializers. /// </summary> /// <param name="diagnostics">Diagnostics.</param> /// <param name="node">Initializer Syntax.</param> /// <param name="type">Array type.</param> /// <param name="knownSizes">Known array bounds.</param> /// <param name="dimension">Current array dimension being processed.</param> /// <param name="boundInitExpr">Array of bound initializer expressions.</param> /// <param name="boundInitExprIndex"> /// Index into the array of bound initializer expressions to fetch the next bound expression. /// </param> /// <returns></returns> private BoundArrayInitialization ConvertAndBindArrayInitialization( BindingDiagnosticBag diagnostics, InitializerExpressionSyntax node, ArrayTypeSymbol type, int?[] knownSizes, int dimension, ImmutableArray<BoundExpression> boundInitExpr, ref int boundInitExprIndex) { Debug.Assert(!boundInitExpr.IsDefault); ArrayBuilder<BoundExpression> initializers = ArrayBuilder<BoundExpression>.GetInstance(); if (dimension == type.Rank) { // We are processing the nth dimension of a rank-n array. We expect that these will // only be values, not array initializers. TypeSymbol elemType = type.ElementType; foreach (var expressionSyntax in node.Expressions) { Debug.Assert(boundInitExprIndex >= 0 && boundInitExprIndex < boundInitExpr.Length); BoundExpression boundExpression = boundInitExpr[boundInitExprIndex]; boundInitExprIndex++; BoundExpression convertedExpression = GenerateConversionForAssignment(elemType, boundExpression, diagnostics); initializers.Add(convertedExpression); } } else { // Inductive case; we'd better have another array initializer foreach (var expr in node.Expressions) { BoundExpression init = null; if (expr.Kind() == SyntaxKind.ArrayInitializerExpression) { init = ConvertAndBindArrayInitialization(diagnostics, (InitializerExpressionSyntax)expr, type, knownSizes, dimension + 1, boundInitExpr, ref boundInitExprIndex); } else { // We have non-array initializer expression, but we expected an array initializer expression. // We have already generated the diagnostics during binding, so just fetch the bound expression. Debug.Assert(boundInitExprIndex >= 0 && boundInitExprIndex < boundInitExpr.Length); init = boundInitExpr[boundInitExprIndex]; Debug.Assert(init.HasAnyErrors); Debug.Assert(init.Type.IsErrorType()); boundInitExprIndex++; } initializers.Add(init); } } bool hasErrors = false; var knownSizeOpt = knownSizes[dimension - 1]; if (knownSizeOpt == null) { knownSizes[dimension - 1] = initializers.Count; } else if (knownSizeOpt != initializers.Count) { // No need to report an error if the known size is negative // since we've already reported CS0248 earlier and it's // expected that the number of initializers won't match. if (knownSizeOpt >= 0) { Error(diagnostics, ErrorCode.ERR_ArrayInitializerIncorrectLength, node, knownSizeOpt.Value); hasErrors = true; } } return new BoundArrayInitialization(node, initializers.ToImmutableAndFree(), hasErrors: hasErrors); } private BoundArrayInitialization BindArrayInitializerList( BindingDiagnosticBag diagnostics, InitializerExpressionSyntax node, ArrayTypeSymbol type, int?[] knownSizes, int dimension, ImmutableArray<BoundExpression> boundInitExprOpt = default(ImmutableArray<BoundExpression>)) { // Bind the array initializer expressions, if not already bound. // NOTE: Initializer expressions might already be bound for implicitly type array creation // NOTE: during array's element type inference. if (boundInitExprOpt.IsDefault) { boundInitExprOpt = BindArrayInitializerExpressions(node, diagnostics, dimension, type.Rank); } // Convert the bound array initializer expressions to array's element type and // generate BoundArrayInitialization with the converted initializers. int boundInitExprIndex = 0; return ConvertAndBindArrayInitialization(diagnostics, node, type, knownSizes, dimension, boundInitExprOpt, ref boundInitExprIndex); } private BoundArrayInitialization BindUnexpectedArrayInitializer( InitializerExpressionSyntax node, BindingDiagnosticBag diagnostics, ErrorCode errorCode, CSharpSyntaxNode errorNode = null) { var result = BindArrayInitializerList( diagnostics, node, this.Compilation.CreateArrayTypeSymbol(GetSpecialType(SpecialType.System_Object, diagnostics, node)), new int?[1], dimension: 1); if (!result.HasAnyErrors) { result = new BoundArrayInitialization(node, result.Initializers, hasErrors: true); } Error(diagnostics, errorCode, errorNode ?? node); return result; } // We could be in the cases // // (1) int[] x = { a, b } // (2) new int[] { a, b } // (3) new int[2] { a, b } // (4) new [] { a, b } // // In case (1) there is no creation syntax. // In cases (2) and (3) creation syntax is an ArrayCreationExpression. // In case (4) creation syntax is an ImplicitArrayCreationExpression. // // In cases (1), (2) and (4) there are no sizes. // // The initializer syntax is always provided. // // If we are in case (3) and sizes are provided then the number of sizes must match the rank // of the array type passed in. // For case (4), i.e. ImplicitArrayCreationExpression, we must have already bound the // initializer expressions for best type inference. // These bound expressions are stored in boundInitExprOpt and reused in creating // BoundArrayInitialization to avoid binding them twice. private BoundArrayCreation BindArrayCreationWithInitializer( BindingDiagnosticBag diagnostics, ExpressionSyntax creationSyntax, InitializerExpressionSyntax initSyntax, ArrayTypeSymbol type, ImmutableArray<BoundExpression> sizes, ImmutableArray<BoundExpression> boundInitExprOpt = default(ImmutableArray<BoundExpression>), bool hasErrors = false) { Debug.Assert(creationSyntax == null || creationSyntax.Kind() == SyntaxKind.ArrayCreationExpression || creationSyntax.Kind() == SyntaxKind.ImplicitArrayCreationExpression); Debug.Assert(initSyntax != null); Debug.Assert((object)type != null); Debug.Assert(boundInitExprOpt.IsDefault || creationSyntax.Kind() == SyntaxKind.ImplicitArrayCreationExpression); // NOTE: In error scenarios, it may be the case sizes.Count > type.Rank. // For example, new int[1 2] has 2 sizes, but rank 1 (since there are 0 commas). int rank = type.Rank; int numSizes = sizes.Length; int?[] knownSizes = new int?[Math.Max(rank, numSizes)]; // If there are sizes given and there is an array initializer, then every size must be a // constant. (We'll check later that it matches) for (int i = 0; i < numSizes; ++i) { // Here we are being bug-for-bug compatible with C# 4. When you have code like // byte[] b = new[uint.MaxValue] { 2 }; // you might expect an error that says that the number of elements in the initializer does // not match the size of the array. But in C# 4 if the constant does not fit into an integer // then we confusingly give the error "that's not a constant". // NOTE: in the example above, GetIntegerConstantForArraySize is returning null because the // size doesn't fit in an int - not because it doesn't match the initializer length. var size = sizes[i]; knownSizes[i] = GetIntegerConstantForArraySize(size); if (!size.HasAnyErrors && knownSizes[i] == null) { Error(diagnostics, ErrorCode.ERR_ConstantExpected, size.Syntax); hasErrors = true; } } // KnownSizes is further mutated by BindArrayInitializerList as it works out more // information about the sizes. BoundArrayInitialization initializer = BindArrayInitializerList(diagnostics, initSyntax, type, knownSizes, 1, boundInitExprOpt); hasErrors = hasErrors || initializer.HasAnyErrors; bool hasCreationSyntax = creationSyntax != null; CSharpSyntaxNode nonNullSyntax = (CSharpSyntaxNode)creationSyntax ?? initSyntax; // Construct a set of size expressions if we were not given any. // // It is possible in error scenarios that some of the bounds were not determined. Substitute // zeroes for those. if (numSizes == 0) { BoundExpression[] sizeArray = new BoundExpression[rank]; for (int i = 0; i < rank; i++) { sizeArray[i] = new BoundLiteral( nonNullSyntax, ConstantValue.Create(knownSizes[i] ?? 0), GetSpecialType(SpecialType.System_Int32, diagnostics, nonNullSyntax)) { WasCompilerGenerated = true }; } sizes = sizeArray.AsImmutableOrNull(); } else if (!hasErrors && rank != numSizes) { Error(diagnostics, ErrorCode.ERR_BadIndexCount, nonNullSyntax, type.Rank); hasErrors = true; } return new BoundArrayCreation(nonNullSyntax, sizes, initializer, type, hasErrors: hasErrors) { WasCompilerGenerated = !hasCreationSyntax && (initSyntax.Parent == null || initSyntax.Parent.Kind() != SyntaxKind.EqualsValueClause || ((EqualsValueClauseSyntax)initSyntax.Parent).Value != initSyntax) }; } private BoundExpression BindStackAllocArrayCreationExpression( StackAllocArrayCreationExpressionSyntax node, BindingDiagnosticBag diagnostics) { TypeSyntax typeSyntax = node.Type; if (typeSyntax.Kind() != SyntaxKind.ArrayType) { Error(diagnostics, ErrorCode.ERR_BadStackAllocExpr, typeSyntax); return new BoundBadExpression( node, LookupResultKind.NotCreatable, //in this context, anyway ImmutableArray<Symbol>.Empty, ImmutableArray<BoundExpression>.Empty, new PointerTypeSymbol(BindType(typeSyntax, diagnostics))); } ArrayTypeSyntax arrayTypeSyntax = (ArrayTypeSyntax)typeSyntax; var elementTypeSyntax = arrayTypeSyntax.ElementType; var arrayType = (ArrayTypeSymbol)BindArrayType(arrayTypeSyntax, diagnostics, permitDimensions: true, basesBeingResolved: null, disallowRestrictedTypes: false).Type; var elementType = arrayType.ElementTypeWithAnnotations; TypeSymbol type = GetStackAllocType(node, elementType, diagnostics, out bool hasErrors); if (!elementType.Type.IsErrorType()) { hasErrors = hasErrors || CheckManagedAddr(Compilation, elementType.Type, elementTypeSyntax.Location, diagnostics); } SyntaxList<ArrayRankSpecifierSyntax> rankSpecifiers = arrayTypeSyntax.RankSpecifiers; if (rankSpecifiers.Count != 1 || rankSpecifiers[0].Sizes.Count != 1) { // NOTE: Dev10 reported several parse errors here. Error(diagnostics, ErrorCode.ERR_BadStackAllocExpr, typeSyntax); var builder = ArrayBuilder<BoundExpression>.GetInstance(); foreach (ArrayRankSpecifierSyntax rankSpecifier in rankSpecifiers) { foreach (ExpressionSyntax size in rankSpecifier.Sizes) { if (size.Kind() != SyntaxKind.OmittedArraySizeExpression) { builder.Add(BindExpression(size, BindingDiagnosticBag.Discarded)); } } } return new BoundBadExpression( node, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, builder.ToImmutableAndFree(), new PointerTypeSymbol(elementType)); } ExpressionSyntax countSyntax = rankSpecifiers[0].Sizes[0]; BoundExpression count = null; if (countSyntax.Kind() != SyntaxKind.OmittedArraySizeExpression) { count = BindValue(countSyntax, diagnostics, BindValueKind.RValue); count = GenerateConversionForAssignment(GetSpecialType(SpecialType.System_Int32, diagnostics, node), count, diagnostics); if (IsNegativeConstantForArraySize(count)) { Error(diagnostics, ErrorCode.ERR_NegativeStackAllocSize, countSyntax); hasErrors = true; } } else if (node.Initializer == null) { Error(diagnostics, ErrorCode.ERR_MissingArraySize, rankSpecifiers[0]); count = BadExpression(countSyntax); hasErrors = true; } return node.Initializer == null ? new BoundStackAllocArrayCreation(node, elementType.Type, count, initializerOpt: null, type, hasErrors: hasErrors) : BindStackAllocWithInitializer(node, node.Initializer, type, elementType.Type, count, diagnostics, hasErrors); } private bool ReportBadStackAllocPosition(SyntaxNode node, BindingDiagnosticBag diagnostics) { Debug.Assert(node is StackAllocArrayCreationExpressionSyntax || node is ImplicitStackAllocArrayCreationExpressionSyntax); bool inLegalPosition = true; // If we are using a language version that does not restrict the position of a stackalloc expression, skip that test. LanguageVersion requiredVersion = MessageID.IDS_FeatureNestedStackalloc.RequiredVersion(); if (requiredVersion > Compilation.LanguageVersion) { inLegalPosition = (IsInMethodBody || IsLocalFunctionsScopeBinder) && node.IsLegalCSharp73SpanStackAllocPosition(); if (!inLegalPosition) { MessageID.IDS_FeatureNestedStackalloc.CheckFeatureAvailability(diagnostics, node, node.GetFirstToken().GetLocation()); } } // Check if we're syntactically within a catch or finally clause. if (this.Flags.IncludesAny(BinderFlags.InCatchBlock | BinderFlags.InCatchFilter | BinderFlags.InFinallyBlock)) { Error(diagnostics, ErrorCode.ERR_StackallocInCatchFinally, node); } return inLegalPosition; } private TypeSymbol GetStackAllocType(SyntaxNode node, TypeWithAnnotations elementTypeWithAnnotations, BindingDiagnosticBag diagnostics, out bool hasErrors) { var inLegalPosition = ReportBadStackAllocPosition(node, diagnostics); hasErrors = !inLegalPosition; if (inLegalPosition && !isStackallocTargetTyped(node)) { CheckFeatureAvailability(node, MessageID.IDS_FeatureRefStructs, diagnostics); var spanType = GetWellKnownType(WellKnownType.System_Span_T, diagnostics, node); return ConstructNamedType( type: spanType, typeSyntax: node.Kind() == SyntaxKind.StackAllocArrayCreationExpression ? ((StackAllocArrayCreationExpressionSyntax)node).Type : node, typeArgumentsSyntax: default, typeArguments: ImmutableArray.Create(elementTypeWithAnnotations), basesBeingResolved: null, diagnostics: diagnostics); } // We treat the stackalloc as target-typed, so we give it a null type for now. return null; // Is this a context in which a stackalloc expression could be converted to the corresponding pointer // type? The only context that permits it is the initialization of a local variable declaration (when // the declaration appears as a statement or as the first part of a for loop). static bool isStackallocTargetTyped(SyntaxNode node) { Debug.Assert(node != null); SyntaxNode equalsValueClause = node.Parent; if (!equalsValueClause.IsKind(SyntaxKind.EqualsValueClause)) { return false; } SyntaxNode variableDeclarator = equalsValueClause.Parent; if (!variableDeclarator.IsKind(SyntaxKind.VariableDeclarator)) { return false; } SyntaxNode variableDeclaration = variableDeclarator.Parent; if (!variableDeclaration.IsKind(SyntaxKind.VariableDeclaration)) { return false; } return variableDeclaration.Parent.IsKind(SyntaxKind.LocalDeclarationStatement) || variableDeclaration.Parent.IsKind(SyntaxKind.ForStatement); } } private BoundExpression BindStackAllocWithInitializer( SyntaxNode node, InitializerExpressionSyntax initSyntax, TypeSymbol type, TypeSymbol elementType, BoundExpression sizeOpt, BindingDiagnosticBag diagnostics, bool hasErrors, ImmutableArray<BoundExpression> boundInitExprOpt = default) { Debug.Assert(node.IsKind(SyntaxKind.ImplicitStackAllocArrayCreationExpression) || node.IsKind(SyntaxKind.StackAllocArrayCreationExpression)); if (boundInitExprOpt.IsDefault) { boundInitExprOpt = BindArrayInitializerExpressions(initSyntax, diagnostics, dimension: 1, rank: 1); } boundInitExprOpt = boundInitExprOpt.SelectAsArray((expr, t) => GenerateConversionForAssignment(t.elementType, expr, t.diagnostics), (elementType, diagnostics)); if (sizeOpt != null) { if (!sizeOpt.HasAnyErrors) { int? constantSizeOpt = GetIntegerConstantForArraySize(sizeOpt); if (constantSizeOpt == null) { Error(diagnostics, ErrorCode.ERR_ConstantExpected, sizeOpt.Syntax); hasErrors = true; } else if (boundInitExprOpt.Length != constantSizeOpt) { Error(diagnostics, ErrorCode.ERR_ArrayInitializerIncorrectLength, node, constantSizeOpt.Value); hasErrors = true; } } } else { sizeOpt = new BoundLiteral( node, ConstantValue.Create(boundInitExprOpt.Length), GetSpecialType(SpecialType.System_Int32, diagnostics, node)) { WasCompilerGenerated = true }; } return new BoundStackAllocArrayCreation(node, elementType, sizeOpt, new BoundArrayInitialization(initSyntax, boundInitExprOpt), type, hasErrors); } private static int? GetIntegerConstantForArraySize(BoundExpression expression) { // If the bound could have been converted to int, then it was. If it could not have been // converted to int, and it was a constant, then it was out of range. Debug.Assert(expression != null); if (expression.HasAnyErrors) { return null; } var constantValue = expression.ConstantValue; if (constantValue == null || constantValue.IsBad || expression.Type.SpecialType != SpecialType.System_Int32) { return null; } return constantValue.Int32Value; } private static bool IsNegativeConstantForArraySize(BoundExpression expression) { Debug.Assert(expression != null); if (expression.HasAnyErrors) { return false; } var constantValue = expression.ConstantValue; if (constantValue == null || constantValue.IsBad) { return false; } var type = expression.Type.SpecialType; if (type == SpecialType.System_Int32) { return constantValue.Int32Value < 0; } if (type == SpecialType.System_Int64) { return constantValue.Int64Value < 0; } // By the time we get here we definitely have int, long, uint or ulong. Obviously the // latter two are never negative. Debug.Assert(type == SpecialType.System_UInt32 || type == SpecialType.System_UInt64); return false; } /// <summary> /// Bind the (implicit or explicit) constructor initializer of a constructor symbol (in source). /// </summary> /// <param name="initializerArgumentListOpt"> /// Null for implicit, /// <see cref="ConstructorInitializerSyntax.ArgumentList"/>, or /// <see cref="PrimaryConstructorBaseTypeSyntax.ArgumentList"/> for explicit.</param> /// <param name="constructor">Constructor containing the initializer.</param> /// <param name="diagnostics">Accumulates errors (e.g. unable to find constructor to invoke).</param> /// <returns>A bound expression for the constructor initializer call.</returns> /// <remarks> /// This method should be kept consistent with Compiler.BindConstructorInitializer (e.g. same error codes). /// </remarks> internal BoundExpression BindConstructorInitializer( ArgumentListSyntax initializerArgumentListOpt, MethodSymbol constructor, BindingDiagnosticBag diagnostics) { Binder argumentListBinder = null; if (initializerArgumentListOpt != null) { argumentListBinder = this.GetBinder(initializerArgumentListOpt); } var result = (argumentListBinder ?? this).BindConstructorInitializerCore(initializerArgumentListOpt, constructor, diagnostics); if (argumentListBinder != null) { // This code is reachable only for speculative SemanticModel. Debug.Assert(argumentListBinder.IsSemanticModelBinder); result = argumentListBinder.WrapWithVariablesIfAny(initializerArgumentListOpt, result); } return result; } private BoundExpression BindConstructorInitializerCore( ArgumentListSyntax initializerArgumentListOpt, MethodSymbol constructor, BindingDiagnosticBag diagnostics) { // Either our base type is not object, or we have an initializer syntax, or both. We're going to // need to do overload resolution on the set of constructors of the base type, either on // the provided initializer syntax, or on an implicit ": base()" syntax. // SPEC ERROR: The specification states that if you have the situation // SPEC ERROR: class B { ... } class D1 : B {} then the default constructor // SPEC ERROR: generated for D1 must call an accessible *parameterless* constructor // SPEC ERROR: in B. However, it also states that if you have // SPEC ERROR: class B { ... } class D2 : B { D2() {} } or // SPEC ERROR: class B { ... } class D3 : B { D3() : base() {} } then // SPEC ERROR: the compiler performs *overload resolution* to determine // SPEC ERROR: which accessible constructor of B is called. Since B might have // SPEC ERROR: a ctor with all optional parameters, overload resolution might // SPEC ERROR: succeed even if there is no parameterless constructor. This // SPEC ERROR: is unintentionally inconsistent, and the native compiler does not // SPEC ERROR: implement this behavior. Rather, we should say in the spec that // SPEC ERROR: if there is no ctor in D1, then a ctor is created for you exactly // SPEC ERROR: as though you'd said "D1() : base() {}". // SPEC ERROR: This is what we now do in Roslyn. Debug.Assert((object)constructor != null); Debug.Assert(constructor.MethodKind == MethodKind.Constructor || constructor.MethodKind == MethodKind.StaticConstructor); // error scenario: constructor initializer on static constructor Debug.Assert(diagnostics != null); NamedTypeSymbol containingType = constructor.ContainingType; // Structs and enums do not have implicit constructor initializers. if ((containingType.TypeKind == TypeKind.Enum || containingType.TypeKind == TypeKind.Struct) && initializerArgumentListOpt == null) { return null; } AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance(); try { TypeSymbol constructorReturnType = constructor.ReturnType; Debug.Assert(constructorReturnType.IsVoidType()); //true of all constructors NamedTypeSymbol baseType = containingType.BaseTypeNoUseSiteDiagnostics; // Get the bound arguments and the argument names. // : this(__arglist()) is legal if (initializerArgumentListOpt != null) { this.BindArgumentsAndNames(initializerArgumentListOpt, diagnostics, analyzedArguments, allowArglist: true); } NamedTypeSymbol initializerType = containingType; bool isBaseConstructorInitializer = initializerArgumentListOpt == null || initializerArgumentListOpt.Parent.Kind() != SyntaxKind.ThisConstructorInitializer; if (isBaseConstructorInitializer) { initializerType = initializerType.BaseTypeNoUseSiteDiagnostics; // Soft assert: we think this is the case, and we're asserting to catch scenarios that violate our expectations Debug.Assert((object)initializerType != null || containingType.SpecialType == SpecialType.System_Object || containingType.IsInterface); if ((object)initializerType == null || containingType.SpecialType == SpecialType.System_Object) //e.g. when defining System.Object in source { // If the constructor initializer is implicit and there is no base type, we're done. // Otherwise, if the constructor initializer is explicit, we're in an error state. if (initializerArgumentListOpt == null) { return null; } else { diagnostics.Add(ErrorCode.ERR_ObjectCallingBaseConstructor, constructor.Locations[0], containingType); return new BoundBadExpression( syntax: initializerArgumentListOpt.Parent, resultKind: LookupResultKind.Empty, symbols: ImmutableArray<Symbol>.Empty, childBoundNodes: BuildArgumentsForErrorRecovery(analyzedArguments), type: constructorReturnType); } } else if (initializerArgumentListOpt != null && containingType.TypeKind == TypeKind.Struct) { diagnostics.Add(ErrorCode.ERR_StructWithBaseConstructorCall, constructor.Locations[0], containingType); return new BoundBadExpression( syntax: initializerArgumentListOpt.Parent, resultKind: LookupResultKind.Empty, symbols: ImmutableArray<Symbol>.Empty, //CONSIDER: we could look for a matching constructor on System.ValueType childBoundNodes: BuildArgumentsForErrorRecovery(analyzedArguments), type: constructorReturnType); } } else { Debug.Assert(initializerArgumentListOpt.Parent.Kind() == SyntaxKind.ThisConstructorInitializer); } CSharpSyntaxNode nonNullSyntax; Location errorLocation; bool enableCallerInfo; switch (initializerArgumentListOpt?.Parent) { case ConstructorInitializerSyntax initializerSyntax: nonNullSyntax = initializerSyntax; errorLocation = initializerSyntax.ThisOrBaseKeyword.GetLocation(); enableCallerInfo = true; break; case PrimaryConstructorBaseTypeSyntax baseWithArguments: nonNullSyntax = baseWithArguments; errorLocation = initializerArgumentListOpt.GetLocation(); enableCallerInfo = true; break; default: // Note: use syntax node of constructor with initializer, not constructor invoked by initializer (i.e. methodResolutionResult). nonNullSyntax = constructor.GetNonNullSyntaxNode(); errorLocation = constructor.Locations[0]; enableCallerInfo = false; break; } if (initializerArgumentListOpt != null && analyzedArguments.HasDynamicArgument) { diagnostics.Add(ErrorCode.ERR_NoDynamicPhantomOnBaseCtor, errorLocation); return new BoundBadExpression( syntax: initializerArgumentListOpt.Parent, resultKind: LookupResultKind.Empty, symbols: ImmutableArray<Symbol>.Empty, //CONSIDER: we could look for a matching constructor on System.ValueType childBoundNodes: BuildArgumentsForErrorRecovery(analyzedArguments), type: constructorReturnType); } BoundExpression receiver = ThisReference(nonNullSyntax, initializerType, wasCompilerGenerated: true); MemberResolutionResult<MethodSymbol> memberResolutionResult; ImmutableArray<MethodSymbol> candidateConstructors; bool found = TryPerformConstructorOverloadResolution( initializerType, analyzedArguments, WellKnownMemberNames.InstanceConstructorName, errorLocation, false, // Don't suppress result diagnostics diagnostics, out memberResolutionResult, out candidateConstructors, allowProtectedConstructorsOfBaseType: true); MethodSymbol resultMember = memberResolutionResult.Member; validateRecordCopyConstructor(constructor, baseType, resultMember, errorLocation, diagnostics); if (found) { bool hasErrors = false; if (resultMember == constructor) { Debug.Assert(initializerType.IsErrorType() || (initializerArgumentListOpt != null && initializerArgumentListOpt.Parent.Kind() == SyntaxKind.ThisConstructorInitializer)); diagnostics.Add(ErrorCode.ERR_RecursiveConstructorCall, errorLocation, constructor); hasErrors = true; // prevent recursive constructor from being emitted } else if (resultMember.HasUnsafeParameter()) { // What if some of the arguments are implicit? Dev10 reports unsafe errors // if the implied argument would have an unsafe type. We need to check // the parameters explicitly, since there won't be bound nodes for the implied // arguments until lowering. // Don't worry about double reporting (i.e. for both the argument and the parameter) // because only one unsafe diagnostic is allowed per scope - the others are suppressed. hasErrors = ReportUnsafeIfNotAllowed(errorLocation, diagnostics); } ReportDiagnosticsIfObsolete(diagnostics, resultMember, nonNullSyntax, hasBaseReceiver: isBaseConstructorInitializer); var expanded = memberResolutionResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm; var argsToParamsOpt = memberResolutionResult.Result.ArgsToParamsOpt; BindDefaultArguments(nonNullSyntax, resultMember.Parameters, analyzedArguments.Arguments, analyzedArguments.RefKinds, ref argsToParamsOpt, out var defaultArguments, expanded, enableCallerInfo, diagnostics); var arguments = analyzedArguments.Arguments.ToImmutable(); var refKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); if (!hasErrors) { hasErrors = !CheckInvocationArgMixing( nonNullSyntax, resultMember, receiver, resultMember.Parameters, arguments, argsToParamsOpt, this.LocalScopeDepth, diagnostics); } return new BoundCall( nonNullSyntax, receiver, resultMember, arguments, analyzedArguments.GetNames(), refKinds, isDelegateCall: false, expanded, invokedAsExtensionMethod: false, argsToParamsOpt: argsToParamsOpt, defaultArguments: defaultArguments, resultKind: LookupResultKind.Viable, type: constructorReturnType, hasErrors: hasErrors) { WasCompilerGenerated = initializerArgumentListOpt == null }; } else { var result = CreateBadCall( node: nonNullSyntax, name: WellKnownMemberNames.InstanceConstructorName, receiver: receiver, methods: candidateConstructors, resultKind: LookupResultKind.OverloadResolutionFailure, typeArgumentsWithAnnotations: ImmutableArray<TypeWithAnnotations>.Empty, analyzedArguments: analyzedArguments, invokedAsExtensionMethod: false, isDelegate: false); result.WasCompilerGenerated = initializerArgumentListOpt == null; return result; } } finally { analyzedArguments.Free(); } static void validateRecordCopyConstructor(MethodSymbol constructor, NamedTypeSymbol baseType, MethodSymbol resultMember, Location errorLocation, BindingDiagnosticBag diagnostics) { if (IsUserDefinedRecordCopyConstructor(constructor)) { if (baseType.SpecialType == SpecialType.System_Object) { if (resultMember is null || resultMember.ContainingType.SpecialType != SpecialType.System_Object) { // Record deriving from object must use `base()`, not `this()` diagnostics.Add(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, errorLocation); } return; } // Unless the base type is 'object', the constructor should invoke a base type copy constructor if (resultMember is null || !SynthesizedRecordCopyCtor.HasCopyConstructorSignature(resultMember)) { diagnostics.Add(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, errorLocation); } } } } internal static bool IsUserDefinedRecordCopyConstructor(MethodSymbol constructor) { return constructor.ContainingType is SourceNamedTypeSymbol sourceType && sourceType.IsRecord && constructor is not SynthesizedRecordConstructor && SynthesizedRecordCopyCtor.HasCopyConstructorSignature(constructor); } private BoundExpression BindImplicitObjectCreationExpression(ImplicitObjectCreationExpressionSyntax node, BindingDiagnosticBag diagnostics) { var arguments = AnalyzedArguments.GetInstance(); BindArgumentsAndNames(node.ArgumentList, diagnostics, arguments, allowArglist: true); var result = new BoundUnconvertedObjectCreationExpression( node, arguments.Arguments.ToImmutable(), arguments.Names.ToImmutableOrNull(), arguments.RefKinds.ToImmutableOrNull(), node.Initializer); arguments.Free(); return result; } protected BoundExpression BindObjectCreationExpression(ObjectCreationExpressionSyntax node, BindingDiagnosticBag diagnostics) { var typeWithAnnotations = BindType(node.Type, diagnostics); var type = typeWithAnnotations.Type; var originalType = type; if (typeWithAnnotations.NullableAnnotation.IsAnnotated() && !type.IsNullableType()) { diagnostics.Add(ErrorCode.ERR_AnnotationDisallowedInObjectCreation, node.Location, type); } switch (type.TypeKind) { case TypeKind.Struct: case TypeKind.Class: case TypeKind.Enum: case TypeKind.Error: return BindClassCreationExpression(node, (NamedTypeSymbol)type, GetName(node.Type), diagnostics, originalType); case TypeKind.Delegate: return BindDelegateCreationExpression(node, (NamedTypeSymbol)type, diagnostics); case TypeKind.Interface: return BindInterfaceCreationExpression(node, (NamedTypeSymbol)type, diagnostics); case TypeKind.TypeParameter: return BindTypeParameterCreationExpression(node, (TypeParameterSymbol)type, diagnostics); case TypeKind.Submission: // script class is synthesized and should not be used as a type of a new expression: throw ExceptionUtilities.UnexpectedValue(type.TypeKind); case TypeKind.Pointer: case TypeKind.FunctionPointer: type = new ExtendedErrorTypeSymbol(type, LookupResultKind.NotCreatable, diagnostics.Add(ErrorCode.ERR_UnsafeTypeInObjectCreation, node.Location, type)); goto case TypeKind.Class; case TypeKind.Dynamic: // we didn't find any type called "dynamic" so we are using the builtin dynamic type, which has no constructors: case TypeKind.Array: // ex: new ref[] type = new ExtendedErrorTypeSymbol(type, LookupResultKind.NotCreatable, diagnostics.Add(ErrorCode.ERR_InvalidObjectCreation, node.Type.Location, type)); goto case TypeKind.Class; default: throw ExceptionUtilities.UnexpectedValue(type.TypeKind); } } private BoundExpression BindDelegateCreationExpression(ObjectCreationExpressionSyntax node, NamedTypeSymbol type, BindingDiagnosticBag diagnostics) { AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance(); BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments, isDelegateCreation: true); var result = BindDelegateCreationExpression(node, type, analyzedArguments, node.Initializer, diagnostics); analyzedArguments.Free(); return result; } private BoundExpression BindDelegateCreationExpression(SyntaxNode node, NamedTypeSymbol type, AnalyzedArguments analyzedArguments, InitializerExpressionSyntax initializerOpt, BindingDiagnosticBag diagnostics) { bool hasErrors = false; if (analyzedArguments.HasErrors) { // Let's skip this part of further error checking without marking hasErrors = true here, // as the argument could be an unbound lambda, and the error could come from inside. // We'll check analyzedArguments.HasErrors again after we find if this is not the case. } else if (analyzedArguments.Arguments.Count == 0) { diagnostics.Add(ErrorCode.ERR_BadCtorArgCount, node.Location, type, 0); hasErrors = true; } else if (analyzedArguments.Names.Count != 0 || analyzedArguments.RefKinds.Count != 0 || analyzedArguments.Arguments.Count != 1) { // Use a smaller span that excludes the parens. var argSyntax = analyzedArguments.Arguments[0].Syntax; var start = argSyntax.SpanStart; var end = analyzedArguments.Arguments[analyzedArguments.Arguments.Count - 1].Syntax.Span.End; var errorSpan = new TextSpan(start, end - start); var loc = new SourceLocation(argSyntax.SyntaxTree, errorSpan); diagnostics.Add(ErrorCode.ERR_MethodNameExpected, loc); hasErrors = true; } if (initializerOpt != null) { Error(diagnostics, ErrorCode.ERR_ObjectOrCollectionInitializerWithDelegateCreation, node); hasErrors = true; } BoundExpression argument = analyzedArguments.Arguments.Count >= 1 ? BindToNaturalType(analyzedArguments.Arguments[0], diagnostics) : null; if (hasErrors) { // skip the rest of this binding } // There are four cases for a delegate creation expression (7.6.10.5): // 1. An anonymous function is treated as a conversion from the anonymous function to the delegate type. else if (argument is UnboundLambda unboundLambda) { // analyzedArguments.HasErrors could be true, // but here the argument is an unbound lambda, the error comes from inside // eg: new Action<int>(x => x.) // We should try to bind it anyway in order for intellisense to work. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var conversion = this.Conversions.ClassifyConversionFromExpression(unboundLambda, type, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); // Attempting to make the conversion caches the diagnostics and the bound state inside // the unbound lambda. Fetch the result from the cache. BoundLambda boundLambda = unboundLambda.Bind(type); if (!conversion.IsImplicit || !conversion.IsValid) { GenerateImplicitConversionError(diagnostics, unboundLambda.Syntax, conversion, unboundLambda, type); } else { // We're not going to produce an error, but it is possible that the conversion from // the lambda to the delegate type produced a warning, which we have not reported. // Instead, we've cached it in the bound lambda. Report it now. diagnostics.AddRange(boundLambda.Diagnostics); } // Just stuff the bound lambda into the delegate creation expression. When we lower the lambda to // its method form we will rewrite this expression to refer to the method. return new BoundDelegateCreationExpression(node, boundLambda, methodOpt: null, isExtensionMethod: false, type: type, hasErrors: !conversion.IsImplicit); } else if (analyzedArguments.HasErrors) { // There is no hope, skip. } // 2. A method group else if (argument.Kind == BoundKind.MethodGroup) { Conversion conversion; BoundMethodGroup methodGroup = (BoundMethodGroup)argument; hasErrors = MethodGroupConversionDoesNotExistOrHasErrors(methodGroup, type, node.Location, diagnostics, out conversion); methodGroup = FixMethodGroupWithTypeOrValue(methodGroup, conversion, diagnostics); return new BoundDelegateCreationExpression(node, methodGroup, conversion.Method, conversion.IsExtensionMethod, type, hasErrors); } else if ((object)argument.Type == null) { diagnostics.Add(ErrorCode.ERR_MethodNameExpected, argument.Syntax.Location); } // 3. A value of the compile-time type dynamic (which is dynamically case 4), or else if (argument.HasDynamicType()) { return new BoundDelegateCreationExpression(node, argument, methodOpt: null, isExtensionMethod: false, type: type); } // 4. A delegate type. else if (argument.Type.TypeKind == TypeKind.Delegate) { var sourceDelegate = (NamedTypeSymbol)argument.Type; MethodGroup methodGroup = MethodGroup.GetInstance(); try { if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, argument.Type, node: node)) { // We want failed "new" expression to use the constructors as their symbols. return new BoundBadExpression(node, LookupResultKind.NotInvocable, StaticCast<Symbol>.From(type.InstanceConstructors), ImmutableArray.Create(argument), type); } methodGroup.PopulateWithSingleMethod(argument, sourceDelegate.DelegateInvokeMethod); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conv = Conversions.MethodGroupConversion(argument.Syntax, methodGroup, type, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!conv.Exists) { var boundMethodGroup = new BoundMethodGroup( argument.Syntax, default, WellKnownMemberNames.DelegateInvokeName, ImmutableArray.Create(sourceDelegate.DelegateInvokeMethod), sourceDelegate.DelegateInvokeMethod, null, BoundMethodGroupFlags.None, argument, LookupResultKind.Viable); if (!Conversions.ReportDelegateOrFunctionPointerMethodGroupDiagnostics(this, boundMethodGroup, type, diagnostics)) { // If we could not produce a more specialized diagnostic, we report // No overload for '{0}' matches delegate '{1}' diagnostics.Add(ErrorCode.ERR_MethDelegateMismatch, node.Location, sourceDelegate.DelegateInvokeMethod, type); } } else { Debug.Assert(!conv.IsExtensionMethod); Debug.Assert(conv.IsValid); // i.e. if it exists, then it is valid. if (!this.MethodGroupConversionHasErrors(argument.Syntax, conv, argument, conv.IsExtensionMethod, isAddressOf: false, type, diagnostics)) { // we do not place the "Invoke" method in the node, indicating that it did not appear in source. return new BoundDelegateCreationExpression(node, argument, methodOpt: null, isExtensionMethod: false, type: type); } } } finally { methodGroup.Free(); } } // Not a valid delegate creation expression else { diagnostics.Add(ErrorCode.ERR_MethodNameExpected, argument.Syntax.Location); } // Note that we want failed "new" expression to use the constructors as their symbols. var childNodes = BuildArgumentsForErrorRecovery(analyzedArguments); return new BoundBadExpression(node, LookupResultKind.OverloadResolutionFailure, StaticCast<Symbol>.From(type.InstanceConstructors), childNodes, type); } private BoundExpression BindClassCreationExpression(ObjectCreationExpressionSyntax node, NamedTypeSymbol type, string typeName, BindingDiagnosticBag diagnostics, TypeSymbol initializerType = null) { // Get the bound arguments and the argument names. AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance(); try { // new C(__arglist()) is legal BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments, allowArglist: true); // No point in performing overload resolution if the type is static or a tuple literal. // Just return a bad expression containing the arguments. if (type.IsStatic) { diagnostics.Add(ErrorCode.ERR_InstantiatingStaticClass, node.Location, type); return MakeBadExpressionForObjectCreation(node, type, analyzedArguments, diagnostics); } else if (node.Type.Kind() == SyntaxKind.TupleType) { diagnostics.Add(ErrorCode.ERR_NewWithTupleTypeSyntax, node.Type.GetLocation()); return MakeBadExpressionForObjectCreation(node, type, analyzedArguments, diagnostics); } return BindClassCreationExpression(node, typeName, node.Type, type, analyzedArguments, diagnostics, node.Initializer, initializerType); } finally { analyzedArguments.Free(); } } #nullable enable /// <summary> /// Helper method to create a synthesized constructor invocation. /// </summary> private BoundExpression MakeConstructorInvocation( NamedTypeSymbol type, ArrayBuilder<BoundExpression> arguments, ArrayBuilder<RefKind> refKinds, SyntaxNode node, BindingDiagnosticBag diagnostics) { Debug.Assert(type.TypeKind is TypeKind.Class or TypeKind.Struct); var analyzedArguments = AnalyzedArguments.GetInstance(); try { analyzedArguments.Arguments.AddRange(arguments); analyzedArguments.RefKinds.AddRange(refKinds); if (type.IsStatic) { diagnostics.Add(ErrorCode.ERR_InstantiatingStaticClass, node.Location, type); return MakeBadExpressionForObjectCreation(node, type, analyzedArguments, initializerOpt: null, typeSyntax: null, diagnostics, wasCompilerGenerated: true); } var creation = BindClassCreationExpression(node, type.Name, node, type, analyzedArguments, diagnostics); creation.WasCompilerGenerated = true; return creation; } finally { analyzedArguments.Free(); } } internal BoundExpression BindObjectCreationForErrorRecovery(BoundUnconvertedObjectCreationExpression node, BindingDiagnosticBag diagnostics) { var arguments = AnalyzedArguments.GetInstance(node.Arguments, node.ArgumentRefKindsOpt, node.ArgumentNamesOpt); var result = MakeBadExpressionForObjectCreation(node.Syntax, CreateErrorType(), arguments, node.InitializerOpt, typeSyntax: node.Syntax, diagnostics); arguments.Free(); return result; } private BoundExpression MakeBadExpressionForObjectCreation(ObjectCreationExpressionSyntax node, TypeSymbol type, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics, bool wasCompilerGenerated = false) { return MakeBadExpressionForObjectCreation(node, type, analyzedArguments, node.Initializer, node.Type, diagnostics, wasCompilerGenerated); } /// <param name="typeSyntax">Shouldn't be null if <paramref name="initializerOpt"/> is not null.</param> private BoundExpression MakeBadExpressionForObjectCreation(SyntaxNode node, TypeSymbol type, AnalyzedArguments analyzedArguments, InitializerExpressionSyntax? initializerOpt, SyntaxNode? typeSyntax, BindingDiagnosticBag diagnostics, bool wasCompilerGenerated = false) { var children = ArrayBuilder<BoundExpression>.GetInstance(); children.AddRange(BuildArgumentsForErrorRecovery(analyzedArguments)); if (initializerOpt != null) { Debug.Assert(typeSyntax is not null); var boundInitializer = BindInitializerExpression(syntax: initializerOpt, type: type, typeSyntax: typeSyntax, isForNewInstance: true, diagnostics: diagnostics); children.Add(boundInitializer); } return new BoundBadExpression(node, LookupResultKind.NotCreatable, ImmutableArray.Create<Symbol?>(type), children.ToImmutableAndFree(), type) { WasCompilerGenerated = wasCompilerGenerated }; } #nullable disable private BoundObjectInitializerExpressionBase BindInitializerExpression( InitializerExpressionSyntax syntax, TypeSymbol type, SyntaxNode typeSyntax, bool isForNewInstance, BindingDiagnosticBag diagnostics) { Debug.Assert(syntax != null); Debug.Assert((object)type != null); var implicitReceiver = new BoundObjectOrCollectionValuePlaceholder(typeSyntax, isForNewInstance, type) { WasCompilerGenerated = true }; switch (syntax.Kind()) { case SyntaxKind.ObjectInitializerExpression: // Uses a special binder to produce customized diagnostics for the object initializer return BindObjectInitializerExpression( syntax, type, diagnostics, implicitReceiver, useObjectInitDiagnostics: true); case SyntaxKind.WithInitializerExpression: return BindObjectInitializerExpression( syntax, type, diagnostics, implicitReceiver, useObjectInitDiagnostics: false); case SyntaxKind.CollectionInitializerExpression: return BindCollectionInitializerExpression(syntax, type, diagnostics, implicitReceiver); default: throw ExceptionUtilities.Unreachable; } } private BoundExpression BindInitializerExpressionOrValue( ExpressionSyntax syntax, TypeSymbol type, SyntaxNode typeSyntax, BindingDiagnosticBag diagnostics) { Debug.Assert(syntax != null); Debug.Assert((object)type != null); switch (syntax.Kind()) { case SyntaxKind.ObjectInitializerExpression: case SyntaxKind.CollectionInitializerExpression: Debug.Assert(syntax.Parent.Parent.Kind() != SyntaxKind.WithInitializerExpression); return BindInitializerExpression((InitializerExpressionSyntax)syntax, type, typeSyntax, isForNewInstance: false, diagnostics); default: return BindValue(syntax, diagnostics, BindValueKind.RValue); } } private BoundObjectInitializerExpression BindObjectInitializerExpression( InitializerExpressionSyntax initializerSyntax, TypeSymbol initializerType, BindingDiagnosticBag diagnostics, BoundObjectOrCollectionValuePlaceholder implicitReceiver, bool useObjectInitDiagnostics) { // SPEC: 7.6.10.2 Object initializers // // SPEC: An object initializer consists of a sequence of member initializers, enclosed by { and } tokens and separated by commas. // SPEC: Each member initializer must name an accessible field or property of the object being initialized, followed by an equals sign and // SPEC: an expression or an object initializer or collection initializer. Debug.Assert(initializerSyntax.Kind() == SyntaxKind.ObjectInitializerExpression || initializerSyntax.Kind() == SyntaxKind.WithInitializerExpression); Debug.Assert((object)initializerType != null); // We use a location specific binder for binding object initializer field/property access to generate object initializer specific diagnostics: // 1) CS1914 (ERR_StaticMemberInObjectInitializer) // 2) CS1917 (ERR_ReadonlyValueTypeInObjectInitializer) // 3) CS1918 (ERR_ValueTypePropertyInObjectInitializer) // Note that this is only used for the LHS of the assignment - these diagnostics do not apply on the RHS. // For this reason, we will actually need two binders: this and this.WithAdditionalFlags. var objectInitializerMemberBinder = useObjectInitDiagnostics ? this.WithAdditionalFlags(BinderFlags.ObjectInitializerMember) : this; var initializers = ArrayBuilder<BoundExpression>.GetInstance(initializerSyntax.Expressions.Count); // Member name map to report duplicate assignments to a field/property. var memberNameMap = PooledHashSet<string>.GetInstance(); foreach (var memberInitializer in initializerSyntax.Expressions) { BoundExpression boundMemberInitializer = BindInitializerMemberAssignment( memberInitializer, initializerType, objectInitializerMemberBinder, diagnostics, implicitReceiver); initializers.Add(boundMemberInitializer); ReportDuplicateObjectMemberInitializers(boundMemberInitializer, memberNameMap, diagnostics); } return new BoundObjectInitializerExpression( initializerSyntax, implicitReceiver, initializers.ToImmutableAndFree(), initializerType); } private BoundExpression BindInitializerMemberAssignment( ExpressionSyntax memberInitializer, TypeSymbol initializerType, Binder objectInitializerMemberBinder, BindingDiagnosticBag diagnostics, BoundObjectOrCollectionValuePlaceholder implicitReceiver) { // SPEC: A member initializer that specifies an expression after the equals sign is processed in the same way as an assignment (spec 7.17.1) to the field or property. if (memberInitializer.Kind() == SyntaxKind.SimpleAssignmentExpression) { var initializer = (AssignmentExpressionSyntax)memberInitializer; // Bind member initializer identifier, i.e. left part of assignment BoundExpression boundLeft = null; var leftSyntax = initializer.Left; if (initializerType.IsDynamic() && leftSyntax.Kind() == SyntaxKind.IdentifierName) { { // D = { ..., <identifier> = <expr>, ... }, where D : dynamic var memberName = ((IdentifierNameSyntax)leftSyntax).Identifier.Text; boundLeft = new BoundDynamicObjectInitializerMember(leftSyntax, memberName, implicitReceiver.Type, initializerType, hasErrors: false); } } else { // We use a location specific binder for binding object initializer field/property access to generate object initializer specific diagnostics: // 1) CS1914 (ERR_StaticMemberInObjectInitializer) // 2) CS1917 (ERR_ReadonlyValueTypeInObjectInitializer) // 3) CS1918 (ERR_ValueTypePropertyInObjectInitializer) // See comments in BindObjectInitializerExpression for more details. Debug.Assert(objectInitializerMemberBinder != null); boundLeft = objectInitializerMemberBinder.BindObjectInitializerMember(initializer, implicitReceiver, diagnostics); } if (boundLeft != null) { Debug.Assert((object)boundLeft.Type != null); // Bind member initializer value, i.e. right part of assignment BoundExpression boundRight = BindInitializerExpressionOrValue( syntax: initializer.Right, type: boundLeft.Type, typeSyntax: boundLeft.Syntax, diagnostics: diagnostics); // Bind member initializer assignment expression return BindAssignment(initializer, boundLeft, boundRight, isRef: false, diagnostics); } } var boundExpression = BindValue(memberInitializer, diagnostics, BindValueKind.RValue); Error(diagnostics, ErrorCode.ERR_InvalidInitializerElementInitializer, memberInitializer); return ToBadExpression(boundExpression, LookupResultKind.NotAValue); } // returns BadBoundExpression or BoundObjectInitializerMember private BoundExpression BindObjectInitializerMember( AssignmentExpressionSyntax namedAssignment, BoundObjectOrCollectionValuePlaceholder implicitReceiver, BindingDiagnosticBag diagnostics) { BoundExpression boundMember; LookupResultKind resultKind; bool hasErrors; if (namedAssignment.Left.Kind() == SyntaxKind.IdentifierName) { var memberName = (IdentifierNameSyntax)namedAssignment.Left; // SPEC: Each member initializer must name an accessible field or property of the object being initialized, followed by an equals sign and // SPEC: an expression or an object initializer or collection initializer. // SPEC: A member initializer that specifies an expression after the equals sign is processed in the same way as an assignment (7.17.1) to the field or property. // SPEC VIOLATION: Native compiler also allows initialization of field-like events in object initializers, so we allow it as well. boundMember = BindInstanceMemberAccess( node: memberName, right: memberName, boundLeft: implicitReceiver, rightName: memberName.Identifier.ValueText, rightArity: 0, typeArgumentsSyntax: default(SeparatedSyntaxList<TypeSyntax>), typeArgumentsWithAnnotations: default(ImmutableArray<TypeWithAnnotations>), invoked: false, indexed: false, diagnostics: diagnostics); resultKind = boundMember.ResultKind; hasErrors = boundMember.HasAnyErrors || implicitReceiver.HasAnyErrors; if (boundMember.Kind == BoundKind.PropertyGroup) { boundMember = BindIndexedPropertyAccess((BoundPropertyGroup)boundMember, mustHaveAllOptionalParameters: true, diagnostics: diagnostics); if (boundMember.HasAnyErrors) { hasErrors = true; } } } else if (namedAssignment.Left.Kind() == SyntaxKind.ImplicitElementAccess) { var implicitIndexing = (ImplicitElementAccessSyntax)namedAssignment.Left; boundMember = BindElementAccess(implicitIndexing, implicitReceiver, implicitIndexing.ArgumentList, diagnostics); resultKind = boundMember.ResultKind; hasErrors = boundMember.HasAnyErrors || implicitReceiver.HasAnyErrors; } else { return null; } // SPEC: A member initializer that specifies an object initializer after the equals sign is a nested object initializer, // SPEC: i.e. an initialization of an embedded object. Instead of assigning a new value to the field or property, // SPEC: the assignments in the nested object initializer are treated as assignments to members of the field or property. // SPEC: Nested object initializers cannot be applied to properties with a value type, or to read-only fields with a value type. // NOTE: The dev11 behavior does not match the spec that was current at the time (quoted above). However, in the roslyn // NOTE: timeframe, the spec will be updated to apply the same restriction to nested collection initializers. Therefore, // NOTE: roslyn will implement the dev11 behavior and it will be spec-compliant. // NOTE: In the roslyn timeframe, an additional restriction will (likely) be added to the spec - it is not sufficient for the // NOTE: type of the member to not be a value type - it must actually be a reference type (i.e. unconstrained type parameters // NOTE: should be prohibited). To avoid breaking existing code, roslyn will not implement this new spec clause. // TODO: If/when we have a way to version warnings, we should add a warning for this. BoundKind boundMemberKind = boundMember.Kind; SyntaxKind rhsKind = namedAssignment.Right.Kind(); bool isRhsNestedInitializer = rhsKind == SyntaxKind.ObjectInitializerExpression || rhsKind == SyntaxKind.CollectionInitializerExpression; BindValueKind valueKind = isRhsNestedInitializer ? BindValueKind.RValue : BindValueKind.Assignable; ImmutableArray<BoundExpression> arguments = ImmutableArray<BoundExpression>.Empty; ImmutableArray<string> argumentNamesOpt = default(ImmutableArray<string>); ImmutableArray<int> argsToParamsOpt = default(ImmutableArray<int>); ImmutableArray<RefKind> argumentRefKindsOpt = default(ImmutableArray<RefKind>); BitVector defaultArguments = default(BitVector); bool expanded = false; switch (boundMemberKind) { case BoundKind.FieldAccess: { var fieldSymbol = ((BoundFieldAccess)boundMember).FieldSymbol; if (isRhsNestedInitializer && fieldSymbol.IsReadOnly && fieldSymbol.Type.IsValueType) { if (!hasErrors) { // TODO: distinct error code for collection initializers? (Dev11 doesn't have one.) Error(diagnostics, ErrorCode.ERR_ReadonlyValueTypeInObjectInitializer, namedAssignment.Left, fieldSymbol, fieldSymbol.Type); hasErrors = true; } resultKind = LookupResultKind.NotAValue; } break; } case BoundKind.EventAccess: break; case BoundKind.PropertyAccess: hasErrors |= isRhsNestedInitializer && !CheckNestedObjectInitializerPropertySymbol(((BoundPropertyAccess)boundMember).PropertySymbol, namedAssignment.Left, diagnostics, hasErrors, ref resultKind); break; case BoundKind.IndexerAccess: { var indexer = BindIndexerDefaultArguments((BoundIndexerAccess)boundMember, valueKind, diagnostics); boundMember = indexer; hasErrors |= isRhsNestedInitializer && !CheckNestedObjectInitializerPropertySymbol(indexer.Indexer, namedAssignment.Left, diagnostics, hasErrors, ref resultKind); arguments = indexer.Arguments; argumentNamesOpt = indexer.ArgumentNamesOpt; argsToParamsOpt = indexer.ArgsToParamsOpt; argumentRefKindsOpt = indexer.ArgumentRefKindsOpt; defaultArguments = indexer.DefaultArguments; expanded = indexer.Expanded; break; } case BoundKind.DynamicIndexerAccess: { var indexer = (BoundDynamicIndexerAccess)boundMember; arguments = indexer.Arguments; argumentNamesOpt = indexer.ArgumentNamesOpt; argumentRefKindsOpt = indexer.ArgumentRefKindsOpt; } break; case BoundKind.ArrayAccess: case BoundKind.PointerElementAccess: return boundMember; default: return BadObjectInitializerMemberAccess(boundMember, implicitReceiver, namedAssignment.Left, diagnostics, valueKind, hasErrors); } if (!hasErrors) { // CheckValueKind to generate possible diagnostics for invalid initializers non-viable member lookup result: // 1) CS0154 (ERR_PropertyLacksGet) // 2) CS0200 (ERR_AssgReadonlyProp) if (!CheckValueKind(boundMember.Syntax, boundMember, valueKind, checkingReceiver: false, diagnostics: diagnostics)) { hasErrors = true; resultKind = isRhsNestedInitializer ? LookupResultKind.NotAValue : LookupResultKind.NotAVariable; } } return new BoundObjectInitializerMember( namedAssignment.Left, boundMember.ExpressionSymbol, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, resultKind, implicitReceiver.Type, type: boundMember.Type, hasErrors: hasErrors); } private static bool CheckNestedObjectInitializerPropertySymbol( PropertySymbol propertySymbol, ExpressionSyntax memberNameSyntax, BindingDiagnosticBag diagnostics, bool suppressErrors, ref LookupResultKind resultKind) { bool hasErrors = false; if (propertySymbol.Type.IsValueType) { if (!suppressErrors) { // TODO: distinct error code for collection initializers? (Dev11 doesn't have one.) Error(diagnostics, ErrorCode.ERR_ValueTypePropertyInObjectInitializer, memberNameSyntax, propertySymbol, propertySymbol.Type); hasErrors = true; } resultKind = LookupResultKind.NotAValue; } return !hasErrors; } private BoundExpression BadObjectInitializerMemberAccess( BoundExpression boundMember, BoundObjectOrCollectionValuePlaceholder implicitReceiver, ExpressionSyntax memberNameSyntax, BindingDiagnosticBag diagnostics, BindValueKind valueKind, bool suppressErrors) { if (!suppressErrors) { string member; var identName = memberNameSyntax as IdentifierNameSyntax; if (identName != null) { member = identName.Identifier.ValueText; } else { member = memberNameSyntax.ToString(); } switch (boundMember.ResultKind) { case LookupResultKind.Empty: Error(diagnostics, ErrorCode.ERR_NoSuchMember, memberNameSyntax, implicitReceiver.Type, member); break; case LookupResultKind.Inaccessible: boundMember = CheckValue(boundMember, valueKind, diagnostics); Debug.Assert(boundMember.HasAnyErrors); break; default: Error(diagnostics, ErrorCode.ERR_MemberCannotBeInitialized, memberNameSyntax, member); break; } } return ToBadExpression(boundMember, (valueKind == BindValueKind.RValue) ? LookupResultKind.NotAValue : LookupResultKind.NotAVariable); } private static void ReportDuplicateObjectMemberInitializers(BoundExpression boundMemberInitializer, HashSet<string> memberNameMap, BindingDiagnosticBag diagnostics) { Debug.Assert(memberNameMap != null); // SPEC: It is an error for an object initializer to include more than one member initializer for the same field or property. if (!boundMemberInitializer.HasAnyErrors) { // SPEC: A member initializer that specifies an expression after the equals sign is processed in the same way as an assignment (7.17.1) to the field or property. var memberInitializerSyntax = boundMemberInitializer.Syntax; Debug.Assert(memberInitializerSyntax.Kind() == SyntaxKind.SimpleAssignmentExpression); var namedAssignment = (AssignmentExpressionSyntax)memberInitializerSyntax; var memberNameSyntax = namedAssignment.Left as IdentifierNameSyntax; if (memberNameSyntax != null) { var memberName = memberNameSyntax.Identifier.ValueText; if (!memberNameMap.Add(memberName)) { Error(diagnostics, ErrorCode.ERR_MemberAlreadyInitialized, memberNameSyntax, memberName); } } } } private BoundCollectionInitializerExpression BindCollectionInitializerExpression( InitializerExpressionSyntax initializerSyntax, TypeSymbol initializerType, BindingDiagnosticBag diagnostics, BoundObjectOrCollectionValuePlaceholder implicitReceiver) { // SPEC: 7.6.10.3 Collection initializers // // SPEC: A collection initializer consists of a sequence of element initializers, enclosed by { and } tokens and separated by commas. // SPEC: The following is an example of an object creation expression that includes a collection initializer: // SPEC: List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // SPEC: The collection object to which a collection initializer is applied must be of a type that implements System.Collections.IEnumerable or // SPEC: a compile-time error occurs. For each specified element in order, the collection initializer invokes an Add method on the target object // SPEC: with the expression list of the element initializer as argument list, applying normal overload resolution for each invocation. // SPEC: Thus, the collection object must contain an applicable Add method for each element initializer. Debug.Assert(initializerSyntax.Kind() == SyntaxKind.CollectionInitializerExpression); Debug.Assert(initializerSyntax.Expressions.Any()); Debug.Assert((object)initializerType != null); var initializerBuilder = ArrayBuilder<BoundExpression>.GetInstance(); // SPEC: The collection object to which a collection initializer is applied must be of a type that implements System.Collections.IEnumerable or // SPEC: a compile-time error occurs. bool hasEnumerableInitializerType = CollectionInitializerTypeImplementsIEnumerable(initializerType, initializerSyntax, diagnostics); if (!hasEnumerableInitializerType && !initializerSyntax.HasErrors && !initializerType.IsErrorType()) { Error(diagnostics, ErrorCode.ERR_CollectionInitRequiresIEnumerable, initializerSyntax, initializerType); } // We use a location specific binder for binding collection initializer Add method to generate specific overload resolution diagnostics: // 1) CS1921 (ERR_InitializerAddHasWrongSignature) // 2) CS1950 (ERR_BadArgTypesForCollectionAdd) // 3) CS1954 (ERR_InitializerAddHasParamModifiers) var collectionInitializerAddMethodBinder = this.WithAdditionalFlags(BinderFlags.CollectionInitializerAddMethod); foreach (var elementInitializer in initializerSyntax.Expressions) { // NOTE: collectionInitializerAddMethodBinder is used only for binding the Add method invocation expression, but not the entire initializer. // NOTE: Hence it is being passed as a parameter to BindCollectionInitializerElement(). // NOTE: Ideally we would want to avoid this and bind the entire initializer with the collectionInitializerAddMethodBinder. // NOTE: However, this approach has few issues. These issues also occur when binding object initializer member assignment. // NOTE: See comments for objectInitializerMemberBinder in BindObjectInitializerExpression method for details about the pitfalls of alternate approaches. BoundExpression boundElementInitializer = BindCollectionInitializerElement(elementInitializer, initializerType, hasEnumerableInitializerType, collectionInitializerAddMethodBinder, diagnostics, implicitReceiver); initializerBuilder.Add(boundElementInitializer); } return new BoundCollectionInitializerExpression(initializerSyntax, implicitReceiver, initializerBuilder.ToImmutableAndFree(), initializerType); } private bool CollectionInitializerTypeImplementsIEnumerable(TypeSymbol initializerType, CSharpSyntaxNode node, BindingDiagnosticBag diagnostics) { // SPEC: The collection object to which a collection initializer is applied must be of a type that implements System.Collections.IEnumerable or // SPEC: a compile-time error occurs. if (initializerType.IsDynamic()) { // We cannot determine at compile time if initializerType implements System.Collections.IEnumerable, we must assume that it does. return true; } else if (!initializerType.IsErrorType()) { TypeSymbol collectionsIEnumerableType = this.GetSpecialType(SpecialType.System_Collections_IEnumerable, diagnostics, node); // NOTE: Ideally, to check if the initializer type implements System.Collections.IEnumerable we can walk through // NOTE: its implemented interfaces. However the native compiler checks to see if there is conversion from initializer // NOTE: type to the predefined System.Collections.IEnumerable type, so we do the same. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var result = Conversions.ClassifyImplicitConversionFromType(initializerType, collectionsIEnumerableType, ref useSiteInfo).IsValid; diagnostics.Add(node, useSiteInfo); return result; } else { return false; } } private BoundExpression BindCollectionInitializerElement( ExpressionSyntax elementInitializer, TypeSymbol initializerType, bool hasEnumerableInitializerType, Binder collectionInitializerAddMethodBinder, BindingDiagnosticBag diagnostics, BoundObjectOrCollectionValuePlaceholder implicitReceiver) { // SPEC: Each element initializer specifies an element to be added to the collection object being initialized, and consists of // SPEC: a list of expressions enclosed by { and } tokens and separated by commas. // SPEC: A single-expression element initializer can be written without braces, but cannot then be an assignment expression, // SPEC: to avoid ambiguity with member initializers. The non-assignment-expression production is defined in 7.18. if (elementInitializer.Kind() == SyntaxKind.ComplexElementInitializerExpression) { return BindComplexElementInitializerExpression( (InitializerExpressionSyntax)elementInitializer, diagnostics, hasEnumerableInitializerType, collectionInitializerAddMethodBinder, implicitReceiver); } else { // Must be a non-assignment expression. if (SyntaxFacts.IsAssignmentExpression(elementInitializer.Kind())) { Error(diagnostics, ErrorCode.ERR_InvalidInitializerElementInitializer, elementInitializer); } var boundElementInitializer = BindInitializerExpressionOrValue(elementInitializer, initializerType, implicitReceiver.Syntax, diagnostics); BoundExpression result = BindCollectionInitializerElementAddMethod( elementInitializer, ImmutableArray.Create(boundElementInitializer), hasEnumerableInitializerType, collectionInitializerAddMethodBinder, diagnostics, implicitReceiver); result.WasCompilerGenerated = true; return result; } } private BoundExpression BindComplexElementInitializerExpression( InitializerExpressionSyntax elementInitializer, BindingDiagnosticBag diagnostics, bool hasEnumerableInitializerType, Binder collectionInitializerAddMethodBinder = null, BoundObjectOrCollectionValuePlaceholder implicitReceiver = null) { var elementInitializerExpressions = elementInitializer.Expressions; if (elementInitializerExpressions.Any()) { var exprBuilder = ArrayBuilder<BoundExpression>.GetInstance(); foreach (var childElementInitializer in elementInitializerExpressions) { exprBuilder.Add(BindValue(childElementInitializer, diagnostics, BindValueKind.RValue)); } return BindCollectionInitializerElementAddMethod( elementInitializer, exprBuilder.ToImmutableAndFree(), hasEnumerableInitializerType, collectionInitializerAddMethodBinder, diagnostics, implicitReceiver); } else { Error(diagnostics, ErrorCode.ERR_EmptyElementInitializer, elementInitializer); return BadExpression(elementInitializer, LookupResultKind.NotInvocable); } } private BoundExpression BindUnexpectedComplexElementInitializer(InitializerExpressionSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node.Kind() == SyntaxKind.ComplexElementInitializerExpression); return BindComplexElementInitializerExpression(node, diagnostics, hasEnumerableInitializerType: false); } private BoundExpression BindCollectionInitializerElementAddMethod( ExpressionSyntax elementInitializer, ImmutableArray<BoundExpression> boundElementInitializerExpressions, bool hasEnumerableInitializerType, Binder collectionInitializerAddMethodBinder, BindingDiagnosticBag diagnostics, BoundObjectOrCollectionValuePlaceholder implicitReceiver) { // SPEC: For each specified element in order, the collection initializer invokes an Add method on the target object // SPEC: with the expression list of the element initializer as argument list, applying normal overload resolution for each invocation. // SPEC: Thus, the collection object must contain an applicable Add method for each element initializer. // We use a location specific binder for binding collection initializer Add method to generate specific overload resolution diagnostics. // 1) CS1921 (ERR_InitializerAddHasWrongSignature) // 2) CS1950 (ERR_BadArgTypesForCollectionAdd) // 3) CS1954 (ERR_InitializerAddHasParamModifiers) // See comments in BindCollectionInitializerExpression for more details. Debug.Assert(!boundElementInitializerExpressions.IsEmpty); if (!hasEnumerableInitializerType) { return BadExpression(elementInitializer, LookupResultKind.NotInvocable, ImmutableArray<Symbol>.Empty, boundElementInitializerExpressions); } Debug.Assert(collectionInitializerAddMethodBinder != null); Debug.Assert(collectionInitializerAddMethodBinder.Flags.Includes(BinderFlags.CollectionInitializerAddMethod)); Debug.Assert(implicitReceiver != null); Debug.Assert((object)implicitReceiver.Type != null); if (implicitReceiver.Type.IsDynamic()) { var hasErrors = ReportBadDynamicArguments(elementInitializer, boundElementInitializerExpressions, refKinds: default, diagnostics, queryClause: null); return new BoundDynamicCollectionElementInitializer( elementInitializer, applicableMethods: ImmutableArray<MethodSymbol>.Empty, implicitReceiver, arguments: boundElementInitializerExpressions.SelectAsArray(e => BindToNaturalType(e, diagnostics)), type: GetSpecialType(SpecialType.System_Void, diagnostics, elementInitializer), hasErrors: hasErrors); } // Receiver is early bound, find method Add and invoke it (may still be a dynamic invocation): var addMethodInvocation = collectionInitializerAddMethodBinder.MakeInvocationExpression( elementInitializer, implicitReceiver, methodName: WellKnownMemberNames.CollectionInitializerAddMethodName, args: boundElementInitializerExpressions, diagnostics: diagnostics); if (addMethodInvocation.Kind == BoundKind.DynamicInvocation) { var dynamicInvocation = (BoundDynamicInvocation)addMethodInvocation; return new BoundDynamicCollectionElementInitializer( elementInitializer, dynamicInvocation.ApplicableMethods, implicitReceiver, dynamicInvocation.Arguments, dynamicInvocation.Type, hasErrors: dynamicInvocation.HasAnyErrors); } else if (addMethodInvocation.Kind == BoundKind.Call) { var boundCall = (BoundCall)addMethodInvocation; // Either overload resolution succeeded for this call or it did not. If it // did not succeed then we've stashed the original method symbols from the // method group, and we should use those as the symbols displayed for the // call. If it did succeed then we did not stash any symbols. if (boundCall.HasErrors && !boundCall.OriginalMethodsOpt.IsDefault) { return boundCall; } return new BoundCollectionElementInitializer( elementInitializer, boundCall.Method, boundCall.Arguments, boundCall.ReceiverOpt, boundCall.Expanded, boundCall.ArgsToParamsOpt, boundCall.DefaultArguments, boundCall.InvokedAsExtensionMethod, boundCall.ResultKind, boundCall.Type, boundCall.HasAnyErrors) { WasCompilerGenerated = true }; } else { Debug.Assert(addMethodInvocation.Kind == BoundKind.BadExpression); return addMethodInvocation; } } internal ImmutableArray<MethodSymbol> FilterInaccessibleConstructors(ImmutableArray<MethodSymbol> constructors, bool allowProtectedConstructorsOfBaseType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { ArrayBuilder<MethodSymbol> builder = null; for (int i = 0; i < constructors.Length; i++) { MethodSymbol constructor = constructors[i]; if (!IsConstructorAccessible(constructor, ref useSiteInfo, allowProtectedConstructorsOfBaseType)) { if (builder == null) { builder = ArrayBuilder<MethodSymbol>.GetInstance(); builder.AddRange(constructors, i); } } else { builder?.Add(constructor); } } return builder == null ? constructors : builder.ToImmutableAndFree(); } private bool IsConstructorAccessible(MethodSymbol constructor, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool allowProtectedConstructorsOfBaseType = false) { Debug.Assert((object)constructor != null); Debug.Assert(constructor.MethodKind == MethodKind.Constructor || constructor.MethodKind == MethodKind.StaticConstructor); NamedTypeSymbol containingType = this.ContainingType; if ((object)containingType != null) { // SPEC VIOLATION: The specification implies that when considering // SPEC VIOLATION: instance methods or instance constructors, we first // SPEC VIOLATION: do overload resolution on the accessible members, and // SPEC VIOLATION: then if the best method chosen is protected and accessed // SPEC VIOLATION: through the wrong type, then an error occurs. The native // SPEC VIOLATION: compiler however does it in the opposite order. First it // SPEC VIOLATION: filters out the protected methods that cannot be called // SPEC VIOLATION: through the given type, and then it does overload resolution // SPEC VIOLATION: on the rest. // // That said, it is somewhat odd that the same rule applies to constructors // as instance methods. A protected constructor is never going to be called // via an instance of a *more derived but different class* the way a // virtual method might be. Nevertheless, that's what we do. // // A constructor is accessed through an instance of the type being constructed: return allowProtectedConstructorsOfBaseType ? this.IsAccessible(constructor, ref useSiteInfo, null) : this.IsSymbolAccessibleConditional(constructor, containingType, ref useSiteInfo, constructor.ContainingType); } else { Debug.Assert((object)this.Compilation.Assembly != null); return IsSymbolAccessibleConditional(constructor, this.Compilation.Assembly, ref useSiteInfo); } } protected BoundExpression BindClassCreationExpression( SyntaxNode node, string typeName, SyntaxNode typeNode, NamedTypeSymbol type, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics, InitializerExpressionSyntax initializerSyntaxOpt = null, TypeSymbol initializerTypeOpt = null, bool wasTargetTyped = false) { BoundExpression result = null; bool hasErrors = type.IsErrorType(); if (type.IsAbstract) { // Report error for new of abstract type. diagnostics.Add(ErrorCode.ERR_NoNewAbstract, node.Location, type); hasErrors = true; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); BoundObjectInitializerExpressionBase boundInitializerOpt = null; // If we have a dynamic argument then do overload resolution to see if there are one or more // applicable candidates. If there are, then this is a dynamic object creation; we'll work out // which ctor to call at runtime. If we have a dynamic argument but no applicable candidates // then we do the analysis again for error reporting purposes. if (analyzedArguments.HasDynamicArgument) { OverloadResolutionResult<MethodSymbol> overloadResolutionResult = OverloadResolutionResult<MethodSymbol>.GetInstance(); this.OverloadResolution.ObjectCreationOverloadResolution(GetAccessibleConstructorsForOverloadResolution(type, ref useSiteInfo), analyzedArguments, overloadResolutionResult, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(useSiteInfo); if (overloadResolutionResult.HasAnyApplicableMember) { var argArray = BuildArgumentsForDynamicInvocation(analyzedArguments, diagnostics); var refKindsArray = analyzedArguments.RefKinds.ToImmutableOrNull(); hasErrors &= ReportBadDynamicArguments(node, argArray, refKindsArray, diagnostics, queryClause: null); boundInitializerOpt = makeBoundInitializerOpt(); result = new BoundDynamicObjectCreationExpression( node, typeName, argArray, analyzedArguments.GetNames(), refKindsArray, boundInitializerOpt, overloadResolutionResult.GetAllApplicableMembers(), type, hasErrors); } overloadResolutionResult.Free(); if (result != null) { return result; } } if (TryPerformConstructorOverloadResolution( type, analyzedArguments, typeName, typeNode.Location, hasErrors, //don't cascade in these cases diagnostics, out MemberResolutionResult<MethodSymbol> memberResolutionResult, out ImmutableArray<MethodSymbol> candidateConstructors, allowProtectedConstructorsOfBaseType: false)) { var method = memberResolutionResult.Member; bool hasError = false; // What if some of the arguments are implicit? Dev10 reports unsafe errors // if the implied argument would have an unsafe type. We need to check // the parameters explicitly, since there won't be bound nodes for the implied // arguments until lowering. if (method.HasUnsafeParameter()) { // Don't worry about double reporting (i.e. for both the argument and the parameter) // because only one unsafe diagnostic is allowed per scope - the others are suppressed. hasError = ReportUnsafeIfNotAllowed(node, diagnostics) || hasError; } ReportDiagnosticsIfObsolete(diagnostics, method, node, hasBaseReceiver: false); // NOTE: Use-site diagnostics were reported during overload resolution. ConstantValue constantValueOpt = (initializerSyntaxOpt == null && method.IsDefaultValueTypeConstructor(requireZeroInit: true)) ? FoldParameterlessValueTypeConstructor(type) : null; var expanded = memberResolutionResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm; var argToParams = memberResolutionResult.Result.ArgsToParamsOpt; BindDefaultArguments(node, method.Parameters, analyzedArguments.Arguments, analyzedArguments.RefKinds, ref argToParams, out var defaultArguments, expanded, enableCallerInfo: true, diagnostics); var arguments = analyzedArguments.Arguments.ToImmutable(); var refKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); if (!hasError) { hasError = !CheckInvocationArgMixing( node, method, null, method.Parameters, arguments, argToParams, this.LocalScopeDepth, diagnostics); } boundInitializerOpt = makeBoundInitializerOpt(); result = new BoundObjectCreationExpression( node, method, candidateConstructors, arguments, analyzedArguments.GetNames(), refKinds, expanded, argToParams, defaultArguments, constantValueOpt, boundInitializerOpt, wasTargetTyped, type, hasError); // CONSIDER: Add ResultKind field to BoundObjectCreationExpression to avoid wrapping result with BoundBadExpression. if (type.IsAbstract) { result = BadExpression(node, LookupResultKind.NotCreatable, result); } return result; } LookupResultKind resultKind; if (type.IsAbstract) { resultKind = LookupResultKind.NotCreatable; } else if (memberResolutionResult.IsValid && !IsConstructorAccessible(memberResolutionResult.Member, ref useSiteInfo)) { resultKind = LookupResultKind.Inaccessible; } else { resultKind = LookupResultKind.OverloadResolutionFailure; } diagnostics.Add(node, useSiteInfo); ArrayBuilder<Symbol> symbols = ArrayBuilder<Symbol>.GetInstance(); symbols.AddRange(candidateConstructors); // NOTE: The use site diagnostics of the candidate constructors have already been reported (in PerformConstructorOverloadResolution). var childNodes = ArrayBuilder<BoundExpression>.GetInstance(); childNodes.AddRange(BuildArgumentsForErrorRecovery(analyzedArguments, candidateConstructors)); if (initializerSyntaxOpt != null) { childNodes.Add(boundInitializerOpt ?? makeBoundInitializerOpt()); } return new BoundBadExpression(node, resultKind, symbols.ToImmutableAndFree(), childNodes.ToImmutableAndFree(), type); BoundObjectInitializerExpressionBase makeBoundInitializerOpt() { if (initializerSyntaxOpt != null) { return BindInitializerExpression(syntax: initializerSyntaxOpt, type: initializerTypeOpt ?? type, typeSyntax: typeNode, isForNewInstance: true, diagnostics: diagnostics); } return null; } } private BoundExpression BindInterfaceCreationExpression(ObjectCreationExpressionSyntax node, NamedTypeSymbol type, BindingDiagnosticBag diagnostics) { AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance(); BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments); var result = BindInterfaceCreationExpression(node, type, diagnostics, node.Type, analyzedArguments, node.Initializer, wasTargetTyped: false); analyzedArguments.Free(); return result; } private BoundExpression BindInterfaceCreationExpression(SyntaxNode node, NamedTypeSymbol type, BindingDiagnosticBag diagnostics, SyntaxNode typeNode, AnalyzedArguments analyzedArguments, InitializerExpressionSyntax initializerOpt, bool wasTargetTyped) { Debug.Assert((object)type != null); // COM interfaces which have ComImportAttribute and CoClassAttribute can be instantiated with "new". // CoClassAttribute contains the type information of the original CoClass for the interface. // We replace the interface creation with CoClass object creation for this case. // NOTE: We don't attempt binding interface creation to CoClass creation if we are within an attribute argument. // NOTE: This is done to prevent a cycle in an error scenario where we have a "new InterfaceType" expression in an attribute argument. // NOTE: Accessing IsComImport/ComImportCoClass properties on given type symbol would attempt ForceCompeteAttributes, which would again try binding all attributes on the symbol. // NOTE: causing infinite recursion. We avoid this cycle by checking if we are within in context of an Attribute argument. if (!this.InAttributeArgument && type.IsComImport) { NamedTypeSymbol coClassType = type.ComImportCoClass; if ((object)coClassType != null) { return BindComImportCoClassCreationExpression(node, type, coClassType, diagnostics, typeNode, analyzedArguments, initializerOpt, wasTargetTyped); } } // interfaces can't be instantiated in C# diagnostics.Add(ErrorCode.ERR_NoNewAbstract, node.Location, type); return MakeBadExpressionForObjectCreation(node, type, analyzedArguments, initializerOpt, typeNode, diagnostics); } private BoundExpression BindComImportCoClassCreationExpression(SyntaxNode node, NamedTypeSymbol interfaceType, NamedTypeSymbol coClassType, BindingDiagnosticBag diagnostics, SyntaxNode typeNode, AnalyzedArguments analyzedArguments, InitializerExpressionSyntax initializerOpt, bool wasTargetTyped) { Debug.Assert((object)interfaceType != null); Debug.Assert(interfaceType.IsInterfaceType()); Debug.Assert((object)coClassType != null); Debug.Assert(TypeSymbol.Equals(interfaceType.ComImportCoClass, coClassType, TypeCompareKind.ConsiderEverything2)); Debug.Assert(coClassType.TypeKind == TypeKind.Class || coClassType.TypeKind == TypeKind.Error); if (coClassType.IsErrorType()) { Error(diagnostics, ErrorCode.ERR_MissingCoClass, node, coClassType, interfaceType); } else if (coClassType.IsUnboundGenericType) { // BREAKING CHANGE: Dev10 allows the following code to compile, even though the output assembly is not verifiable and generates a runtime exception: // // [ComImport, Guid("00020810-0000-0000-C000-000000000046")] // [CoClass(typeof(GenericClass<>))] // public interface InterfaceType {} // public class GenericClass<T>: InterfaceType {} // // public class Program // { // public static void Main() { var i = new InterfaceType(); } // } // // We disallow CoClass creation if coClassType is an unbound generic type and report a compile time error. Error(diagnostics, ErrorCode.ERR_BadCoClassSig, node, coClassType, interfaceType); } else { // NoPIA support if (interfaceType.ContainingAssembly.IsLinked) { return BindNoPiaObjectCreationExpression(node, interfaceType, coClassType, diagnostics, typeNode, analyzedArguments, initializerOpt); } var classCreation = BindClassCreationExpression( node, coClassType.Name, typeNode, coClassType, analyzedArguments, diagnostics, initializerOpt, interfaceType, wasTargetTyped); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = this.Conversions.ClassifyConversionFromExpression(classCreation, interfaceType, ref useSiteInfo, forCast: true); diagnostics.Add(node, useSiteInfo); if (!conversion.IsValid) { SymbolDistinguisher distinguisher = new SymbolDistinguisher(this.Compilation, coClassType, interfaceType); Error(diagnostics, ErrorCode.ERR_NoExplicitConv, node, distinguisher.First, distinguisher.Second); } // Bind the conversion, but drop the conversion node. CreateConversion(classCreation, conversion, interfaceType, diagnostics); // Override result type to be the interface type. switch (classCreation.Kind) { case BoundKind.ObjectCreationExpression: var creation = (BoundObjectCreationExpression)classCreation; return creation.Update(creation.Constructor, creation.ConstructorsGroup, creation.Arguments, creation.ArgumentNamesOpt, creation.ArgumentRefKindsOpt, creation.Expanded, creation.ArgsToParamsOpt, creation.DefaultArguments, creation.ConstantValueOpt, creation.InitializerExpressionOpt, interfaceType); case BoundKind.BadExpression: var bad = (BoundBadExpression)classCreation; return bad.Update(bad.ResultKind, bad.Symbols, bad.ChildBoundNodes, interfaceType); default: throw ExceptionUtilities.UnexpectedValue(classCreation.Kind); } } return MakeBadExpressionForObjectCreation(node, interfaceType, analyzedArguments, initializerOpt, typeNode, diagnostics); } private BoundExpression BindNoPiaObjectCreationExpression( SyntaxNode node, NamedTypeSymbol interfaceType, NamedTypeSymbol coClassType, BindingDiagnosticBag diagnostics, SyntaxNode typeNode, AnalyzedArguments analyzedArguments, InitializerExpressionSyntax initializerOpt) { string guidString; if (!coClassType.GetGuidString(out guidString)) { // At this point, VB reports ERRID_NoPIAAttributeMissing2 if guid isn't there. // C# doesn't complain and instead uses zero guid. guidString = System.Guid.Empty.ToString("D"); } var boundInitializerOpt = initializerOpt == null ? null : BindInitializerExpression(syntax: initializerOpt, type: interfaceType, typeSyntax: typeNode, isForNewInstance: true, diagnostics: diagnostics); var creation = new BoundNoPiaObjectCreationExpression(node, guidString, boundInitializerOpt, interfaceType); if (analyzedArguments.Arguments.Count > 0) { diagnostics.Add(ErrorCode.ERR_BadCtorArgCount, typeNode.Location, interfaceType, analyzedArguments.Arguments.Count); var children = BuildArgumentsForErrorRecovery(analyzedArguments).Add(creation); return new BoundBadExpression(node, LookupResultKind.OverloadResolutionFailure, ImmutableArray<Symbol>.Empty, children, creation.Type); } return creation; } private BoundExpression BindTypeParameterCreationExpression(ObjectCreationExpressionSyntax node, TypeParameterSymbol typeParameter, BindingDiagnosticBag diagnostics) { AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance(); BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments); var result = BindTypeParameterCreationExpression(node, typeParameter, analyzedArguments, node.Initializer, node.Type, diagnostics); analyzedArguments.Free(); return result; } private BoundExpression BindTypeParameterCreationExpression(SyntaxNode node, TypeParameterSymbol typeParameter, AnalyzedArguments analyzedArguments, InitializerExpressionSyntax initializerOpt, SyntaxNode typeSyntax, BindingDiagnosticBag diagnostics) { if (!typeParameter.HasConstructorConstraint && !typeParameter.IsValueType) { diagnostics.Add(ErrorCode.ERR_NoNewTyvar, node.Location, typeParameter); } else if (analyzedArguments.Arguments.Count > 0) { diagnostics.Add(ErrorCode.ERR_NewTyvarWithArgs, node.Location, typeParameter); } else { var boundInitializerOpt = initializerOpt == null ? null : BindInitializerExpression( syntax: initializerOpt, type: typeParameter, typeSyntax: typeSyntax, isForNewInstance: true, diagnostics: diagnostics); return new BoundNewT(node, boundInitializerOpt, typeParameter); } return MakeBadExpressionForObjectCreation(node, typeParameter, analyzedArguments, initializerOpt, typeSyntax, diagnostics); } /// <summary> /// Given the type containing constructors, gets the list of candidate instance constructors and uses overload resolution to determine which one should be called. /// </summary> /// <param name="typeContainingConstructors">The containing type of the constructors.</param> /// <param name="analyzedArguments">The already bound arguments to the constructor.</param> /// <param name="errorName">The name to use in diagnostics if overload resolution fails.</param> /// <param name="errorLocation">The location at which to report overload resolution result diagnostics.</param> /// <param name="suppressResultDiagnostics">True to suppress overload resolution result diagnostics (but not argument diagnostics).</param> /// <param name="diagnostics">Where diagnostics will be reported.</param> /// <param name="memberResolutionResult">If this method returns true, then it will contain a valid MethodResolutionResult. /// Otherwise, it may contain a MethodResolutionResult for an inaccessible constructor (in which case, it will incorrectly indicate success) or nothing at all.</param> /// <param name="candidateConstructors">Candidate instance constructors of type <paramref name="typeContainingConstructors"/> used for overload resolution.</param> /// <param name="allowProtectedConstructorsOfBaseType">It is always legal to access a protected base class constructor /// via a constructor initializer, but not from an object creation expression.</param> /// <returns>True if overload resolution successfully chose an accessible constructor.</returns> /// <remarks> /// The two-pass algorithm (accessible constructors, then all constructors) is the reason for the unusual signature /// of this method (i.e. not populating a pre-existing <see cref="OverloadResolutionResult{MethodSymbol}"/>). /// Presently, rationalizing this behavior is not worthwhile. /// </remarks> internal bool TryPerformConstructorOverloadResolution( NamedTypeSymbol typeContainingConstructors, AnalyzedArguments analyzedArguments, string errorName, Location errorLocation, bool suppressResultDiagnostics, BindingDiagnosticBag diagnostics, out MemberResolutionResult<MethodSymbol> memberResolutionResult, out ImmutableArray<MethodSymbol> candidateConstructors, bool allowProtectedConstructorsOfBaseType) // Last to make named arguments more convenient. { // Get accessible constructors for performing overload resolution. ImmutableArray<MethodSymbol> allInstanceConstructors; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); candidateConstructors = GetAccessibleConstructorsForOverloadResolution(typeContainingConstructors, allowProtectedConstructorsOfBaseType, out allInstanceConstructors, ref useSiteInfo); OverloadResolutionResult<MethodSymbol> result = OverloadResolutionResult<MethodSymbol>.GetInstance(); // Indicates whether overload resolution successfully chose an accessible constructor. bool succeededConsideringAccessibility = false; // Indicates whether overload resolution resulted in a single best match, even though it might be inaccessible. bool succeededIgnoringAccessibility = false; if (candidateConstructors.Any()) { // We have at least one accessible candidate constructor, perform overload resolution with accessible candidateConstructors. this.OverloadResolution.ObjectCreationOverloadResolution(candidateConstructors, analyzedArguments, result, ref useSiteInfo); if (result.Succeeded) { succeededConsideringAccessibility = true; succeededIgnoringAccessibility = true; } } if (!succeededConsideringAccessibility && allInstanceConstructors.Length > candidateConstructors.Length) { // Overload resolution failed on the accessible candidateConstructors, but we have at least one inaccessible constructor. // We might have a best match constructor which is inaccessible. // Try overload resolution with all instance constructors to generate correct diagnostics and semantic info for this case. OverloadResolutionResult<MethodSymbol> inaccessibleResult = OverloadResolutionResult<MethodSymbol>.GetInstance(); this.OverloadResolution.ObjectCreationOverloadResolution(allInstanceConstructors, analyzedArguments, inaccessibleResult, ref useSiteInfo); if (inaccessibleResult.Succeeded) { succeededIgnoringAccessibility = true; candidateConstructors = allInstanceConstructors; result.Free(); result = inaccessibleResult; } else { inaccessibleResult.Free(); } } diagnostics.Add(errorLocation, useSiteInfo); if (succeededIgnoringAccessibility) { this.CoerceArguments<MethodSymbol>(result.ValidResult, analyzedArguments.Arguments, diagnostics, receiverType: null, receiverRefKind: null, receiverEscapeScope: Binder.ExternalScope); } // Fill in the out parameter with the result, if there was one; it might be inaccessible. memberResolutionResult = succeededIgnoringAccessibility ? result.ValidResult : default(MemberResolutionResult<MethodSymbol>); // Invalid results are not interesting - we have enough info in candidateConstructors. // If something failed and we are reporting errors, then report the right errors. // * If the failure was due to inaccessibility, just report that. // * If the failure was not due to inaccessibility then only report an error // on the constructor if there were no errors on the arguments. if (!succeededConsideringAccessibility && !suppressResultDiagnostics) { if (succeededIgnoringAccessibility) { // It is not legal to directly call a protected constructor on a base class unless // the "this" of the call is known to be of the current type. That is, it is // perfectly legal to say ": base()" to call a protected base class ctor, but // it is not legal to say "new MyBase()" if the ctor is protected. // // The native compiler produces the error CS1540: // // Cannot access protected member 'MyBase.MyBase' via a qualifier of type 'MyBase'; // the qualifier must be of type 'Derived' (or derived from it) // // Though technically correct, this is a very confusing error message for this scenario; // one does not typically think of the constructor as being a method that is // called with an implicit "this" of a particular receiver type, even though of course // that is exactly what it is. // // The better error message here is to simply say that the best possible ctor cannot // be accessed because it is not accessible. // // CONSIDER: We might consider making up a new error message for this situation. // // CS0122: 'MyBase.MyBase' is inaccessible due to its protection level diagnostics.Add(ErrorCode.ERR_BadAccess, errorLocation, result.ValidResult.Member); } else { result.ReportDiagnostics( binder: this, location: errorLocation, nodeOpt: null, diagnostics, name: errorName, receiver: null, invokedExpression: null, analyzedArguments, memberGroup: candidateConstructors, typeContainingConstructors, delegateTypeBeingInvoked: null); } } result.Free(); return succeededConsideringAccessibility; } private ImmutableArray<MethodSymbol> GetAccessibleConstructorsForOverloadResolution(NamedTypeSymbol type, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { ImmutableArray<MethodSymbol> allInstanceConstructors; return GetAccessibleConstructorsForOverloadResolution(type, false, out allInstanceConstructors, ref useSiteInfo); } private ImmutableArray<MethodSymbol> GetAccessibleConstructorsForOverloadResolution(NamedTypeSymbol type, bool allowProtectedConstructorsOfBaseType, out ImmutableArray<MethodSymbol> allInstanceConstructors, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (type.IsErrorType()) { // For Caas, we want to supply the constructors even in error cases // We may end up supplying the constructors of an unconstructed symbol, // but that's better than nothing. type = type.GetNonErrorGuess() as NamedTypeSymbol ?? type; } allInstanceConstructors = type.InstanceConstructors; return FilterInaccessibleConstructors(allInstanceConstructors, allowProtectedConstructorsOfBaseType, ref useSiteInfo); } private static ConstantValue FoldParameterlessValueTypeConstructor(NamedTypeSymbol type) { // DELIBERATE SPEC VIOLATION: // // Object creation expressions like "new int()" are not considered constant expressions // by the specification but they are by the native compiler; we maintain compatibility // with this bug. // // Additionally, it also treats "new X()", where X is an enum type, as a // constant expression with default value 0, we maintain compatibility with it. var specialType = type.SpecialType; if (type.TypeKind == TypeKind.Enum) { specialType = type.EnumUnderlyingType.SpecialType; } switch (specialType) { case SpecialType.System_SByte: case SpecialType.System_Int16: case SpecialType.System_Int32: case SpecialType.System_Int64: case SpecialType.System_Byte: case SpecialType.System_UInt16: case SpecialType.System_UInt32: case SpecialType.System_UInt64: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: case SpecialType.System_Boolean: case SpecialType.System_Char: return ConstantValue.Default(specialType); } return null; } private BoundLiteral BindLiteralConstant(LiteralExpressionSyntax node, BindingDiagnosticBag diagnostics) { // bug.Assert(node.Kind == SyntaxKind.LiteralExpression); var value = node.Token.Value; ConstantValue cv; TypeSymbol type = null; if (value == null) { cv = ConstantValue.Null; } else { Debug.Assert(!value.GetType().GetTypeInfo().IsEnum); var specialType = SpecialTypeExtensions.FromRuntimeTypeOfLiteralValue(value); // C# literals can't be of type byte, sbyte, short, ushort: Debug.Assert( specialType != SpecialType.None && specialType != SpecialType.System_Byte && specialType != SpecialType.System_SByte && specialType != SpecialType.System_Int16 && specialType != SpecialType.System_UInt16); cv = ConstantValue.Create(value, specialType); type = GetSpecialType(specialType, diagnostics, node); } return new BoundLiteral(node, cv, type); } private BoundExpression BindCheckedExpression(CheckedExpressionSyntax node, BindingDiagnosticBag diagnostics) { // the binder is not cached since we only cache statement level binders return this.WithCheckedOrUncheckedRegion(node.Kind() == SyntaxKind.CheckedExpression). BindParenthesizedExpression(node.Expression, diagnostics); } /// <summary> /// Binds a member access expression /// </summary> private BoundExpression BindMemberAccess( MemberAccessExpressionSyntax node, bool invoked, bool indexed, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); BoundExpression boundLeft; ExpressionSyntax exprSyntax = node.Expression; if (node.Kind() == SyntaxKind.SimpleMemberAccessExpression) { // NOTE: CheckValue will be called explicitly in BindMemberAccessWithBoundLeft. boundLeft = BindLeftOfPotentialColorColorMemberAccess(exprSyntax, diagnostics); } else { Debug.Assert(node.Kind() == SyntaxKind.PointerMemberAccessExpression); boundLeft = BindRValueWithoutTargetType(exprSyntax, diagnostics); // Not Color Color issues with -> // CONSIDER: another approach would be to construct a BoundPointerMemberAccess (assuming such a type existed), // but that would be much more cumbersome because we'd be unable to build upon the BindMemberAccess infrastructure, // which expects a receiver. // Dereference before binding member; TypeSymbol pointedAtType; bool hasErrors; BindPointerIndirectionExpressionInternal(node, boundLeft, diagnostics, out pointedAtType, out hasErrors); // If there is no pointed-at type, fall back on the actual type (i.e. assume the user meant "." instead of "->"). if (ReferenceEquals(pointedAtType, null)) { boundLeft = ToBadExpression(boundLeft); } else { boundLeft = new BoundPointerIndirectionOperator(exprSyntax, boundLeft, pointedAtType, hasErrors) { WasCompilerGenerated = true, // don't interfere with the type info for exprSyntax. }; } } return BindMemberAccessWithBoundLeft(node, boundLeft, node.Name, node.OperatorToken, invoked, indexed, diagnostics); } /// <summary> /// Attempt to bind the LHS of a member access expression. If this is a Color Color case (spec 7.6.4.1), /// then return a BoundExpression if we can easily disambiguate or a BoundTypeOrValueExpression if we /// cannot. If this is not a Color Color case, then return null. /// </summary> private BoundExpression BindLeftOfPotentialColorColorMemberAccess(ExpressionSyntax left, BindingDiagnosticBag diagnostics) { if (left is IdentifierNameSyntax identifier) { return BindLeftIdentifierOfPotentialColorColorMemberAccess(identifier, diagnostics); } // NOTE: it is up to the caller to call CheckValue on the result. return BindExpression(left, diagnostics); } // Avoid inlining to minimize stack size in caller. [MethodImpl(MethodImplOptions.NoInlining)] private BoundExpression BindLeftIdentifierOfPotentialColorColorMemberAccess(IdentifierNameSyntax left, BindingDiagnosticBag diagnostics) { // SPEC: 7.6.4.1 Identical simple names and type names // SPEC: In a member access of the form E.I, if E is a single identifier, and if the meaning of E as // SPEC: a simple-name (spec 7.6.2) is a constant, field, property, local variable, or parameter with the // SPEC: same type as the meaning of E as a type-name (spec 3.8), then both possible meanings of E are // SPEC: permitted. The two possible meanings of E.I are never ambiguous, since I must necessarily be // SPEC: a member of the type E in both cases. In other words, the rule simply permits access to the // SPEC: static members and nested types of E where a compile-time error would otherwise have occurred. var valueDiagnostics = BindingDiagnosticBag.Create(diagnostics); var boundValue = BindIdentifier(left, invoked: false, indexed: false, diagnostics: valueDiagnostics); Symbol leftSymbol; if (boundValue.Kind == BoundKind.Conversion) { // BindFieldAccess may insert a conversion if binding occurs // within an enum member initializer. leftSymbol = ((BoundConversion)boundValue).Operand.ExpressionSymbol; } else { leftSymbol = boundValue.ExpressionSymbol; } if ((object)leftSymbol != null) { switch (leftSymbol.Kind) { case SymbolKind.Field: case SymbolKind.Local: case SymbolKind.Parameter: case SymbolKind.Property: case SymbolKind.RangeVariable: var leftType = boundValue.Type; Debug.Assert((object)leftType != null); var leftName = left.Identifier.ValueText; if (leftType.Name == leftName || IsUsingAliasInScope(leftName)) { var typeDiagnostics = BindingDiagnosticBag.Create(diagnostics); var boundType = BindNamespaceOrType(left, typeDiagnostics); if (TypeSymbol.Equals(boundType.Type, leftType, TypeCompareKind.ConsiderEverything2)) { // NOTE: ReplaceTypeOrValueReceiver will call CheckValue explicitly. boundValue = BindToNaturalType(boundValue, valueDiagnostics); return new BoundTypeOrValueExpression(left, new BoundTypeOrValueData(leftSymbol, boundValue, valueDiagnostics, boundType, typeDiagnostics), leftType); } } break; // case SymbolKind.Event: //SPEC: 7.6.4.1 (a.k.a. Color Color) doesn't cover events } } // Not a Color Color case; return the bound member. // NOTE: it is up to the caller to call CheckValue on the result. diagnostics.AddRange(valueDiagnostics); return boundValue; } // returns true if name matches a using alias in scope // NOTE: when true is returned, the corresponding using is also marked as "used" private bool IsUsingAliasInScope(string name) { var isSemanticModel = this.IsSemanticModelBinder; for (var chain = this.ImportChain; chain != null; chain = chain.ParentOpt) { if (IsUsingAlias(chain.Imports.UsingAliases, name, isSemanticModel)) { return true; } } return false; } private BoundExpression BindDynamicMemberAccess( ExpressionSyntax node, BoundExpression boundLeft, SimpleNameSyntax right, bool invoked, bool indexed, BindingDiagnosticBag diagnostics) { // We have an expression of the form "dynExpr.Name" or "dynExpr.Name<X>" SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax = right.Kind() == SyntaxKind.GenericName ? ((GenericNameSyntax)right).TypeArgumentList.Arguments : default(SeparatedSyntaxList<TypeSyntax>); bool rightHasTypeArguments = typeArgumentsSyntax.Count > 0; ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations = rightHasTypeArguments ? BindTypeArguments(typeArgumentsSyntax, diagnostics) : default(ImmutableArray<TypeWithAnnotations>); bool hasErrors = false; if (!invoked && rightHasTypeArguments) { // error CS0307: The property 'P' cannot be used with type arguments Error(diagnostics, ErrorCode.ERR_TypeArgsNotAllowed, right, right.Identifier.Text, SymbolKind.Property.Localize()); hasErrors = true; } if (rightHasTypeArguments) { for (int i = 0; i < typeArgumentsWithAnnotations.Length; ++i) { var typeArgument = typeArgumentsWithAnnotations[i]; if (typeArgument.Type.IsPointerOrFunctionPointer() || typeArgument.Type.IsRestrictedType()) { // "The type '{0}' may not be used as a type argument" Error(diagnostics, ErrorCode.ERR_BadTypeArgument, typeArgumentsSyntax[i], typeArgument.Type); hasErrors = true; } } } return new BoundDynamicMemberAccess( syntax: node, receiver: boundLeft, typeArgumentsOpt: typeArgumentsWithAnnotations, name: right.Identifier.ValueText, invoked: invoked, indexed: indexed, type: Compilation.DynamicType, hasErrors: hasErrors); } /// <summary> /// Bind the RHS of a member access expression, given the bound LHS. /// It is assumed that CheckValue has not been called on the LHS. /// </summary> /// <remarks> /// If new checks are added to this method, they will also need to be added to <see cref="MakeQueryInvocation(CSharpSyntaxNode, BoundExpression, string, TypeSyntax, TypeWithAnnotations, BindingDiagnosticBag)"/>. /// </remarks> private BoundExpression BindMemberAccessWithBoundLeft( ExpressionSyntax node, BoundExpression boundLeft, SimpleNameSyntax right, SyntaxToken operatorToken, bool invoked, bool indexed, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); Debug.Assert(boundLeft != null); boundLeft = MakeMemberAccessValue(boundLeft, diagnostics); TypeSymbol leftType = boundLeft.Type; if ((object)leftType != null && leftType.IsDynamic()) { // There are some sources of a `dynamic` typed value that can be known before runtime // to be invalid. For example, accessing a set-only property whose type is dynamic: // dynamic Goo { set; } // If Goo itself is a dynamic thing (e.g. in `x.Goo.Bar`, `x` is dynamic, and we're // currently checking Bar), then CheckValue will do nothing. boundLeft = CheckValue(boundLeft, BindValueKind.RValue, diagnostics); return BindDynamicMemberAccess(node, boundLeft, right, invoked, indexed, diagnostics); } // No member accesses on void if ((object)leftType != null && leftType.IsVoidType()) { diagnostics.Add(ErrorCode.ERR_BadUnaryOp, operatorToken.GetLocation(), SyntaxFacts.GetText(operatorToken.Kind()), leftType); return BadExpression(node, boundLeft); } // No member accesses on default if (boundLeft.IsLiteralDefault()) { DiagnosticInfo diagnosticInfo = new CSDiagnosticInfo(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, SyntaxFacts.GetText(operatorToken.Kind()), boundLeft.Display); diagnostics.Add(new CSDiagnostic(diagnosticInfo, operatorToken.GetLocation())); return BadExpression(node, boundLeft); } if (boundLeft.Kind == BoundKind.UnboundLambda) { Debug.Assert((object)leftType == null); var msgId = ((UnboundLambda)boundLeft).MessageID; diagnostics.Add(ErrorCode.ERR_BadUnaryOp, node.Location, SyntaxFacts.GetText(operatorToken.Kind()), msgId.Localize()); return BadExpression(node, boundLeft); } boundLeft = BindToNaturalType(boundLeft, diagnostics); leftType = boundLeft.Type; var lookupResult = LookupResult.GetInstance(); try { LookupOptions options = LookupOptions.AllMethodsOnArityZero; if (invoked) { options |= LookupOptions.MustBeInvocableIfMember; } var typeArgumentsSyntax = right.Kind() == SyntaxKind.GenericName ? ((GenericNameSyntax)right).TypeArgumentList.Arguments : default(SeparatedSyntaxList<TypeSyntax>); var typeArguments = typeArgumentsSyntax.Count > 0 ? BindTypeArguments(typeArgumentsSyntax, diagnostics) : default(ImmutableArray<TypeWithAnnotations>); // A member-access consists of a primary-expression, a predefined-type, or a // qualified-alias-member, followed by a "." token, followed by an identifier, // optionally followed by a type-argument-list. // A member-access is either of the form E.I or of the form E.I<A1, ..., AK>, where // E is a primary-expression, I is a single identifier and <A1, ..., AK> is an // optional type-argument-list. When no type-argument-list is specified, consider K // to be zero. // UNDONE: A member-access with a primary-expression of type dynamic is dynamically bound. // UNDONE: In this case the compiler classifies the member access as a property access of // UNDONE: type dynamic. The rules below to determine the meaning of the member-access are // UNDONE: then applied at run-time, using the run-time type instead of the compile-time // UNDONE: type of the primary-expression. If this run-time classification leads to a method // UNDONE: group, then the member access must be the primary-expression of an invocation-expression. // The member-access is evaluated and classified as follows: var rightName = right.Identifier.ValueText; var rightArity = right.Arity; BoundExpression result; switch (boundLeft.Kind) { case BoundKind.NamespaceExpression: { result = tryBindMemberAccessWithBoundNamespaceLeft(((BoundNamespaceExpression)boundLeft).NamespaceSymbol, node, boundLeft, right, diagnostics, lookupResult, options, typeArgumentsSyntax, typeArguments, rightName, rightArity); if (result is object) { return result; } break; } case BoundKind.TypeExpression: { result = tryBindMemberAccessWithBoundTypeLeft(node, boundLeft, right, invoked, indexed, diagnostics, leftType, lookupResult, options, typeArgumentsSyntax, typeArguments, rightName, rightArity); if (result is object) { return result; } break; } case BoundKind.TypeOrValueExpression: { // CheckValue call will occur in ReplaceTypeOrValueReceiver. // NOTE: This means that we won't get CheckValue diagnostics in error scenarios, // but they would be cascading anyway. return BindInstanceMemberAccess(node, right, boundLeft, rightName, rightArity, typeArgumentsSyntax, typeArguments, invoked, indexed, diagnostics); } default: { // Can't dot into the null literal if (boundLeft.Kind == BoundKind.Literal && ((BoundLiteral)boundLeft).ConstantValueOpt == ConstantValue.Null) { if (!boundLeft.HasAnyErrors) { Error(diagnostics, ErrorCode.ERR_BadUnaryOp, node, operatorToken.Text, boundLeft.Display); } return BadExpression(node, boundLeft); } else if ((object)leftType != null) { // NB: We don't know if we really only need RValue access, or if we are actually // passing the receiver implicitly by ref (e.g. in a struct instance method invocation). // These checks occur later. boundLeft = CheckValue(boundLeft, BindValueKind.RValue, diagnostics); boundLeft = BindToNaturalType(boundLeft, diagnostics); return BindInstanceMemberAccess(node, right, boundLeft, rightName, rightArity, typeArgumentsSyntax, typeArguments, invoked, indexed, diagnostics); } break; } } this.BindMemberAccessReportError(node, right, rightName, boundLeft, lookupResult.Error, diagnostics); return BindMemberAccessBadResult(node, rightName, boundLeft, lookupResult.Error, lookupResult.Symbols.ToImmutable(), lookupResult.Kind); } finally { lookupResult.Free(); } [MethodImpl(MethodImplOptions.NoInlining)] BoundExpression tryBindMemberAccessWithBoundNamespaceLeft( NamespaceSymbol ns, ExpressionSyntax node, BoundExpression boundLeft, SimpleNameSyntax right, BindingDiagnosticBag diagnostics, LookupResult lookupResult, LookupOptions options, SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax, ImmutableArray<TypeWithAnnotations> typeArguments, string rightName, int rightArity) { // If K is zero and E is a namespace and E contains a nested namespace with name I, // then the result is that namespace. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupMembersWithFallback(lookupResult, ns, rightName, rightArity, ref useSiteInfo, options: options); diagnostics.Add(right, useSiteInfo); ArrayBuilder<Symbol> symbols = lookupResult.Symbols; if (lookupResult.IsMultiViable) { bool wasError; Symbol sym = ResultSymbol(lookupResult, rightName, rightArity, node, diagnostics, false, out wasError, ns, options); if (wasError) { return new BoundBadExpression(node, LookupResultKind.Ambiguous, lookupResult.Symbols.AsImmutable(), ImmutableArray.Create(boundLeft), CreateErrorType(rightName), hasErrors: true); } else if (sym.Kind == SymbolKind.Namespace) { return new BoundNamespaceExpression(node, (NamespaceSymbol)sym); } else { Debug.Assert(sym.Kind == SymbolKind.NamedType); var type = (NamedTypeSymbol)sym; if (!typeArguments.IsDefault) { type = ConstructNamedTypeUnlessTypeArgumentOmitted(right, type, typeArgumentsSyntax, typeArguments, diagnostics); } ReportDiagnosticsIfObsolete(diagnostics, type, node, hasBaseReceiver: false); return new BoundTypeExpression(node, null, type); } } else if (lookupResult.Kind == LookupResultKind.WrongArity) { Debug.Assert(symbols.Count > 0); Debug.Assert(symbols[0].Kind == SymbolKind.NamedType); Error(diagnostics, lookupResult.Error, right); return new BoundTypeExpression(node, null, new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(symbols[0]), symbols.ToImmutable(), lookupResult.Kind, lookupResult.Error, rightArity)); } else if (lookupResult.Kind == LookupResultKind.Empty) { Debug.Assert(lookupResult.IsClear, "If there's a legitimate reason for having candidates without a reason, then we should produce something intelligent in such cases."); Debug.Assert(lookupResult.Error == null); NotFound(node, rightName, rightArity, rightName, diagnostics, aliasOpt: null, qualifierOpt: ns, options: options); return new BoundBadExpression(node, lookupResult.Kind, symbols.AsImmutable(), ImmutableArray.Create(boundLeft), CreateErrorType(rightName), hasErrors: true); } return null; } [MethodImpl(MethodImplOptions.NoInlining)] BoundExpression tryBindMemberAccessWithBoundTypeLeft( ExpressionSyntax node, BoundExpression boundLeft, SimpleNameSyntax right, bool invoked, bool indexed, BindingDiagnosticBag diagnostics, TypeSymbol leftType, LookupResult lookupResult, LookupOptions options, SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax, ImmutableArray<TypeWithAnnotations> typeArguments, string rightName, int rightArity) { Debug.Assert((object)leftType != null); if (leftType.TypeKind == TypeKind.TypeParameter) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupMembersWithFallback(lookupResult, leftType, rightName, rightArity, ref useSiteInfo, basesBeingResolved: null, options: options | LookupOptions.MustNotBeInstance | LookupOptions.MustBeAbstract); diagnostics.Add(right, useSiteInfo); if (lookupResult.IsMultiViable) { CheckFeatureAvailability(boundLeft.Syntax, MessageID.IDS_FeatureStaticAbstractMembersInInterfaces, diagnostics); return BindMemberOfType(node, right, rightName, rightArity, indexed, boundLeft, typeArgumentsSyntax, typeArguments, lookupResult, BoundMethodGroupFlags.None, diagnostics: diagnostics); } else if (lookupResult.IsClear) { Error(diagnostics, ErrorCode.ERR_BadSKunknown, boundLeft.Syntax, leftType, MessageID.IDS_SK_TYVAR.Localize()); return BadExpression(node, LookupResultKind.NotAValue, boundLeft); } } else if (this.EnclosingNameofArgument == node) { // Support selecting an extension method from a type name in nameof(.) return BindInstanceMemberAccess(node, right, boundLeft, rightName, rightArity, typeArgumentsSyntax, typeArguments, invoked, indexed, diagnostics); } else { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupMembersWithFallback(lookupResult, leftType, rightName, rightArity, ref useSiteInfo, basesBeingResolved: null, options: options); diagnostics.Add(right, useSiteInfo); if (lookupResult.IsMultiViable) { return BindMemberOfType(node, right, rightName, rightArity, indexed, boundLeft, typeArgumentsSyntax, typeArguments, lookupResult, BoundMethodGroupFlags.None, diagnostics: diagnostics); } } return null; } } private void WarnOnAccessOfOffDefault(SyntaxNode node, BoundExpression boundLeft, BindingDiagnosticBag diagnostics) { if ((boundLeft is BoundDefaultLiteral || boundLeft is BoundDefaultExpression) && boundLeft.ConstantValue == ConstantValue.Null && Compilation.LanguageVersion < MessageID.IDS_FeatureNullableReferenceTypes.RequiredVersion()) { Error(diagnostics, ErrorCode.WRN_DotOnDefault, node, boundLeft.Type); } } /// <summary> /// Create a value from the expression that can be used as a left-hand-side /// of a member access. This method special-cases method and property /// groups only. All other expressions are returned as is. /// </summary> private BoundExpression MakeMemberAccessValue(BoundExpression expr, BindingDiagnosticBag diagnostics) { switch (expr.Kind) { case BoundKind.MethodGroup: { var methodGroup = (BoundMethodGroup)expr; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var resolution = this.ResolveMethodGroup(methodGroup, analyzedArguments: null, isMethodGroupConversion: false, useSiteInfo: ref useSiteInfo); diagnostics.Add(expr.Syntax, useSiteInfo); if (!expr.HasAnyErrors) { diagnostics.AddRange(resolution.Diagnostics); if (resolution.MethodGroup != null && !resolution.HasAnyErrors) { Debug.Assert(!resolution.IsEmpty); var method = resolution.MethodGroup.Methods[0]; Error(diagnostics, ErrorCode.ERR_BadSKunknown, methodGroup.NameSyntax, method, MessageID.IDS_SK_METHOD.Localize()); } } expr = this.BindMemberAccessBadResult(methodGroup); resolution.Free(); return expr; } case BoundKind.PropertyGroup: return BindIndexedPropertyAccess((BoundPropertyGroup)expr, mustHaveAllOptionalParameters: false, diagnostics: diagnostics); default: return BindToNaturalType(expr, diagnostics); } } private BoundExpression BindInstanceMemberAccess( SyntaxNode node, SyntaxNode right, BoundExpression boundLeft, string rightName, int rightArity, SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax, ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations, bool invoked, bool indexed, BindingDiagnosticBag diagnostics, bool searchExtensionMethodsIfNecessary = true) { Debug.Assert(rightArity == (typeArgumentsWithAnnotations.IsDefault ? 0 : typeArgumentsWithAnnotations.Length)); var leftType = boundLeft.Type; LookupOptions options = LookupOptions.AllMethodsOnArityZero; if (invoked) { options |= LookupOptions.MustBeInvocableIfMember; } var lookupResult = LookupResult.GetInstance(); try { // If E is a property access, indexer access, variable, or value, the type of // which is T, and a member lookup of I in T with K type arguments produces a // match, then E.I is evaluated and classified as follows: // UNDONE: Classify E as prop access, indexer access, variable or value bool leftIsBaseReference = boundLeft.Kind == BoundKind.BaseReference; if (leftIsBaseReference) { options |= LookupOptions.UseBaseReferenceAccessibility; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupMembersWithFallback(lookupResult, leftType, rightName, rightArity, ref useSiteInfo, basesBeingResolved: null, options: options); diagnostics.Add(right, useSiteInfo); // SPEC: Otherwise, an attempt is made to process E.I as an extension method invocation. // SPEC: If this fails, E.I is an invalid member reference, and a binding-time error occurs. searchExtensionMethodsIfNecessary = searchExtensionMethodsIfNecessary && !leftIsBaseReference; BoundMethodGroupFlags flags = 0; if (searchExtensionMethodsIfNecessary) { flags |= BoundMethodGroupFlags.SearchExtensionMethods; } if (lookupResult.IsMultiViable) { return BindMemberOfType(node, right, rightName, rightArity, indexed, boundLeft, typeArgumentsSyntax, typeArgumentsWithAnnotations, lookupResult, flags, diagnostics); } if (searchExtensionMethodsIfNecessary) { var boundMethodGroup = new BoundMethodGroup( node, typeArgumentsWithAnnotations, boundLeft, rightName, lookupResult.Symbols.All(s => s.Kind == SymbolKind.Method) ? lookupResult.Symbols.SelectAsArray(s_toMethodSymbolFunc) : ImmutableArray<MethodSymbol>.Empty, lookupResult, flags); if (!boundMethodGroup.HasErrors && typeArgumentsSyntax.Any(SyntaxKind.OmittedTypeArgument)) { Error(diagnostics, ErrorCode.ERR_OmittedTypeArgument, node); } return boundMethodGroup; } this.BindMemberAccessReportError(node, right, rightName, boundLeft, lookupResult.Error, diagnostics); return BindMemberAccessBadResult(node, rightName, boundLeft, lookupResult.Error, lookupResult.Symbols.ToImmutable(), lookupResult.Kind); } finally { lookupResult.Free(); } } private void BindMemberAccessReportError(BoundMethodGroup node, BindingDiagnosticBag diagnostics) { var nameSyntax = node.NameSyntax; var syntax = node.MemberAccessExpressionSyntax ?? nameSyntax; this.BindMemberAccessReportError(syntax, nameSyntax, node.Name, node.ReceiverOpt, node.LookupError, diagnostics); } /// <summary> /// Report the error from member access lookup. Or, if there /// was no explicit error from lookup, report "no such member". /// </summary> private void BindMemberAccessReportError( SyntaxNode node, SyntaxNode name, string plainName, BoundExpression boundLeft, DiagnosticInfo lookupError, BindingDiagnosticBag diagnostics) { if (boundLeft.HasAnyErrors && boundLeft.Kind != BoundKind.TypeOrValueExpression) { return; } if (lookupError != null) { // CONSIDER: there are some cases where Dev10 uses the span of "node", // rather than "right". diagnostics.Add(new CSDiagnostic(lookupError, name.Location)); } else if (node.IsQuery()) { ReportQueryLookupFailed(node, boundLeft, plainName, ImmutableArray<Symbol>.Empty, diagnostics); } else { if ((object)boundLeft.Type == null) { Error(diagnostics, ErrorCode.ERR_NoSuchMember, name, boundLeft.Display, plainName); } else if (boundLeft.Kind == BoundKind.TypeExpression || boundLeft.Kind == BoundKind.BaseReference || node.Kind() == SyntaxKind.AwaitExpression && plainName == WellKnownMemberNames.GetResult) { Error(diagnostics, ErrorCode.ERR_NoSuchMember, name, boundLeft.Type, plainName); } else if (WouldUsingSystemFindExtension(boundLeft.Type, plainName)) { Error(diagnostics, ErrorCode.ERR_NoSuchMemberOrExtensionNeedUsing, name, boundLeft.Type, plainName, "System"); } else { Error(diagnostics, ErrorCode.ERR_NoSuchMemberOrExtension, name, boundLeft.Type, plainName); } } } private bool WouldUsingSystemFindExtension(TypeSymbol receiver, string methodName) { // we have a special case to make the diagnostic for await expressions more clear for Windows: // if the receiver type is a windows RT async interface and the method name is GetAwaiter, // then we would suggest a using directive for "System". // TODO: we should check if such a using directive would actually help, or if there is already one in scope. return methodName == WellKnownMemberNames.GetAwaiter && ImplementsWinRTAsyncInterface(receiver); } /// <summary> /// Return true if the given type is or implements a WinRTAsyncInterface. /// </summary> private bool ImplementsWinRTAsyncInterface(TypeSymbol type) { return IsWinRTAsyncInterface(type) || type.AllInterfacesNoUseSiteDiagnostics.Any(i => IsWinRTAsyncInterface(i)); } private bool IsWinRTAsyncInterface(TypeSymbol type) { if (!type.IsInterfaceType()) { return false; } var namedType = ((NamedTypeSymbol)type).ConstructedFrom; return TypeSymbol.Equals(namedType, Compilation.GetWellKnownType(WellKnownType.Windows_Foundation_IAsyncAction), TypeCompareKind.ConsiderEverything2) || TypeSymbol.Equals(namedType, Compilation.GetWellKnownType(WellKnownType.Windows_Foundation_IAsyncActionWithProgress_T), TypeCompareKind.ConsiderEverything2) || TypeSymbol.Equals(namedType, Compilation.GetWellKnownType(WellKnownType.Windows_Foundation_IAsyncOperation_T), TypeCompareKind.ConsiderEverything2) || TypeSymbol.Equals(namedType, Compilation.GetWellKnownType(WellKnownType.Windows_Foundation_IAsyncOperationWithProgress_T2), TypeCompareKind.ConsiderEverything2); } private BoundExpression BindMemberAccessBadResult(BoundMethodGroup node) { var nameSyntax = node.NameSyntax; var syntax = node.MemberAccessExpressionSyntax ?? nameSyntax; return this.BindMemberAccessBadResult(syntax, node.Name, node.ReceiverOpt, node.LookupError, StaticCast<Symbol>.From(node.Methods), node.ResultKind); } /// <summary> /// Return a BoundExpression representing the invalid member. /// </summary> private BoundExpression BindMemberAccessBadResult( SyntaxNode node, string nameString, BoundExpression boundLeft, DiagnosticInfo lookupError, ImmutableArray<Symbol> symbols, LookupResultKind lookupKind) { if (symbols.Length > 0 && symbols[0].Kind == SymbolKind.Method) { var builder = ArrayBuilder<MethodSymbol>.GetInstance(); foreach (var s in symbols) { var m = s as MethodSymbol; if ((object)m != null) builder.Add(m); } var methods = builder.ToImmutableAndFree(); // Expose the invalid methods as a BoundMethodGroup. // Since we do not want to perform further method // lookup, searchExtensionMethods is set to false. // Don't bother calling ConstructBoundMethodGroupAndReportOmittedTypeArguments - // we've reported other errors. return new BoundMethodGroup( node, default(ImmutableArray<TypeWithAnnotations>), nameString, methods, methods.Length == 1 ? methods[0] : null, lookupError, flags: BoundMethodGroupFlags.None, receiverOpt: boundLeft, resultKind: lookupKind, hasErrors: true); } var symbolOpt = symbols.Length == 1 ? symbols[0] : null; return new BoundBadExpression( node, lookupKind, (object)symbolOpt == null ? ImmutableArray<Symbol>.Empty : ImmutableArray.Create(symbolOpt), boundLeft == null ? ImmutableArray<BoundExpression>.Empty : ImmutableArray.Create(BindToTypeForErrorRecovery(boundLeft)), GetNonMethodMemberType(symbolOpt)); } private TypeSymbol GetNonMethodMemberType(Symbol symbolOpt) { TypeSymbol resultType = null; if ((object)symbolOpt != null) { switch (symbolOpt.Kind) { case SymbolKind.Field: resultType = ((FieldSymbol)symbolOpt).GetFieldType(this.FieldsBeingBound).Type; break; case SymbolKind.Property: resultType = ((PropertySymbol)symbolOpt).Type; break; case SymbolKind.Event: resultType = ((EventSymbol)symbolOpt).Type; break; } } return resultType ?? CreateErrorType(); } /// <summary> /// Combine the receiver and arguments of an extension method /// invocation into a single argument list to allow overload resolution /// to treat the invocation as a static method invocation with no receiver. /// </summary> private static void CombineExtensionMethodArguments(BoundExpression receiver, AnalyzedArguments originalArguments, AnalyzedArguments extensionMethodArguments) { Debug.Assert(receiver != null); Debug.Assert(extensionMethodArguments.Arguments.Count == 0); Debug.Assert(extensionMethodArguments.Names.Count == 0); Debug.Assert(extensionMethodArguments.RefKinds.Count == 0); extensionMethodArguments.IsExtensionMethodInvocation = true; extensionMethodArguments.Arguments.Add(receiver); extensionMethodArguments.Arguments.AddRange(originalArguments.Arguments); if (originalArguments.Names.Count > 0) { extensionMethodArguments.Names.Add(null); extensionMethodArguments.Names.AddRange(originalArguments.Names); } if (originalArguments.RefKinds.Count > 0) { extensionMethodArguments.RefKinds.Add(RefKind.None); extensionMethodArguments.RefKinds.AddRange(originalArguments.RefKinds); } } /// <summary> /// Binds a static or instance member access. /// </summary> private BoundExpression BindMemberOfType( SyntaxNode node, SyntaxNode right, string plainName, int arity, bool indexed, BoundExpression left, SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax, ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations, LookupResult lookupResult, BoundMethodGroupFlags methodGroupFlags, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); Debug.Assert(left != null); Debug.Assert(lookupResult.IsMultiViable); Debug.Assert(lookupResult.Symbols.Any()); var members = ArrayBuilder<Symbol>.GetInstance(); BoundExpression result; bool wasError; Symbol symbol = GetSymbolOrMethodOrPropertyGroup(lookupResult, right, plainName, arity, members, diagnostics, out wasError, qualifierOpt: left is BoundTypeExpression typeExpr ? typeExpr.Type : null); if ((object)symbol == null) { Debug.Assert(members.Count > 0); // If I identifies one or more methods, then the result is a method group with // no associated instance expression. If a type argument list was specified, it // is used in calling a generic method. // (Note that for static methods, we are stashing away the type expression in // the receiver of the method group, even though the spec notes that there is // no associated instance expression.) result = ConstructBoundMemberGroupAndReportOmittedTypeArguments( node, typeArgumentsSyntax, typeArgumentsWithAnnotations, left, plainName, members, lookupResult, methodGroupFlags, wasError, diagnostics); } else { // methods are special because of extension methods. Debug.Assert(symbol.Kind != SymbolKind.Method); left = ReplaceTypeOrValueReceiver(left, symbol.IsStatic || symbol.Kind == SymbolKind.NamedType, diagnostics); // Events are handled later as we don't know yet if we are binding to the event or it's backing field. if (symbol.Kind != SymbolKind.Event) { ReportDiagnosticsIfObsolete(diagnostics, symbol, node, hasBaseReceiver: left.Kind == BoundKind.BaseReference); } switch (symbol.Kind) { case SymbolKind.NamedType: case SymbolKind.ErrorType: if (IsInstanceReceiver(left) == true && !wasError) { // CS0572: 'B': cannot reference a type through an expression; try 'A.B' instead Error(diagnostics, ErrorCode.ERR_BadTypeReference, right, plainName, symbol); wasError = true; } // If I identifies a type, then the result is that type constructed with // the given type arguments. var type = (NamedTypeSymbol)symbol; if (!typeArgumentsWithAnnotations.IsDefault) { type = ConstructNamedTypeUnlessTypeArgumentOmitted(right, type, typeArgumentsSyntax, typeArgumentsWithAnnotations, diagnostics); } result = new BoundTypeExpression( syntax: node, aliasOpt: null, boundContainingTypeOpt: left as BoundTypeExpression, boundDimensionsOpt: ImmutableArray<BoundExpression>.Empty, typeWithAnnotations: TypeWithAnnotations.Create(type)); break; case SymbolKind.Property: // If I identifies a static property, then the result is a property // access with no associated instance expression. result = BindPropertyAccess(node, left, (PropertySymbol)symbol, diagnostics, lookupResult.Kind, hasErrors: wasError); break; case SymbolKind.Event: // If I identifies a static event, then the result is an event // access with no associated instance expression. result = BindEventAccess(node, left, (EventSymbol)symbol, diagnostics, lookupResult.Kind, hasErrors: wasError); break; case SymbolKind.Field: // If I identifies a static field: // UNDONE: If the field is readonly and the reference occurs outside the static constructor of // UNDONE: the class or struct in which the field is declared, then the result is a value, namely // UNDONE: the value of the static field I in E. // UNDONE: Otherwise, the result is a variable, namely the static field I in E. // UNDONE: Need a way to mark an expression node as "I am a variable, not a value". result = BindFieldAccess(node, left, (FieldSymbol)symbol, diagnostics, lookupResult.Kind, indexed, hasErrors: wasError); break; default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } } members.Free(); return result; } protected MethodGroupResolution BindExtensionMethod( SyntaxNode expression, string methodName, AnalyzedArguments analyzedArguments, BoundExpression left, ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations, bool isMethodGroupConversion, RefKind returnRefKind, TypeSymbol returnType, bool withDependencies) { var firstResult = new MethodGroupResolution(); AnalyzedArguments actualArguments = null; foreach (var scope in new ExtensionMethodScopes(this)) { var methodGroup = MethodGroup.GetInstance(); var diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies); this.PopulateExtensionMethodsFromSingleBinder(scope, methodGroup, expression, left, methodName, typeArgumentsWithAnnotations, diagnostics); // analyzedArguments will be null if the caller is resolving for error recovery to the first method group // that can accept that receiver, regardless of arguments, when the signature cannot be inferred. // (In the error case of nameof(o.M) or the error case of o.M = null; for instance.) if (analyzedArguments == null) { if (expression == EnclosingNameofArgument) { for (int i = methodGroup.Methods.Count - 1; i >= 0; i--) { if ((object)methodGroup.Methods[i].ReduceExtensionMethod(left.Type, this.Compilation) == null) methodGroup.Methods.RemoveAt(i); } } if (methodGroup.Methods.Count != 0) { return new MethodGroupResolution(methodGroup, diagnostics.ToReadOnlyAndFree()); } } if (methodGroup.Methods.Count == 0) { methodGroup.Free(); diagnostics.Free(); continue; } if (actualArguments == null) { // Create a set of arguments for overload resolution of the // extension methods that includes the "this" parameter. actualArguments = AnalyzedArguments.GetInstance(); CombineExtensionMethodArguments(left, analyzedArguments, actualArguments); } var overloadResolutionResult = OverloadResolutionResult<MethodSymbol>.GetInstance(); bool allowRefOmittedArguments = methodGroup.Receiver.IsExpressionOfComImportType(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); OverloadResolution.MethodInvocationOverloadResolution( methods: methodGroup.Methods, typeArguments: methodGroup.TypeArguments, receiver: methodGroup.Receiver, arguments: actualArguments, result: overloadResolutionResult, useSiteInfo: ref useSiteInfo, isMethodGroupConversion: isMethodGroupConversion, allowRefOmittedArguments: allowRefOmittedArguments, returnRefKind: returnRefKind, returnType: returnType); diagnostics.Add(expression, useSiteInfo); var sealedDiagnostics = diagnostics.ToReadOnlyAndFree(); // Note: the MethodGroupResolution instance is responsible for freeing its copy of actual arguments var result = new MethodGroupResolution(methodGroup, null, overloadResolutionResult, AnalyzedArguments.GetInstance(actualArguments), methodGroup.ResultKind, sealedDiagnostics); // If the search in the current scope resulted in any applicable method (regardless of whether a best // applicable method could be determined) then our search is complete. Otherwise, store aside the // first non-applicable result and continue searching for an applicable result. if (result.HasAnyApplicableMethod) { if (!firstResult.IsEmpty) { firstResult.MethodGroup.Free(); firstResult.OverloadResolutionResult.Free(); } return result; } else if (firstResult.IsEmpty) { firstResult = result; } else { // Neither the first result, nor applicable. No need to save result. overloadResolutionResult.Free(); methodGroup.Free(); } } Debug.Assert((actualArguments == null) || !firstResult.IsEmpty); actualArguments?.Free(); return firstResult; } private void PopulateExtensionMethodsFromSingleBinder( ExtensionMethodScope scope, MethodGroup methodGroup, SyntaxNode node, BoundExpression left, string rightName, ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations, BindingDiagnosticBag diagnostics) { int arity; LookupOptions options; if (typeArgumentsWithAnnotations.IsDefault) { arity = 0; options = LookupOptions.AllMethodsOnArityZero; } else { arity = typeArgumentsWithAnnotations.Length; options = LookupOptions.Default; } var lookupResult = LookupResult.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupExtensionMethodsInSingleBinder(scope, lookupResult, rightName, arity, options, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (lookupResult.IsMultiViable) { Debug.Assert(lookupResult.Symbols.Any()); var members = ArrayBuilder<Symbol>.GetInstance(); bool wasError; Symbol symbol = GetSymbolOrMethodOrPropertyGroup(lookupResult, node, rightName, arity, members, diagnostics, out wasError, qualifierOpt: null); Debug.Assert((object)symbol == null); Debug.Assert(members.Count > 0); methodGroup.PopulateWithExtensionMethods(left, members, typeArgumentsWithAnnotations, lookupResult.Kind); members.Free(); } lookupResult.Free(); } protected BoundExpression BindFieldAccess( SyntaxNode node, BoundExpression receiver, FieldSymbol fieldSymbol, BindingDiagnosticBag diagnostics, LookupResultKind resultKind, bool indexed, bool hasErrors) { bool hasError = false; NamedTypeSymbol type = fieldSymbol.ContainingType; var isEnumField = (fieldSymbol.IsStatic && type.IsEnumType()); if (isEnumField && !type.IsValidEnumType()) { Error(diagnostics, ErrorCode.ERR_BindToBogus, node, fieldSymbol); hasError = true; } if (!hasError) { hasError = this.CheckInstanceOrStatic(node, receiver, fieldSymbol, ref resultKind, diagnostics); } if (!hasError && fieldSymbol.IsFixedSizeBuffer && !IsInsideNameof) { // SPEC: In a member access of the form E.I, if E is of a struct type and a member lookup of I in // that struct type identifies a fixed size member, then E.I is evaluated and classified as follows: // * If the expression E.I does not occur in an unsafe context, a compile-time error occurs. // * If E is classified as a value, a compile-time error occurs. // * Otherwise, if E is a moveable variable and the expression E.I is not a fixed_pointer_initializer, // a compile-time error occurs. // * Otherwise, E references a fixed variable and the result of the expression is a pointer to the // first element of the fixed size buffer member I in E. The result is of type S*, where S is // the element type of I, and is classified as a value. TypeSymbol receiverType = receiver.Type; // Reflect errors that have been reported elsewhere... hasError = (object)receiverType == null || !receiverType.IsValueType; if (!hasError) { var isFixedStatementExpression = SyntaxFacts.IsFixedStatementExpression(node); if (IsMoveableVariable(receiver, out Symbol accessedLocalOrParameterOpt) != isFixedStatementExpression) { if (indexed) { // SPEC C# 7.3: If the fixed size buffer access is the receiver of an element_access_expression, // E may be either fixed or moveable CheckFeatureAvailability(node, MessageID.IDS_FeatureIndexingMovableFixedBuffers, diagnostics); } else { Error(diagnostics, isFixedStatementExpression ? ErrorCode.ERR_FixedNotNeeded : ErrorCode.ERR_FixedBufferNotFixed, node); hasErrors = hasError = true; } } } if (!hasError) { hasError = !CheckValueKind(node, receiver, BindValueKind.FixedReceiver, checkingReceiver: false, diagnostics: diagnostics); } } ConstantValue constantValueOpt = null; if (fieldSymbol.IsConst && !IsInsideNameof) { constantValueOpt = fieldSymbol.GetConstantValue(this.ConstantFieldsInProgress, this.IsEarlyAttributeBinder); if (constantValueOpt == ConstantValue.Unset) { // Evaluating constant expression before dependencies // have been evaluated. Treat this as a Bad value. constantValueOpt = ConstantValue.Bad; } } if (!fieldSymbol.IsStatic) { WarnOnAccessOfOffDefault(node, receiver, diagnostics); } if (!IsBadBaseAccess(node, receiver, fieldSymbol, diagnostics)) { CheckReceiverAndRuntimeSupportForSymbolAccess(node, receiver, fieldSymbol, diagnostics); } TypeSymbol fieldType = fieldSymbol.GetFieldType(this.FieldsBeingBound).Type; BoundExpression expr = new BoundFieldAccess(node, receiver, fieldSymbol, constantValueOpt, resultKind, fieldType, hasErrors: (hasErrors || hasError)); // Spec 14.3: "Within an enum member initializer, values of other enum members are // always treated as having the type of their underlying type" if (this.InEnumMemberInitializer()) { NamedTypeSymbol enumType = null; if (isEnumField) { // This is an obvious consequence of the spec. // It is for cases like: // enum E { // A, // B = A + 1, //A is implicitly converted to int (underlying type) // } enumType = type; } else if (constantValueOpt != null && fieldType.IsEnumType()) { // This seems like a borderline SPEC VIOLATION that we're preserving for back compat. // It is for cases like: // const E e = E.A; // enum E { // A, // B = e + 1, //e is implicitly converted to int (underlying type) // } enumType = (NamedTypeSymbol)fieldType; } if ((object)enumType != null) { NamedTypeSymbol underlyingType = enumType.EnumUnderlyingType; Debug.Assert((object)underlyingType != null); expr = new BoundConversion( node, expr, Conversion.ImplicitNumeric, @checked: true, explicitCastInCode: false, conversionGroupOpt: null, constantValueOpt: expr.ConstantValue, type: underlyingType); } } return expr; } private bool InEnumMemberInitializer() { var containingType = this.ContainingType; return this.InFieldInitializer && (object)containingType != null && containingType.IsEnumType(); } private BoundExpression BindPropertyAccess( SyntaxNode node, BoundExpression receiver, PropertySymbol propertySymbol, BindingDiagnosticBag diagnostics, LookupResultKind lookupResult, bool hasErrors) { bool hasError = this.CheckInstanceOrStatic(node, receiver, propertySymbol, ref lookupResult, diagnostics); if (!propertySymbol.IsStatic) { WarnOnAccessOfOffDefault(node, receiver, diagnostics); } return new BoundPropertyAccess(node, receiver, propertySymbol, lookupResult, propertySymbol.Type, hasErrors: (hasErrors || hasError)); } private void CheckReceiverAndRuntimeSupportForSymbolAccess(SyntaxNode node, BoundExpression receiverOpt, Symbol symbol, BindingDiagnosticBag diagnostics) { if (symbol.ContainingType?.IsInterface == true) { if (symbol.IsStatic && symbol.IsAbstract) { Debug.Assert(symbol is not TypeSymbol); if (receiverOpt is BoundQueryClause { Value: var value }) { receiverOpt = value; } if (receiverOpt is not BoundTypeExpression { Type: { TypeKind: TypeKind.TypeParameter } }) { Error(diagnostics, ErrorCode.ERR_BadAbstractStaticMemberAccess, node); return; } if (!Compilation.Assembly.RuntimeSupportsStaticAbstractMembersInInterfaces && Compilation.SourceModule != symbol.ContainingModule) { Error(diagnostics, ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, node); return; } } if (!Compilation.Assembly.RuntimeSupportsDefaultInterfaceImplementation && Compilation.SourceModule != symbol.ContainingModule) { if (!symbol.IsStatic && !(symbol is TypeSymbol) && !symbol.IsImplementableInterfaceMember()) { Error(diagnostics, ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, node); } else { switch (symbol.DeclaredAccessibility) { case Accessibility.Protected: case Accessibility.ProtectedOrInternal: case Accessibility.ProtectedAndInternal: Error(diagnostics, ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, node); break; } } } } } private BoundExpression BindEventAccess( SyntaxNode node, BoundExpression receiver, EventSymbol eventSymbol, BindingDiagnosticBag diagnostics, LookupResultKind lookupResult, bool hasErrors) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); bool isUsableAsField = eventSymbol.HasAssociatedField && this.IsAccessible(eventSymbol.AssociatedField, ref useSiteInfo, (receiver != null) ? receiver.Type : null); diagnostics.Add(node, useSiteInfo); bool hasError = this.CheckInstanceOrStatic(node, receiver, eventSymbol, ref lookupResult, diagnostics); if (!eventSymbol.IsStatic) { WarnOnAccessOfOffDefault(node, receiver, diagnostics); } return new BoundEventAccess(node, receiver, eventSymbol, isUsableAsField, lookupResult, eventSymbol.Type, hasErrors: (hasErrors || hasError)); } // Say if the receive is an instance or a type, or could be either (returns null). private static bool? IsInstanceReceiver(BoundExpression receiver) { if (receiver == null) { return false; } else { switch (receiver.Kind) { case BoundKind.PreviousSubmissionReference: // Could be either instance or static reference. return null; case BoundKind.TypeExpression: return false; case BoundKind.QueryClause: return IsInstanceReceiver(((BoundQueryClause)receiver).Value); default: return true; } } } private bool CheckInstanceOrStatic( SyntaxNode node, BoundExpression receiver, Symbol symbol, ref LookupResultKind resultKind, BindingDiagnosticBag diagnostics) { bool? instanceReceiver = IsInstanceReceiver(receiver); if (!symbol.RequiresInstanceReceiver()) { if (instanceReceiver == true) { ErrorCode errorCode = this.Flags.Includes(BinderFlags.ObjectInitializerMember) ? ErrorCode.ERR_StaticMemberInObjectInitializer : ErrorCode.ERR_ObjectProhibited; Error(diagnostics, errorCode, node, symbol); resultKind = LookupResultKind.StaticInstanceMismatch; return true; } } else { if (instanceReceiver == false && !IsInsideNameof) { Error(diagnostics, ErrorCode.ERR_ObjectRequired, node, symbol); resultKind = LookupResultKind.StaticInstanceMismatch; return true; } } return false; } /// <summary> /// Given a viable LookupResult, report any ambiguity errors and return either a single /// non-method symbol or a method or property group. If the result set represents a /// collection of methods or a collection of properties where at least one of the properties /// is an indexed property, then 'methodOrPropertyGroup' is populated with the method or /// property group and the method returns null. Otherwise, the method returns a single /// symbol and 'methodOrPropertyGroup' is empty. (Since the result set is viable, there /// must be at least one symbol.) If the result set is ambiguous - either containing multiple /// members of different member types, or multiple properties but no indexed properties - /// then a diagnostic is reported for the ambiguity and a single symbol is returned. /// </summary> private Symbol GetSymbolOrMethodOrPropertyGroup(LookupResult result, SyntaxNode node, string plainName, int arity, ArrayBuilder<Symbol> methodOrPropertyGroup, BindingDiagnosticBag diagnostics, out bool wasError, NamespaceOrTypeSymbol qualifierOpt) { Debug.Assert(!methodOrPropertyGroup.Any()); node = GetNameSyntax(node) ?? node; wasError = false; Debug.Assert(result.Kind != LookupResultKind.Empty); Debug.Assert(!result.Symbols.Any(s => s.IsIndexer())); Symbol other = null; // different member type from 'methodOrPropertyGroup' // Populate 'methodOrPropertyGroup' with a set of methods if any, // or a set of properties if properties but no methods. If there are // other member types, 'other' will be set to one of those members. foreach (var symbol in result.Symbols) { var kind = symbol.Kind; if (methodOrPropertyGroup.Count > 0) { var existingKind = methodOrPropertyGroup[0].Kind; if (existingKind != kind) { // Mix of different member kinds. Prefer methods over // properties and properties over other members. if ((existingKind == SymbolKind.Method) || ((existingKind == SymbolKind.Property) && (kind != SymbolKind.Method))) { other = symbol; continue; } other = methodOrPropertyGroup[0]; methodOrPropertyGroup.Clear(); } } if ((kind == SymbolKind.Method) || (kind == SymbolKind.Property)) { // SPEC VIOLATION: The spec states "Members that include an override modifier are excluded from the set" // SPEC VIOLATION: However, we are not going to do that here; we will keep the overriding member // SPEC VIOLATION: in the method group. The reason is because for features like "go to definition" // SPEC VIOLATION: we wish to go to the overriding member, not to the member of the base class. // SPEC VIOLATION: Or, for code generation of a call to Int32.ToString() we want to generate // SPEC VIOLATION: code that directly calls the Int32.ToString method with an int on the stack, // SPEC VIOLATION: rather than making a virtual call to ToString on a boxed int. methodOrPropertyGroup.Add(symbol); } else { other = symbol; } } Debug.Assert(methodOrPropertyGroup.Any() || ((object)other != null)); if ((methodOrPropertyGroup.Count > 0) && IsMethodOrPropertyGroup(methodOrPropertyGroup)) { // Ambiguities between methods and non-methods are reported here, // but all other ambiguities, including those between properties and // non-methods, are reported in ResultSymbol. if ((methodOrPropertyGroup[0].Kind == SymbolKind.Method) || ((object)other == null)) { // Result will be treated as a method or property group. Any additional // checks, such as use-site errors, must be handled by the caller when // converting to method invocation or property access. if (result.Error != null) { Error(diagnostics, result.Error, node); wasError = (result.Error.Severity == DiagnosticSeverity.Error); } return null; } } methodOrPropertyGroup.Clear(); return ResultSymbol(result, plainName, arity, node, diagnostics, false, out wasError, qualifierOpt); } private static bool IsMethodOrPropertyGroup(ArrayBuilder<Symbol> members) { Debug.Assert(members.Count > 0); var member = members[0]; // Members should be a consistent type. Debug.Assert(members.All(m => m.Kind == member.Kind)); switch (member.Kind) { case SymbolKind.Method: return true; case SymbolKind.Property: Debug.Assert(members.All(m => !m.IsIndexer())); // Do not treat a set of non-indexed properties as a property group, to // avoid the overhead of a BoundPropertyGroup node and overload // resolution for the common property access case. If there are multiple // non-indexed properties (two properties P that differ by custom attributes // for instance), the expectation is that the caller will report an ambiguity // and choose one for error recovery. foreach (PropertySymbol property in members) { if (property.IsIndexedProperty) { return true; } } return false; default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } private BoundExpression BindElementAccess(ElementAccessExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression receiver = BindExpression(node.Expression, diagnostics: diagnostics, invoked: false, indexed: true); return BindElementAccess(node, receiver, node.ArgumentList, diagnostics); } private BoundExpression BindElementAccess(ExpressionSyntax node, BoundExpression receiver, BracketedArgumentListSyntax argumentList, BindingDiagnosticBag diagnostics) { AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance(); try { BindArgumentsAndNames(argumentList, diagnostics, analyzedArguments); if (receiver.Kind == BoundKind.PropertyGroup) { var propertyGroup = (BoundPropertyGroup)receiver; return BindIndexedPropertyAccess(node, propertyGroup.ReceiverOpt, propertyGroup.Properties, analyzedArguments, diagnostics); } receiver = CheckValue(receiver, BindValueKind.RValue, diagnostics); receiver = BindToNaturalType(receiver, diagnostics); return BindElementOrIndexerAccess(node, receiver, analyzedArguments, diagnostics); } finally { analyzedArguments.Free(); } } private BoundExpression BindElementOrIndexerAccess(ExpressionSyntax node, BoundExpression expr, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics) { if ((object)expr.Type == null) { return BadIndexerExpression(node, expr, analyzedArguments, null, diagnostics); } WarnOnAccessOfOffDefault(node, expr, diagnostics); // Did we have any errors? if (analyzedArguments.HasErrors || expr.HasAnyErrors) { // At this point we definitely have reported an error, but we still might be // able to get more semantic analysis of the indexing operation. We do not // want to report cascading errors. BoundExpression result = BindElementAccessCore(node, expr, analyzedArguments, BindingDiagnosticBag.Discarded); return result; } return BindElementAccessCore(node, expr, analyzedArguments, diagnostics); } private BoundExpression BadIndexerExpression(ExpressionSyntax node, BoundExpression expr, AnalyzedArguments analyzedArguments, DiagnosticInfo errorOpt, BindingDiagnosticBag diagnostics) { if (!expr.HasAnyErrors) { diagnostics.Add(errorOpt ?? new CSDiagnosticInfo(ErrorCode.ERR_BadIndexLHS, expr.Display), node.Location); } var childBoundNodes = BuildArgumentsForErrorRecovery(analyzedArguments).Add(expr); return new BoundBadExpression(node, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, childBoundNodes, CreateErrorType(), hasErrors: true); } private BoundExpression BindElementAccessCore( ExpressionSyntax node, BoundExpression expr, AnalyzedArguments arguments, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); Debug.Assert(expr != null); Debug.Assert((object)expr.Type != null); Debug.Assert(arguments != null); var exprType = expr.Type; switch (exprType.TypeKind) { case TypeKind.Array: return BindArrayAccess(node, expr, arguments, diagnostics); case TypeKind.Dynamic: return BindDynamicIndexer(node, expr, arguments, ImmutableArray<PropertySymbol>.Empty, diagnostics); case TypeKind.Pointer: return BindPointerElementAccess(node, expr, arguments, diagnostics); case TypeKind.Class: case TypeKind.Struct: case TypeKind.Interface: case TypeKind.TypeParameter: return BindIndexerAccess(node, expr, arguments, diagnostics); case TypeKind.Submission: // script class is synthesized and should not be used as a type of an indexer expression: default: return BadIndexerExpression(node, expr, arguments, null, diagnostics); } } private BoundExpression BindArrayAccess(ExpressionSyntax node, BoundExpression expr, AnalyzedArguments arguments, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); Debug.Assert(expr != null); Debug.Assert(arguments != null); // For an array access, the primary-no-array-creation-expression of the element-access // must be a value of an array-type. Furthermore, the argument-list of an array access // is not allowed to contain named arguments.The number of expressions in the // argument-list must be the same as the rank of the array-type, and each expression // must be of type int, uint, long, ulong, or must be implicitly convertible to one or // more of these types. if (arguments.Names.Count > 0) { Error(diagnostics, ErrorCode.ERR_NamedArgumentForArray, node); } bool hasErrors = ReportRefOrOutArgument(arguments, diagnostics); var arrayType = (ArrayTypeSymbol)expr.Type; // Note that the spec says to determine which of {int, uint, long, ulong} *each* index // expression is convertible to. That is not what C# 1 through 4 did; the // implementations instead determined which of those four types *all* of the index // expressions converted to. int rank = arrayType.Rank; if (arguments.Arguments.Count != rank) { Error(diagnostics, ErrorCode.ERR_BadIndexCount, node, rank); return new BoundArrayAccess(node, expr, BuildArgumentsForErrorRecovery(arguments), arrayType.ElementType, hasErrors: true); } // Convert all the arguments to the array index type. BoundExpression[] convertedArguments = new BoundExpression[arguments.Arguments.Count]; for (int i = 0; i < arguments.Arguments.Count; ++i) { BoundExpression argument = arguments.Arguments[i]; BoundExpression index = ConvertToArrayIndex(argument, diagnostics, allowIndexAndRange: rank == 1); convertedArguments[i] = index; // NOTE: Dev10 only warns if rank == 1 // Question: Why do we limit this warning to one-dimensional arrays? // Answer: Because multidimensional arrays can have nonzero lower bounds in the CLR. if (rank == 1 && !index.HasAnyErrors) { ConstantValue constant = index.ConstantValue; if (constant != null && constant.IsNegativeNumeric) { Error(diagnostics, ErrorCode.WRN_NegativeArrayIndex, index.Syntax); } } } TypeSymbol resultType = rank == 1 && TypeSymbol.Equals( convertedArguments[0].Type, Compilation.GetWellKnownType(WellKnownType.System_Range), TypeCompareKind.ConsiderEverything) ? arrayType : arrayType.ElementType; return hasErrors ? new BoundArrayAccess(node, BindToTypeForErrorRecovery(expr), convertedArguments.Select(e => BindToTypeForErrorRecovery(e)).AsImmutableOrNull(), resultType, hasErrors: true) : new BoundArrayAccess(node, expr, convertedArguments.AsImmutableOrNull(), resultType, hasErrors: false); } private BoundExpression ConvertToArrayIndex(BoundExpression index, BindingDiagnosticBag diagnostics, bool allowIndexAndRange) { Debug.Assert(index != null); if (index.Kind == BoundKind.OutVariablePendingInference) { return ((OutVariablePendingInference)index).FailInference(this, diagnostics); } else if (index.Kind == BoundKind.DiscardExpression && !index.HasExpressionType()) { return ((BoundDiscardExpression)index).FailInference(this, diagnostics); } var node = index.Syntax; var result = TryImplicitConversionToArrayIndex(index, SpecialType.System_Int32, node, diagnostics) ?? TryImplicitConversionToArrayIndex(index, SpecialType.System_UInt32, node, diagnostics) ?? TryImplicitConversionToArrayIndex(index, SpecialType.System_Int64, node, diagnostics) ?? TryImplicitConversionToArrayIndex(index, SpecialType.System_UInt64, node, diagnostics); if (result is null && allowIndexAndRange) { result = TryImplicitConversionToArrayIndex(index, WellKnownType.System_Index, node, diagnostics); if (result is null) { result = TryImplicitConversionToArrayIndex(index, WellKnownType.System_Range, node, diagnostics); if (result is object) { // This member is needed for lowering and should produce an error if not present _ = GetWellKnownTypeMember( WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__GetSubArray_T, diagnostics, syntax: node); } } else { // This member is needed for lowering and should produce an error if not present _ = GetWellKnownTypeMember( WellKnownMember.System_Index__GetOffset, diagnostics, syntax: node); } } if (result is null) { // Give the error that would be given upon conversion to int32. NamedTypeSymbol int32 = GetSpecialType(SpecialType.System_Int32, diagnostics, node); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion failedConversion = this.Conversions.ClassifyConversionFromExpression(index, int32, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); GenerateImplicitConversionError(diagnostics, node, failedConversion, index, int32); // Suppress any additional diagnostics return CreateConversion(node, index, failedConversion, isCast: false, conversionGroupOpt: null, destination: int32, diagnostics: BindingDiagnosticBag.Discarded); } return result; } private BoundExpression TryImplicitConversionToArrayIndex(BoundExpression expr, WellKnownType wellKnownType, SyntaxNode node, BindingDiagnosticBag diagnostics) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); TypeSymbol type = GetWellKnownType(wellKnownType, ref useSiteInfo); if (type.IsErrorType()) { return null; } var attemptDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); var result = TryImplicitConversionToArrayIndex(expr, type, node, attemptDiagnostics); if (result is object) { diagnostics.Add(node, useSiteInfo); diagnostics.AddRange(attemptDiagnostics); } attemptDiagnostics.Free(); return result; } private BoundExpression TryImplicitConversionToArrayIndex(BoundExpression expr, SpecialType specialType, SyntaxNode node, BindingDiagnosticBag diagnostics) { var attemptDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); TypeSymbol type = GetSpecialType(specialType, attemptDiagnostics, node); var result = TryImplicitConversionToArrayIndex(expr, type, node, attemptDiagnostics); if (result is object) { diagnostics.AddRange(attemptDiagnostics); } attemptDiagnostics.Free(); return result; } private BoundExpression TryImplicitConversionToArrayIndex(BoundExpression expr, TypeSymbol targetType, SyntaxNode node, BindingDiagnosticBag diagnostics) { Debug.Assert(expr != null); Debug.Assert((object)targetType != null); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = this.Conversions.ClassifyImplicitConversionFromExpression(expr, targetType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!conversion.Exists) { return null; } if (conversion.IsDynamic) { conversion = conversion.SetArrayIndexConversionForDynamic(); } BoundExpression result = CreateConversion(expr.Syntax, expr, conversion, isCast: false, conversionGroupOpt: null, destination: targetType, diagnostics); // UNDONE: was cast? Debug.Assert(result != null); // If this ever fails (it shouldn't), then put a null-check around the diagnostics update. return result; } private BoundExpression BindPointerElementAccess(ExpressionSyntax node, BoundExpression expr, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); Debug.Assert(expr != null); Debug.Assert(analyzedArguments != null); bool hasErrors = false; if (analyzedArguments.Names.Count > 0) { // CONSIDER: the error text for this error code mentions "arrays". It might be nice if we had // a separate error code for pointer element access. Error(diagnostics, ErrorCode.ERR_NamedArgumentForArray, node); hasErrors = true; } hasErrors = hasErrors || ReportRefOrOutArgument(analyzedArguments, diagnostics); Debug.Assert(expr.Type.IsPointerType()); PointerTypeSymbol pointerType = (PointerTypeSymbol)expr.Type; TypeSymbol pointedAtType = pointerType.PointedAtType; ArrayBuilder<BoundExpression> arguments = analyzedArguments.Arguments; if (arguments.Count != 1) { if (!hasErrors) { Error(diagnostics, ErrorCode.ERR_PtrIndexSingle, node); } return new BoundPointerElementAccess(node, expr, BadExpression(node, BuildArgumentsForErrorRecovery(analyzedArguments)).MakeCompilerGenerated(), CheckOverflowAtRuntime, pointedAtType, hasErrors: true); } if (pointedAtType.IsVoidType()) { Error(diagnostics, ErrorCode.ERR_VoidError, expr.Syntax); hasErrors = true; } BoundExpression index = arguments[0]; index = ConvertToArrayIndex(index, diagnostics, allowIndexAndRange: false); return new BoundPointerElementAccess(node, expr, index, CheckOverflowAtRuntime, pointedAtType, hasErrors); } private static bool ReportRefOrOutArgument(AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics) { int numArguments = analyzedArguments.Arguments.Count; for (int i = 0; i < numArguments; i++) { RefKind refKind = analyzedArguments.RefKind(i); if (refKind != RefKind.None) { Error(diagnostics, ErrorCode.ERR_BadArgExtraRef, analyzedArguments.Argument(i).Syntax, i + 1, refKind.ToArgumentDisplayString()); return true; } } return false; } private BoundExpression BindIndexerAccess(ExpressionSyntax node, BoundExpression expr, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); Debug.Assert(expr != null); Debug.Assert((object)expr.Type != null); Debug.Assert(analyzedArguments != null); LookupResult lookupResult = LookupResult.GetInstance(); LookupOptions lookupOptions = expr.Kind == BoundKind.BaseReference ? LookupOptions.UseBaseReferenceAccessibility : LookupOptions.Default; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupMembersWithFallback(lookupResult, expr.Type, WellKnownMemberNames.Indexer, arity: 0, useSiteInfo: ref useSiteInfo, options: lookupOptions); diagnostics.Add(node, useSiteInfo); // Store, rather than return, so that we can release resources. BoundExpression indexerAccessExpression; if (!lookupResult.IsMultiViable) { if (TryBindIndexOrRangeIndexer( node, expr, analyzedArguments, diagnostics, out var patternIndexerAccess)) { indexerAccessExpression = patternIndexerAccess; } else { indexerAccessExpression = BadIndexerExpression(node, expr, analyzedArguments, lookupResult.Error, diagnostics); } } else { ArrayBuilder<PropertySymbol> indexerGroup = ArrayBuilder<PropertySymbol>.GetInstance(); foreach (Symbol symbol in lookupResult.Symbols) { Debug.Assert(symbol.IsIndexer()); indexerGroup.Add((PropertySymbol)symbol); } indexerAccessExpression = BindIndexerOrIndexedPropertyAccess(node, expr, indexerGroup, analyzedArguments, diagnostics); indexerGroup.Free(); } lookupResult.Free(); return indexerAccessExpression; } private static readonly Func<PropertySymbol, bool> s_isIndexedPropertyWithNonOptionalArguments = property => { if (property.IsIndexer || !property.IsIndexedProperty) { return false; } Debug.Assert(property.ParameterCount > 0); var parameter = property.Parameters[0]; return !parameter.IsOptional && !parameter.IsParams; }; private static readonly SymbolDisplayFormat s_propertyGroupFormat = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, memberOptions: SymbolDisplayMemberOptions.IncludeContainingType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); private BoundExpression BindIndexedPropertyAccess(BoundPropertyGroup propertyGroup, bool mustHaveAllOptionalParameters, BindingDiagnosticBag diagnostics) { var syntax = propertyGroup.Syntax; var receiverOpt = propertyGroup.ReceiverOpt; var properties = propertyGroup.Properties; if (properties.All(s_isIndexedPropertyWithNonOptionalArguments)) { Error(diagnostics, mustHaveAllOptionalParameters ? ErrorCode.ERR_IndexedPropertyMustHaveAllOptionalParams : ErrorCode.ERR_IndexedPropertyRequiresParams, syntax, properties[0].ToDisplayString(s_propertyGroupFormat)); return BoundIndexerAccess.ErrorAccess( syntax, receiverOpt, CreateErrorPropertySymbol(properties), ImmutableArray<BoundExpression>.Empty, default(ImmutableArray<string>), default(ImmutableArray<RefKind>), properties); } var arguments = AnalyzedArguments.GetInstance(); var result = BindIndexedPropertyAccess(syntax, receiverOpt, properties, arguments, diagnostics); arguments.Free(); return result; } private BoundExpression BindIndexedPropertyAccess(SyntaxNode syntax, BoundExpression receiverOpt, ImmutableArray<PropertySymbol> propertyGroup, AnalyzedArguments arguments, BindingDiagnosticBag diagnostics) { // TODO: We're creating an extra copy of the properties array in BindIndexerOrIndexedProperty // converting the ArrayBuilder to ImmutableArray. Avoid the extra copy. var properties = ArrayBuilder<PropertySymbol>.GetInstance(); properties.AddRange(propertyGroup); var result = BindIndexerOrIndexedPropertyAccess(syntax, receiverOpt, properties, arguments, diagnostics); properties.Free(); return result; } private BoundExpression BindDynamicIndexer( SyntaxNode syntax, BoundExpression receiver, AnalyzedArguments arguments, ImmutableArray<PropertySymbol> applicableProperties, BindingDiagnosticBag diagnostics) { bool hasErrors = false; BoundKind receiverKind = receiver.Kind; if (receiverKind == BoundKind.BaseReference) { Error(diagnostics, ErrorCode.ERR_NoDynamicPhantomOnBaseIndexer, syntax); hasErrors = true; } else if (receiverKind == BoundKind.TypeOrValueExpression) { var typeOrValue = (BoundTypeOrValueExpression)receiver; // Unfortunately, the runtime binder doesn't have APIs that would allow us to pass both "type or value". // Ideally the runtime binder would choose between type and value based on the result of the overload resolution. // We need to pick one or the other here. Dev11 compiler passes the type only if the value can't be accessed. bool inStaticContext; bool useType = IsInstance(typeOrValue.Data.ValueSymbol) && !HasThis(isExplicit: false, inStaticContext: out inStaticContext); receiver = ReplaceTypeOrValueReceiver(typeOrValue, useType, diagnostics); } var argArray = BuildArgumentsForDynamicInvocation(arguments, diagnostics); var refKindsArray = arguments.RefKinds.ToImmutableOrNull(); hasErrors &= ReportBadDynamicArguments(syntax, argArray, refKindsArray, diagnostics, queryClause: null); return new BoundDynamicIndexerAccess( syntax, receiver, argArray, arguments.GetNames(), refKindsArray, applicableProperties, AssemblySymbol.DynamicType, hasErrors); } private BoundExpression BindIndexerOrIndexedPropertyAccess( SyntaxNode syntax, BoundExpression receiverOpt, ArrayBuilder<PropertySymbol> propertyGroup, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics) { OverloadResolutionResult<PropertySymbol> overloadResolutionResult = OverloadResolutionResult<PropertySymbol>.GetInstance(); bool allowRefOmittedArguments = receiverOpt.IsExpressionOfComImportType(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.OverloadResolution.PropertyOverloadResolution(propertyGroup, receiverOpt, analyzedArguments, overloadResolutionResult, allowRefOmittedArguments, ref useSiteInfo); diagnostics.Add(syntax, useSiteInfo); BoundExpression propertyAccess; if (analyzedArguments.HasDynamicArgument && overloadResolutionResult.HasAnyApplicableMember) { // Note that the runtime binder may consider candidates that haven't passed compile-time final validation // and an ambiguity error may be reported. Also additional checks are performed in runtime final validation // that are not performed at compile-time. // Only if the set of final applicable candidates is empty we know for sure the call will fail at runtime. var finalApplicableCandidates = GetCandidatesPassingFinalValidation(syntax, overloadResolutionResult, receiverOpt, default(ImmutableArray<TypeWithAnnotations>), diagnostics); overloadResolutionResult.Free(); return BindDynamicIndexer(syntax, receiverOpt, analyzedArguments, finalApplicableCandidates, diagnostics); } ImmutableArray<string> argumentNames = analyzedArguments.GetNames(); ImmutableArray<RefKind> argumentRefKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); if (!overloadResolutionResult.Succeeded) { // If the arguments had an error reported about them then suppress further error // reporting for overload resolution. ImmutableArray<PropertySymbol> candidates = propertyGroup.ToImmutable(); if (!analyzedArguments.HasErrors) { if (TryBindIndexOrRangeIndexer( syntax, receiverOpt, analyzedArguments, diagnostics, out var patternIndexerAccess)) { return patternIndexerAccess; } else { // Dev10 uses the "this" keyword as the method name for indexers. var candidate = candidates[0]; var name = candidate.IsIndexer ? SyntaxFacts.GetText(SyntaxKind.ThisKeyword) : candidate.Name; overloadResolutionResult.ReportDiagnostics( binder: this, location: syntax.Location, nodeOpt: syntax, diagnostics: diagnostics, name: name, receiver: null, invokedExpression: null, arguments: analyzedArguments, memberGroup: candidates, typeContainingConstructor: null, delegateTypeBeingInvoked: null); } } ImmutableArray<BoundExpression> arguments = BuildArgumentsForErrorRecovery(analyzedArguments, candidates); // A bad BoundIndexerAccess containing an ErrorPropertySymbol will produce better flow analysis results than // a BoundBadExpression containing the candidate indexers. PropertySymbol property = (candidates.Length == 1) ? candidates[0] : CreateErrorPropertySymbol(candidates); propertyAccess = BoundIndexerAccess.ErrorAccess( syntax, receiverOpt, property, arguments, argumentNames, argumentRefKinds, candidates); } else { MemberResolutionResult<PropertySymbol> resolutionResult = overloadResolutionResult.ValidResult; PropertySymbol property = resolutionResult.Member; RefKind? receiverRefKind = receiverOpt?.GetRefKind(); uint receiverEscapeScope = property.RequiresInstanceReceiver && receiverOpt != null ? receiverRefKind?.IsWritableReference() == true ? GetRefEscape(receiverOpt, LocalScopeDepth) : GetValEscape(receiverOpt, LocalScopeDepth) : Binder.ExternalScope; this.CoerceArguments<PropertySymbol>(resolutionResult, analyzedArguments.Arguments, diagnostics, receiverOpt?.Type, receiverRefKind, receiverEscapeScope); var isExpanded = resolutionResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm; var argsToParams = resolutionResult.Result.ArgsToParamsOpt; ReportDiagnosticsIfObsolete(diagnostics, property, syntax, hasBaseReceiver: receiverOpt != null && receiverOpt.Kind == BoundKind.BaseReference); // Make sure that the result of overload resolution is valid. var gotError = MemberGroupFinalValidationAccessibilityChecks(receiverOpt, property, syntax, diagnostics, invokedAsExtensionMethod: false); var receiver = ReplaceTypeOrValueReceiver(receiverOpt, property.IsStatic, diagnostics); if (!gotError && receiver != null && receiver.Kind == BoundKind.ThisReference && receiver.WasCompilerGenerated) { gotError = IsRefOrOutThisParameterCaptured(syntax, diagnostics); } var arguments = analyzedArguments.Arguments.ToImmutable(); if (!gotError) { gotError = !CheckInvocationArgMixing( syntax, property, receiver, property.Parameters, arguments, argsToParams, this.LocalScopeDepth, diagnostics); } // Note that we do not bind default arguments here, because at this point we do not know whether // the indexer is being used in a 'get', or 'set', or 'get+set' (compound assignment) context. propertyAccess = new BoundIndexerAccess( syntax, receiver, property, arguments, argumentNames, argumentRefKinds, isExpanded, argsToParams, defaultArguments: default, property.Type, gotError); } overloadResolutionResult.Free(); return propertyAccess; } private bool TryBindIndexOrRangeIndexer( SyntaxNode syntax, BoundExpression receiverOpt, AnalyzedArguments arguments, BindingDiagnosticBag diagnostics, out BoundIndexOrRangePatternIndexerAccess patternIndexerAccess) { patternIndexerAccess = null; // Verify a few things up-front, namely that we have a single argument // to this indexer that has an Index or Range type and that there is // a real receiver with a known type if (arguments.Arguments.Count != 1) { return false; } var argument = arguments.Arguments[0]; var argType = argument.Type; bool argIsIndex = TypeSymbol.Equals(argType, Compilation.GetWellKnownType(WellKnownType.System_Index), TypeCompareKind.ConsiderEverything); bool argIsRange = !argIsIndex && TypeSymbol.Equals(argType, Compilation.GetWellKnownType(WellKnownType.System_Range), TypeCompareKind.ConsiderEverything); if ((!argIsIndex && !argIsRange) || !(receiverOpt?.Type is TypeSymbol receiverType)) { return false; } // SPEC: // An indexer invocation with a single argument of System.Index or System.Range will // succeed if the receiver type conforms to an appropriate pattern, namely // 1. The receiver type's original definition has an accessible property getter that returns // an int and has the name Length or Count // 2. For Index: Has an accessible indexer with a single int parameter // For Range: Has an accessible Slice method that takes two int parameters PropertySymbol lengthOrCountProperty; var lookupResult = LookupResult.GetInstance(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; // Look for Length first if (!tryLookupLengthOrCount(WellKnownMemberNames.LengthPropertyName, out lengthOrCountProperty) && !tryLookupLengthOrCount(WellKnownMemberNames.CountPropertyName, out lengthOrCountProperty)) { return false; } Debug.Assert(lengthOrCountProperty is { }); if (argIsIndex) { // Look for `T this[int i]` indexer LookupMembersInType( lookupResult, receiverType, WellKnownMemberNames.Indexer, arity: 0, basesBeingResolved: null, LookupOptions.Default, originalBinder: this, diagnose: false, ref discardedUseSiteInfo); if (lookupResult.IsMultiViable) { foreach (var candidate in lookupResult.Symbols) { if (!candidate.IsStatic && candidate is PropertySymbol property && IsAccessible(property, ref discardedUseSiteInfo) && property.OriginalDefinition is { ParameterCount: 1 } original && isIntNotByRef(original.Parameters[0])) { CheckImplicitThisCopyInReadOnlyMember(receiverOpt, lengthOrCountProperty.GetMethod, diagnostics); ReportDiagnosticsIfObsolete(diagnostics, property, syntax, hasBaseReceiver: false); ReportDiagnosticsIfObsolete(diagnostics, lengthOrCountProperty, syntax, hasBaseReceiver: false); // note: implicit copy check on the indexer accessor happens in CheckPropertyValueKind patternIndexerAccess = new BoundIndexOrRangePatternIndexerAccess( syntax, receiverOpt, lengthOrCountProperty, property, BindToNaturalType(argument, diagnostics), property.Type); break; } } } } else if (receiverType.SpecialType == SpecialType.System_String) { Debug.Assert(argIsRange); // Look for Substring var substring = (MethodSymbol)Compilation.GetSpecialTypeMember(SpecialMember.System_String__Substring); if (substring is object) { patternIndexerAccess = new BoundIndexOrRangePatternIndexerAccess( syntax, receiverOpt, lengthOrCountProperty, substring, BindToNaturalType(argument, diagnostics), substring.ReturnType); checkWellKnown(WellKnownMember.System_Range__get_Start); checkWellKnown(WellKnownMember.System_Range__get_End); } } else { Debug.Assert(argIsRange); // Look for `T Slice(int, int)` indexer LookupMembersInType( lookupResult, receiverType, WellKnownMemberNames.SliceMethodName, arity: 0, basesBeingResolved: null, LookupOptions.Default, originalBinder: this, diagnose: false, ref discardedUseSiteInfo); if (lookupResult.IsMultiViable) { foreach (var candidate in lookupResult.Symbols) { if (!candidate.IsStatic && IsAccessible(candidate, ref discardedUseSiteInfo) && candidate is MethodSymbol method && method.OriginalDefinition is var original && original.ParameterCount == 2 && isIntNotByRef(original.Parameters[0]) && isIntNotByRef(original.Parameters[1])) { CheckImplicitThisCopyInReadOnlyMember(receiverOpt, lengthOrCountProperty.GetMethod, diagnostics); CheckImplicitThisCopyInReadOnlyMember(receiverOpt, method, diagnostics); ReportDiagnosticsIfObsolete(diagnostics, method, syntax, hasBaseReceiver: false); ReportDiagnosticsIfObsolete(diagnostics, lengthOrCountProperty, syntax, hasBaseReceiver: false); patternIndexerAccess = new BoundIndexOrRangePatternIndexerAccess( syntax, receiverOpt, lengthOrCountProperty, method, BindToNaturalType(argument, diagnostics), method.ReturnType); checkWellKnown(WellKnownMember.System_Range__get_Start); checkWellKnown(WellKnownMember.System_Range__get_End); break; } } } } cleanup(lookupResult); if (patternIndexerAccess is null) { return false; } _ = MessageID.IDS_FeatureIndexOperator.CheckFeatureAvailability(diagnostics, syntax); checkWellKnown(WellKnownMember.System_Index__GetOffset); if (arguments.Names.Count > 0) { diagnostics.Add( argIsRange ? ErrorCode.ERR_ImplicitRangeIndexerWithName : ErrorCode.ERR_ImplicitIndexIndexerWithName, arguments.Names[0].GetValueOrDefault().Location); } return true; static void cleanup(LookupResult lookupResult) { lookupResult.Free(); } static bool isIntNotByRef(ParameterSymbol param) => param.Type.SpecialType == SpecialType.System_Int32 && param.RefKind == RefKind.None; void checkWellKnown(WellKnownMember member) { // Check required well-known member. They may not be needed // during lowering, but it's simpler to always require them to prevent // the user from getting surprising errors when optimizations fail _ = GetWellKnownTypeMember(member, diagnostics, syntax: syntax); } bool tryLookupLengthOrCount(string propertyName, out PropertySymbol valid) { LookupMembersInType( lookupResult, receiverType, propertyName, arity: 0, basesBeingResolved: null, LookupOptions.Default, originalBinder: this, diagnose: false, useSiteInfo: ref discardedUseSiteInfo); if (lookupResult.IsSingleViable && lookupResult.Symbols[0] is PropertySymbol property && property.GetOwnOrInheritedGetMethod()?.OriginalDefinition is MethodSymbol getMethod && getMethod.ReturnType.SpecialType == SpecialType.System_Int32 && getMethod.RefKind == RefKind.None && !getMethod.IsStatic && IsAccessible(getMethod, ref discardedUseSiteInfo)) { lookupResult.Clear(); valid = property; return true; } lookupResult.Clear(); valid = null; return false; } } private ErrorPropertySymbol CreateErrorPropertySymbol(ImmutableArray<PropertySymbol> propertyGroup) { TypeSymbol propertyType = GetCommonTypeOrReturnType(propertyGroup) ?? CreateErrorType(); var candidate = propertyGroup[0]; return new ErrorPropertySymbol(candidate.ContainingType, propertyType, candidate.Name, candidate.IsIndexer, candidate.IsIndexedProperty); } /// <summary> /// Perform lookup and overload resolution on methods defined directly on the class and any /// extension methods in scope. Lookup will occur for extension methods in all nested scopes /// as necessary until an appropriate method is found. If analyzedArguments is null, the first /// method group is returned, without overload resolution being performed. That method group /// will either be the methods defined on the receiver class directly (no extension methods) /// or the first set of extension methods. /// </summary> /// <param name="node">The node associated with the method group</param> /// <param name="analyzedArguments">The arguments of the invocation (or the delegate type, if a method group conversion)</param> /// <param name="isMethodGroupConversion">True if it is a method group conversion</param> /// <param name="useSiteInfo"></param> /// <param name="inferWithDynamic"></param> /// <param name="returnRefKind">If a method group conversion, the desired ref kind of the delegate</param> /// <param name="returnType">If a method group conversion, the desired return type of the delegate. /// May be null during inference if the return type of the delegate needs to be computed.</param> internal MethodGroupResolution ResolveMethodGroup( BoundMethodGroup node, AnalyzedArguments analyzedArguments, bool isMethodGroupConversion, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool inferWithDynamic = false, RefKind returnRefKind = default, TypeSymbol returnType = null, bool isFunctionPointerResolution = false, in CallingConventionInfo callingConventionInfo = default) { return ResolveMethodGroup( node, node.Syntax, node.Name, analyzedArguments, isMethodGroupConversion, ref useSiteInfo, inferWithDynamic: inferWithDynamic, returnRefKind: returnRefKind, returnType: returnType, isFunctionPointerResolution: isFunctionPointerResolution, callingConventionInfo: callingConventionInfo); } internal MethodGroupResolution ResolveMethodGroup( BoundMethodGroup node, SyntaxNode expression, string methodName, AnalyzedArguments analyzedArguments, bool isMethodGroupConversion, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool inferWithDynamic = false, bool allowUnexpandedForm = true, RefKind returnRefKind = default, TypeSymbol returnType = null, bool isFunctionPointerResolution = false, in CallingConventionInfo callingConventionInfo = default) { var methodResolution = ResolveMethodGroupInternal( node, expression, methodName, analyzedArguments, isMethodGroupConversion, ref useSiteInfo, inferWithDynamic: inferWithDynamic, allowUnexpandedForm: allowUnexpandedForm, returnRefKind: returnRefKind, returnType: returnType, isFunctionPointerResolution: isFunctionPointerResolution, callingConvention: callingConventionInfo); if (methodResolution.IsEmpty && !methodResolution.HasAnyErrors) { Debug.Assert(node.LookupError == null); var diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, useSiteInfo.AccumulatesDependencies); diagnostics.AddRange(methodResolution.Diagnostics); // Could still have use site warnings. BindMemberAccessReportError(node, diagnostics); // Note: no need to free `methodResolution`, we're transferring the pooled objects it owned return new MethodGroupResolution(methodResolution.MethodGroup, methodResolution.OtherSymbol, methodResolution.OverloadResolutionResult, methodResolution.AnalyzedArguments, methodResolution.ResultKind, diagnostics.ToReadOnlyAndFree()); } return methodResolution; } internal MethodGroupResolution ResolveMethodGroupForFunctionPointer( BoundMethodGroup methodGroup, AnalyzedArguments analyzedArguments, TypeSymbol returnType, RefKind returnRefKind, in CallingConventionInfo callingConventionInfo, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ResolveDefaultMethodGroup( methodGroup, analyzedArguments, isMethodGroupConversion: true, ref useSiteInfo, inferWithDynamic: false, allowUnexpandedForm: true, returnRefKind, returnType, isFunctionPointerResolution: true, callingConventionInfo); } private MethodGroupResolution ResolveMethodGroupInternal( BoundMethodGroup methodGroup, SyntaxNode expression, string methodName, AnalyzedArguments analyzedArguments, bool isMethodGroupConversion, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool inferWithDynamic = false, bool allowUnexpandedForm = true, RefKind returnRefKind = default, TypeSymbol returnType = null, bool isFunctionPointerResolution = false, in CallingConventionInfo callingConvention = default) { var methodResolution = ResolveDefaultMethodGroup( methodGroup, analyzedArguments, isMethodGroupConversion, ref useSiteInfo, inferWithDynamic, allowUnexpandedForm, returnRefKind, returnType, isFunctionPointerResolution, callingConvention); // If the method group's receiver is dynamic then there is no point in looking for extension methods; // it's going to be a dynamic invocation. if (!methodGroup.SearchExtensionMethods || methodResolution.HasAnyApplicableMethod || methodGroup.MethodGroupReceiverIsDynamic()) { return methodResolution; } var extensionMethodResolution = BindExtensionMethod( expression, methodName, analyzedArguments, methodGroup.ReceiverOpt, methodGroup.TypeArgumentsOpt, isMethodGroupConversion, returnRefKind: returnRefKind, returnType: returnType, withDependencies: useSiteInfo.AccumulatesDependencies); bool preferExtensionMethodResolution = false; if (extensionMethodResolution.HasAnyApplicableMethod) { preferExtensionMethodResolution = true; } else if (extensionMethodResolution.IsEmpty) { preferExtensionMethodResolution = false; } else if (methodResolution.IsEmpty) { preferExtensionMethodResolution = true; } else { // At this point, both method group resolutions are non-empty but neither contains any applicable method. // Choose the MethodGroupResolution with the better (i.e. less worse) result kind. Debug.Assert(!methodResolution.HasAnyApplicableMethod); Debug.Assert(!extensionMethodResolution.HasAnyApplicableMethod); Debug.Assert(!methodResolution.IsEmpty); Debug.Assert(!extensionMethodResolution.IsEmpty); LookupResultKind methodResultKind = methodResolution.ResultKind; LookupResultKind extensionMethodResultKind = extensionMethodResolution.ResultKind; if (methodResultKind != extensionMethodResultKind && methodResultKind == extensionMethodResultKind.WorseResultKind(methodResultKind)) { preferExtensionMethodResolution = true; } } if (preferExtensionMethodResolution) { methodResolution.Free(); Debug.Assert(!extensionMethodResolution.IsEmpty); return extensionMethodResolution; //NOTE: the first argument of this MethodGroupResolution could be a BoundTypeOrValueExpression } extensionMethodResolution.Free(); return methodResolution; } private MethodGroupResolution ResolveDefaultMethodGroup( BoundMethodGroup node, AnalyzedArguments analyzedArguments, bool isMethodGroupConversion, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool inferWithDynamic = false, bool allowUnexpandedForm = true, RefKind returnRefKind = default, TypeSymbol returnType = null, bool isFunctionPointerResolution = false, in CallingConventionInfo callingConvention = default) { var methods = node.Methods; if (methods.Length == 0) { var method = node.LookupSymbolOpt as MethodSymbol; if ((object)method != null) { methods = ImmutableArray.Create(method); } } var sealedDiagnostics = ImmutableBindingDiagnostic<AssemblySymbol>.Empty; if (node.LookupError != null) { var diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false); Error(diagnostics, node.LookupError, node.NameSyntax); sealedDiagnostics = diagnostics.ToReadOnlyAndFree(); } if (methods.Length == 0) { return new MethodGroupResolution(node.LookupSymbolOpt, node.ResultKind, sealedDiagnostics); } var methodGroup = MethodGroup.GetInstance(); // NOTE: node.ReceiverOpt could be a BoundTypeOrValueExpression - users need to check. methodGroup.PopulateWithNonExtensionMethods(node.ReceiverOpt, methods, node.TypeArgumentsOpt, node.ResultKind, node.LookupError); if (node.LookupError != null) { return new MethodGroupResolution(methodGroup, sealedDiagnostics); } // Arguments will be null if the caller is resolving to the first available // method group, regardless of arguments, when the signature cannot // be inferred. (In the error case of o.M = null; for instance.) if (analyzedArguments == null) { return new MethodGroupResolution(methodGroup, sealedDiagnostics); } else { var result = OverloadResolutionResult<MethodSymbol>.GetInstance(); bool allowRefOmittedArguments = methodGroup.Receiver.IsExpressionOfComImportType(); OverloadResolution.MethodInvocationOverloadResolution( methodGroup.Methods, methodGroup.TypeArguments, methodGroup.Receiver, analyzedArguments, result, ref useSiteInfo, isMethodGroupConversion, allowRefOmittedArguments, inferWithDynamic, allowUnexpandedForm, returnRefKind, returnType, isFunctionPointerResolution, callingConvention); // Note: the MethodGroupResolution instance is responsible for freeing its copy of analyzed arguments return new MethodGroupResolution(methodGroup, null, result, AnalyzedArguments.GetInstance(analyzedArguments), methodGroup.ResultKind, sealedDiagnostics); } } #nullable enable internal NamedTypeSymbol? GetMethodGroupDelegateType(BoundMethodGroup node, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (GetUniqueSignatureFromMethodGroup(node) is { } method && GetMethodGroupOrLambdaDelegateType(method.RefKind, method.ReturnsVoid ? default : method.ReturnTypeWithAnnotations, method.ParameterRefKinds, method.ParameterTypesWithAnnotations, ref useSiteInfo) is { } delegateType) { return delegateType; } return null; } /// <summary> /// Returns one of the methods from the method group if all methods in the method group /// have the same signature, ignoring parameter names and custom modifiers. The particular /// method returned is not important since the caller is interested in the signature only. /// </summary> private MethodSymbol? GetUniqueSignatureFromMethodGroup(BoundMethodGroup node) { MethodSymbol? method = null; foreach (var m in node.Methods) { switch (node.ReceiverOpt) { case BoundTypeExpression: if (!m.IsStatic) continue; break; case BoundThisReference { WasCompilerGenerated: true }: break; default: if (m.IsStatic) continue; break; } if (!isCandidateUnique(ref method, m)) { return null; } } if (node.SearchExtensionMethods) { var receiver = node.ReceiverOpt!; foreach (var scope in new ExtensionMethodScopes(this)) { var methodGroup = MethodGroup.GetInstance(); PopulateExtensionMethodsFromSingleBinder(scope, methodGroup, node.Syntax, receiver, node.Name, node.TypeArgumentsOpt, BindingDiagnosticBag.Discarded); foreach (var m in methodGroup.Methods) { if (m.ReduceExtensionMethod(receiver.Type, Compilation) is { } reduced && !isCandidateUnique(ref method, reduced)) { methodGroup.Free(); return null; } } methodGroup.Free(); } } if (method is null) { return null; } int n = node.TypeArgumentsOpt.IsDefaultOrEmpty ? 0 : node.TypeArgumentsOpt.Length; if (method.Arity != n) { return null; } else if (n > 0) { method = method.ConstructedFrom.Construct(node.TypeArgumentsOpt); } return method; static bool isCandidateUnique(ref MethodSymbol? method, MethodSymbol candidate) { if (method is null) { method = candidate; return true; } if (MemberSignatureComparer.MethodGroupSignatureComparer.Equals(method, candidate)) { return true; } method = null; return false; } } // This method was adapted from LoweredDynamicOperationFactory.GetDelegateType(). // Consider using that method directly since it also synthesizes delegates if necessary. internal NamedTypeSymbol? GetMethodGroupOrLambdaDelegateType( RefKind returnRefKind, TypeWithAnnotations returnTypeOpt, ImmutableArray<RefKind> parameterRefKinds, ImmutableArray<TypeWithAnnotations> parameterTypes, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(returnTypeOpt.Type?.IsVoidType() != true); // expecting !returnTypeOpt.HasType rather than System.Void if (returnRefKind == RefKind.None && (parameterRefKinds.IsDefault || parameterRefKinds.All(refKind => refKind == RefKind.None))) { var wkDelegateType = returnTypeOpt.HasType ? WellKnownTypes.GetWellKnownFunctionDelegate(invokeArgumentCount: parameterTypes.Length) : WellKnownTypes.GetWellKnownActionDelegate(invokeArgumentCount: parameterTypes.Length); if (wkDelegateType != WellKnownType.Unknown) { var delegateType = Compilation.GetWellKnownType(wkDelegateType); delegateType.AddUseSiteInfo(ref useSiteInfo); if (returnTypeOpt.HasType) { parameterTypes = parameterTypes.Add(returnTypeOpt); } if (parameterTypes.Length == 0) { return delegateType; } if (checkConstraints(Compilation, Conversions, delegateType, parameterTypes)) { return delegateType.Construct(parameterTypes); } } } return null; static bool checkConstraints(CSharpCompilation compilation, ConversionsBase conversions, NamedTypeSymbol delegateType, ImmutableArray<TypeWithAnnotations> typeArguments) { var diagnosticsBuilder = ArrayBuilder<TypeParameterDiagnosticInfo>.GetInstance(); var typeParameters = delegateType.TypeParameters; var substitution = new TypeMap(typeParameters, typeArguments); ArrayBuilder<TypeParameterDiagnosticInfo>? useSiteDiagnosticsBuilder = null; var result = delegateType.CheckConstraints( new ConstraintsHelper.CheckConstraintsArgs(compilation, conversions, includeNullability: false, NoLocation.Singleton, diagnostics: null, template: CompoundUseSiteInfo<AssemblySymbol>.Discarded), substitution, typeParameters, typeArguments, diagnosticsBuilder, nullabilityDiagnosticsBuilderOpt: null, ref useSiteDiagnosticsBuilder); diagnosticsBuilder.Free(); return result; } } #nullable disable internal static bool ReportDelegateInvokeUseSiteDiagnostic(BindingDiagnosticBag diagnostics, TypeSymbol possibleDelegateType, Location location = null, SyntaxNode node = null) { Debug.Assert((location == null) ^ (node == null)); if (!possibleDelegateType.IsDelegateType()) { return false; } MethodSymbol invoke = possibleDelegateType.DelegateInvokeMethod(); if ((object)invoke == null) { diagnostics.Add(new CSDiagnosticInfo(ErrorCode.ERR_InvalidDelegateType, possibleDelegateType), location ?? node.Location); return true; } UseSiteInfo<AssemblySymbol> info = invoke.GetUseSiteInfo(); diagnostics.AddDependencies(info); DiagnosticInfo diagnosticInfo = info.DiagnosticInfo; if (diagnosticInfo == null) { return false; } if (location == null) { location = node.Location; } if (diagnosticInfo.Code == (int)ErrorCode.ERR_InvalidDelegateType) { diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_InvalidDelegateType, possibleDelegateType), location)); return true; } return Symbol.ReportUseSiteDiagnostic(diagnosticInfo, diagnostics, location); } private BoundConditionalAccess BindConditionalAccessExpression(ConditionalAccessExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression receiver = BindConditionalAccessReceiver(node, diagnostics); var conditionalAccessBinder = new BinderWithConditionalReceiver(this, receiver); var access = conditionalAccessBinder.BindValue(node.WhenNotNull, diagnostics, BindValueKind.RValue); if (receiver.HasAnyErrors || access.HasAnyErrors) { return new BoundConditionalAccess(node, receiver, access, CreateErrorType(), hasErrors: true); } var receiverType = receiver.Type; Debug.Assert((object)receiverType != null); // access cannot be a method group if (access.Kind == BoundKind.MethodGroup) { return GenerateBadConditionalAccessNodeError(node, receiver, access, diagnostics); } var accessType = access.Type; // access cannot have no type if ((object)accessType == null) { return GenerateBadConditionalAccessNodeError(node, receiver, access, diagnostics); } // The resulting type must be either a reference type T or Nullable<T> // Therefore we must reject cases resulting in types that are not reference types and cannot be lifted into nullable. // - access cannot have unconstrained generic type // - access cannot be a pointer // - access cannot be a restricted type if ((!accessType.IsReferenceType && !accessType.IsValueType) || accessType.IsPointerOrFunctionPointer() || accessType.IsRestrictedType()) { // Result type of the access is void when result value cannot be made nullable. // For improved diagnostics we detect the cases where the value will be used and produce a // more specific (though not technically correct) diagnostic here: // "Error CS0023: Operator '?' cannot be applied to operand of type 'T'" bool resultIsUsed = true; CSharpSyntaxNode parent = node.Parent; if (parent != null) { switch (parent.Kind()) { case SyntaxKind.ExpressionStatement: resultIsUsed = ((ExpressionStatementSyntax)parent).Expression != node; break; case SyntaxKind.SimpleLambdaExpression: resultIsUsed = (((SimpleLambdaExpressionSyntax)parent).Body != node) || MethodOrLambdaRequiresValue(ContainingMemberOrLambda, Compilation); break; case SyntaxKind.ParenthesizedLambdaExpression: resultIsUsed = (((ParenthesizedLambdaExpressionSyntax)parent).Body != node) || MethodOrLambdaRequiresValue(ContainingMemberOrLambda, Compilation); break; case SyntaxKind.ArrowExpressionClause: resultIsUsed = (((ArrowExpressionClauseSyntax)parent).Expression != node) || MethodOrLambdaRequiresValue(ContainingMemberOrLambda, Compilation); break; case SyntaxKind.ForStatement: // Incrementors and Initializers doesn't have to produce a value var loop = (ForStatementSyntax)parent; resultIsUsed = !loop.Incrementors.Contains(node) && !loop.Initializers.Contains(node); break; } } if (resultIsUsed) { return GenerateBadConditionalAccessNodeError(node, receiver, access, diagnostics); } accessType = GetSpecialType(SpecialType.System_Void, diagnostics, node); } // if access has value type, the type of the conditional access is nullable of that // https://github.com/dotnet/roslyn/issues/35075: The test `accessType.IsValueType && !accessType.IsNullableType()` // should probably be `accessType.IsNonNullableValueType()` if (accessType.IsValueType && !accessType.IsNullableType() && !accessType.IsVoidType()) { accessType = GetSpecialType(SpecialType.System_Nullable_T, diagnostics, node).Construct(accessType); } return new BoundConditionalAccess(node, receiver, access, accessType); } internal static bool MethodOrLambdaRequiresValue(Symbol symbol, CSharpCompilation compilation) { return symbol is MethodSymbol method && !method.ReturnsVoid && !method.IsAsyncEffectivelyReturningTask(compilation); } private BoundConditionalAccess GenerateBadConditionalAccessNodeError(ConditionalAccessExpressionSyntax node, BoundExpression receiver, BoundExpression access, BindingDiagnosticBag diagnostics) { var operatorToken = node.OperatorToken; // TODO: need a special ERR for this. // conditional access is not really a binary operator. DiagnosticInfo diagnosticInfo = new CSDiagnosticInfo(ErrorCode.ERR_BadUnaryOp, SyntaxFacts.GetText(operatorToken.Kind()), access.Display); diagnostics.Add(new CSDiagnostic(diagnosticInfo, operatorToken.GetLocation())); receiver = BadExpression(receiver.Syntax, receiver); return new BoundConditionalAccess(node, receiver, access, CreateErrorType(), hasErrors: true); } private BoundExpression BindMemberBindingExpression(MemberBindingExpressionSyntax node, bool invoked, bool indexed, BindingDiagnosticBag diagnostics) { BoundExpression receiver = GetReceiverForConditionalBinding(node, diagnostics); var memberAccess = BindMemberAccessWithBoundLeft(node, receiver, node.Name, node.OperatorToken, invoked, indexed, diagnostics); return memberAccess; } private BoundExpression BindElementBindingExpression(ElementBindingExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression receiver = GetReceiverForConditionalBinding(node, diagnostics); var memberAccess = BindElementAccess(node, receiver, node.ArgumentList, diagnostics); return memberAccess; } private static CSharpSyntaxNode GetConditionalReceiverSyntax(ConditionalAccessExpressionSyntax node) { Debug.Assert(node != null); Debug.Assert(node.Expression != null); var receiver = node.Expression; while (receiver.IsKind(SyntaxKind.ParenthesizedExpression)) { receiver = ((ParenthesizedExpressionSyntax)receiver).Expression; Debug.Assert(receiver != null); } return receiver; } private BoundExpression GetReceiverForConditionalBinding(ExpressionSyntax binding, BindingDiagnosticBag diagnostics) { var conditionalAccessNode = SyntaxFactory.FindConditionalAccessNodeForBinding(binding); Debug.Assert(conditionalAccessNode != null); BoundExpression receiver = this.ConditionalReceiverExpression; if (receiver?.Syntax != GetConditionalReceiverSyntax(conditionalAccessNode)) { // this can happen when semantic model binds parts of a Call or a broken access expression. // We may not have receiver available in such cases. // Not a problem - we only need receiver to get its type and we can bind it here. receiver = BindConditionalAccessReceiver(conditionalAccessNode, diagnostics); } // create surrogate receiver var receiverType = receiver.Type; if (receiverType?.IsNullableType() == true) { receiverType = receiverType.GetNullableUnderlyingType(); } receiver = new BoundConditionalReceiver(receiver.Syntax, 0, receiverType ?? CreateErrorType(), hasErrors: receiver.HasErrors) { WasCompilerGenerated = true }; return receiver; } private BoundExpression BindConditionalAccessReceiver(ConditionalAccessExpressionSyntax node, BindingDiagnosticBag diagnostics) { var receiverSyntax = node.Expression; var receiver = BindRValueWithoutTargetType(receiverSyntax, diagnostics); receiver = MakeMemberAccessValue(receiver, diagnostics); if (receiver.HasAnyErrors) { return receiver; } var operatorToken = node.OperatorToken; if (receiver.Kind == BoundKind.UnboundLambda) { var msgId = ((UnboundLambda)receiver).MessageID; DiagnosticInfo diagnosticInfo = new CSDiagnosticInfo(ErrorCode.ERR_BadUnaryOp, SyntaxFacts.GetText(operatorToken.Kind()), msgId.Localize()); diagnostics.Add(new CSDiagnostic(diagnosticInfo, node.Location)); return BadExpression(receiverSyntax, receiver); } var receiverType = receiver.Type; // Can't dot into the null literal or anything that has no type if ((object)receiverType == null) { Error(diagnostics, ErrorCode.ERR_BadUnaryOp, operatorToken.GetLocation(), operatorToken.Text, receiver.Display); return BadExpression(receiverSyntax, receiver); } // No member accesses on void if (receiverType.IsVoidType()) { Error(diagnostics, ErrorCode.ERR_BadUnaryOp, operatorToken.GetLocation(), operatorToken.Text, receiverType); return BadExpression(receiverSyntax, receiver); } if (receiverType.IsValueType && !receiverType.IsNullableType()) { // must be nullable or reference type Error(diagnostics, ErrorCode.ERR_BadUnaryOp, operatorToken.GetLocation(), operatorToken.Text, receiverType); return BadExpression(receiverSyntax, receiver); } return receiver; } } }
// Licensed to the .NET Foundation under one or more 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.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This portion of the binder converts an <see cref="ExpressionSyntax"/> into a <see cref="BoundExpression"/>. /// </summary> internal partial class Binder { /// <summary> /// Determines whether "this" reference is available within the current context. /// </summary> /// <param name="isExplicit">The reference was explicitly specified in syntax.</param> /// <param name="inStaticContext">True if "this" is not available due to the current method/property/field initializer being static.</param> /// <returns>True if a reference to "this" is available.</returns> internal bool HasThis(bool isExplicit, out bool inStaticContext) { var memberOpt = this.ContainingMemberOrLambda?.ContainingNonLambdaMember(); if (memberOpt?.IsStatic == true) { inStaticContext = memberOpt.Kind == SymbolKind.Field || memberOpt.Kind == SymbolKind.Method || memberOpt.Kind == SymbolKind.Property; return false; } inStaticContext = false; if (InConstructorInitializer || InAttributeArgument) { return false; } var containingType = memberOpt?.ContainingType; bool inTopLevelScriptMember = (object)containingType != null && containingType.IsScriptClass; // "this" is not allowed in field initializers (that are not script variable initializers): if (InFieldInitializer && !inTopLevelScriptMember) { return false; } // top-level script code only allows implicit "this" reference: return !inTopLevelScriptMember || !isExplicit; } internal bool InFieldInitializer { get { return this.Flags.Includes(BinderFlags.FieldInitializer); } } internal bool InParameterDefaultValue { get { return this.Flags.Includes(BinderFlags.ParameterDefaultValue); } } protected bool InConstructorInitializer { get { return this.Flags.Includes(BinderFlags.ConstructorInitializer); } } internal bool InAttributeArgument { get { return this.Flags.Includes(BinderFlags.AttributeArgument); } } internal bool InCref { get { return this.Flags.Includes(BinderFlags.Cref); } } protected bool InCrefButNotParameterOrReturnType { get { return InCref && !this.Flags.Includes(BinderFlags.CrefParameterOrReturnType); } } /// <summary> /// Returns true if the node is in a position where an unbound type /// such as (C&lt;,&gt;) is allowed. /// </summary> protected virtual bool IsUnboundTypeAllowed(GenericNameSyntax syntax) { return Next.IsUnboundTypeAllowed(syntax); } /// <summary> /// Generates a new <see cref="BoundBadExpression"/> with no known type /// </summary> private BoundBadExpression BadExpression(SyntaxNode syntax) { return BadExpression(syntax, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty); } /// <summary> /// Generates a new <see cref="BoundBadExpression"/> with no known type, and the given bound child. /// </summary> private BoundBadExpression BadExpression(SyntaxNode syntax, BoundExpression childNode) { return BadExpression(syntax, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, childNode); } /// <summary> /// Generates a new <see cref="BoundBadExpression"/> with no known type, and the given bound children. /// </summary> private BoundBadExpression BadExpression(SyntaxNode syntax, ImmutableArray<BoundExpression> childNodes) { return BadExpression(syntax, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, childNodes); } /// <summary> /// Generates a new <see cref="BoundBadExpression"/> with no known type, given lookup resultKind. /// </summary> protected BoundBadExpression BadExpression(SyntaxNode syntax, LookupResultKind lookupResultKind) { return BadExpression(syntax, lookupResultKind, ImmutableArray<Symbol>.Empty); } /// <summary> /// Generates a new <see cref="BoundBadExpression"/> with no known type, given lookup resultKind and the given bound child. /// </summary> protected BoundBadExpression BadExpression(SyntaxNode syntax, LookupResultKind lookupResultKind, BoundExpression childNode) { return BadExpression(syntax, lookupResultKind, ImmutableArray<Symbol>.Empty, childNode); } /// <summary> /// Generates a new <see cref="BoundBadExpression"/> with no known type, given lookupResultKind and given symbols for GetSemanticInfo API. /// </summary> private BoundBadExpression BadExpression(SyntaxNode syntax, LookupResultKind resultKind, ImmutableArray<Symbol> symbols) { return new BoundBadExpression(syntax, resultKind, symbols, ImmutableArray<BoundExpression>.Empty, CreateErrorType()); } /// <summary> /// Generates a new <see cref="BoundBadExpression"/> with no known type, given lookupResultKind and given symbols for GetSemanticInfo API, /// and the given bound child. /// </summary> private BoundBadExpression BadExpression(SyntaxNode syntax, LookupResultKind resultKind, ImmutableArray<Symbol> symbols, BoundExpression childNode) { return new BoundBadExpression(syntax, resultKind, symbols, ImmutableArray.Create(BindToTypeForErrorRecovery(childNode)), CreateErrorType()); } /// <summary> /// Generates a new <see cref="BoundBadExpression"/> with no known type, given lookupResultKind and given symbols for GetSemanticInfo API, /// and the given bound children. /// </summary> private BoundBadExpression BadExpression(SyntaxNode syntax, LookupResultKind resultKind, ImmutableArray<Symbol> symbols, ImmutableArray<BoundExpression> childNodes, bool wasCompilerGenerated = false) { return new BoundBadExpression(syntax, resultKind, symbols, childNodes.SelectAsArray((e, self) => self.BindToTypeForErrorRecovery(e), this), CreateErrorType()) { WasCompilerGenerated = wasCompilerGenerated }; } /// <summary> /// Helper method to generate a bound expression with HasErrors set to true. /// Returned bound expression is guaranteed to have a non-null type, except when <paramref name="expr"/> is an unbound lambda. /// If <paramref name="expr"/> already has errors and meets the above type requirements, then it is returned unchanged. /// Otherwise, if <paramref name="expr"/> is a BoundBadExpression, then it is updated with the <paramref name="resultKind"/> and non-null type. /// Otherwise, a new <see cref="BoundBadExpression"/> wrapping <paramref name="expr"/> is returned. /// </summary> /// <remarks> /// Returned expression need not be a <see cref="BoundBadExpression"/>, but is guaranteed to have HasErrors set to true. /// </remarks> private BoundExpression ToBadExpression(BoundExpression expr, LookupResultKind resultKind = LookupResultKind.Empty) { Debug.Assert(expr != null); Debug.Assert(resultKind != LookupResultKind.Viable); TypeSymbol resultType = expr.Type; BoundKind exprKind = expr.Kind; if (expr.HasAnyErrors && ((object)resultType != null || exprKind == BoundKind.UnboundLambda || exprKind == BoundKind.DefaultLiteral)) { return expr; } if (exprKind == BoundKind.BadExpression) { var badExpression = (BoundBadExpression)expr; return badExpression.Update(resultKind, badExpression.Symbols, badExpression.ChildBoundNodes, resultType); } else { ArrayBuilder<Symbol> symbols = ArrayBuilder<Symbol>.GetInstance(); expr.GetExpressionSymbols(symbols, parent: null, binder: this); return new BoundBadExpression( expr.Syntax, resultKind, symbols.ToImmutableAndFree(), ImmutableArray.Create(BindToTypeForErrorRecovery(expr)), resultType ?? CreateErrorType()); } } internal NamedTypeSymbol CreateErrorType(string name = "") { return new ExtendedErrorTypeSymbol(this.Compilation, name, arity: 0, errorInfo: null, unreported: false); } /// <summary> /// Bind the expression and verify the expression matches the combination of lvalue and /// rvalue requirements given by valueKind. If the expression was bound successfully, but /// did not meet the requirements, the return value will be a <see cref="BoundBadExpression"/> that /// (typically) wraps the subexpression. /// </summary> internal BoundExpression BindValue(ExpressionSyntax node, BindingDiagnosticBag diagnostics, BindValueKind valueKind) { var result = this.BindExpression(node, diagnostics: diagnostics, invoked: false, indexed: false); return CheckValue(result, valueKind, diagnostics); } internal BoundExpression BindRValueWithoutTargetType(ExpressionSyntax node, BindingDiagnosticBag diagnostics, bool reportNoTargetType = true) { return BindToNaturalType(BindValue(node, diagnostics, BindValueKind.RValue), diagnostics, reportNoTargetType); } /// <summary> /// When binding a switch case's expression, it is possible that it resolves to a type (technically, a type pattern). /// This implementation permits either an rvalue or a BoundTypeExpression. /// </summary> internal BoundExpression BindTypeOrRValue(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { var valueOrType = BindExpression(node, diagnostics: diagnostics, invoked: false, indexed: false); if (valueOrType.Kind == BoundKind.TypeExpression) { // In the Color Color case (Kind == BoundKind.TypeOrValueExpression), we treat it as a value // by not entering this if statement return valueOrType; } return CheckValue(valueOrType, BindValueKind.RValue, diagnostics); } internal BoundExpression BindToTypeForErrorRecovery(BoundExpression expression, TypeSymbol type = null) { if (expression is null) return null; var result = !expression.NeedsToBeConverted() ? expression : type is null ? BindToNaturalType(expression, BindingDiagnosticBag.Discarded, reportNoTargetType: false) : GenerateConversionForAssignment(type, expression, BindingDiagnosticBag.Discarded); return result; } /// <summary> /// Bind an rvalue expression to its natural type. For example, a switch expression that has not been /// converted to another type has to be converted to its own natural type by applying a conversion to /// that type to each of the arms of the switch expression. This method is a bottleneck for ensuring /// that such a conversion occurs when needed. It also handles tuple expressions which need to be /// converted to their own natural type because they may contain switch expressions. /// </summary> internal BoundExpression BindToNaturalType(BoundExpression expression, BindingDiagnosticBag diagnostics, bool reportNoTargetType = true) { if (!expression.NeedsToBeConverted()) return expression; BoundExpression result; switch (expression) { case BoundUnconvertedSwitchExpression expr: { var commonType = expr.Type; var exprSyntax = (SwitchExpressionSyntax)expr.Syntax; bool hasErrors = expression.HasErrors; if (commonType is null) { diagnostics.Add(ErrorCode.ERR_SwitchExpressionNoBestType, exprSyntax.SwitchKeyword.GetLocation()); commonType = CreateErrorType(); hasErrors = true; } result = ConvertSwitchExpression(expr, commonType, conversionIfTargetTyped: null, diagnostics, hasErrors); } break; case BoundUnconvertedConditionalOperator op: { TypeSymbol type = op.Type; bool hasErrors = op.HasErrors; if (type is null) { Debug.Assert(op.NoCommonTypeError != 0); type = CreateErrorType(); hasErrors = true; object trueArg = op.Consequence.Display; object falseArg = op.Alternative.Display; if (op.NoCommonTypeError == ErrorCode.ERR_InvalidQM && trueArg is Symbol trueSymbol && falseArg is Symbol falseSymbol) { // ERR_InvalidQM is an error that there is no conversion between the two types. They might be the same // type name from different assemblies, so we disambiguate the display. SymbolDistinguisher distinguisher = new SymbolDistinguisher(this.Compilation, trueSymbol, falseSymbol); trueArg = distinguisher.First; falseArg = distinguisher.Second; } diagnostics.Add(op.NoCommonTypeError, op.Syntax.Location, trueArg, falseArg); } result = ConvertConditionalExpression(op, type, conversionIfTargetTyped: null, diagnostics, hasErrors); } break; case BoundTupleLiteral sourceTuple: { var boundArgs = ArrayBuilder<BoundExpression>.GetInstance(sourceTuple.Arguments.Length); foreach (var arg in sourceTuple.Arguments) { boundArgs.Add(BindToNaturalType(arg, diagnostics, reportNoTargetType)); } result = new BoundConvertedTupleLiteral( sourceTuple.Syntax, sourceTuple, wasTargetTyped: false, boundArgs.ToImmutableAndFree(), sourceTuple.ArgumentNamesOpt, sourceTuple.InferredNamesOpt, sourceTuple.Type, // same type to keep original element names sourceTuple.HasErrors).WithSuppression(sourceTuple.IsSuppressed); } break; case BoundDefaultLiteral defaultExpr: { if (reportNoTargetType) { // In some cases, we let the caller report the error diagnostics.Add(ErrorCode.ERR_DefaultLiteralNoTargetType, defaultExpr.Syntax.GetLocation()); } result = new BoundDefaultExpression( defaultExpr.Syntax, targetType: null, defaultExpr.ConstantValue, CreateErrorType(), hasErrors: true).WithSuppression(defaultExpr.IsSuppressed); } break; case BoundStackAllocArrayCreation { Type: null } boundStackAlloc: { // This is a context in which the stackalloc could be either a pointer // or a span. For backward compatibility we treat it as a pointer. var type = new PointerTypeSymbol(TypeWithAnnotations.Create(boundStackAlloc.ElementType)); result = GenerateConversionForAssignment(type, boundStackAlloc, diagnostics); } break; case BoundUnconvertedObjectCreationExpression expr: { if (reportNoTargetType && !expr.HasAnyErrors) { diagnostics.Add(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, expr.Syntax.GetLocation(), expr.Display); } result = BindObjectCreationForErrorRecovery(expr, diagnostics); } break; case BoundUnconvertedInterpolatedString unconvertedInterpolatedString: { result = BindUnconvertedInterpolatedStringToString(unconvertedInterpolatedString, diagnostics); } break; default: result = expression; break; } return result?.WithWasConverted(); } private BoundExpression BindToInferredDelegateType(BoundExpression expr, BindingDiagnosticBag diagnostics) { var syntax = expr.Syntax; CheckFeatureAvailability(syntax, MessageID.IDS_FeatureInferredDelegateType, diagnostics); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var delegateType = expr switch { UnboundLambda unboundLambda => unboundLambda.InferDelegateType(ref useSiteInfo), BoundMethodGroup methodGroup => GetMethodGroupDelegateType(methodGroup, ref useSiteInfo), _ => throw ExceptionUtilities.UnexpectedValue(expr), }; diagnostics.Add(syntax, useSiteInfo); if (delegateType is null) { diagnostics.Add(ErrorCode.ERR_CannotInferDelegateType, syntax.GetLocation()); delegateType = CreateErrorType(); } return GenerateConversionForAssignment(delegateType, expr, diagnostics); } internal BoundExpression BindValueAllowArgList(ExpressionSyntax node, BindingDiagnosticBag diagnostics, BindValueKind valueKind) { var result = this.BindExpressionAllowArgList(node, diagnostics: diagnostics); return CheckValue(result, valueKind, diagnostics); } internal BoundFieldEqualsValue BindFieldInitializer( FieldSymbol field, EqualsValueClauseSyntax initializerOpt, BindingDiagnosticBag diagnostics) { Debug.Assert((object)this.ContainingMemberOrLambda == field); if (initializerOpt == null) { return null; } Binder initializerBinder = this.GetBinder(initializerOpt); Debug.Assert(initializerBinder != null); BoundExpression result = initializerBinder.BindVariableOrAutoPropInitializerValue(initializerOpt, RefKind.None, field.GetFieldType(initializerBinder.FieldsBeingBound).Type, diagnostics); return new BoundFieldEqualsValue(initializerOpt, field, initializerBinder.GetDeclaredLocalsForScope(initializerOpt), result); } internal BoundExpression BindVariableOrAutoPropInitializerValue( EqualsValueClauseSyntax initializerOpt, RefKind refKind, TypeSymbol varType, BindingDiagnosticBag diagnostics) { if (initializerOpt == null) { return null; } BindValueKind valueKind; ExpressionSyntax value; IsInitializerRefKindValid(initializerOpt, initializerOpt, refKind, diagnostics, out valueKind, out value); BoundExpression initializer = BindPossibleArrayInitializer(value, varType, valueKind, diagnostics); initializer = GenerateConversionForAssignment(varType, initializer, diagnostics); return initializer; } internal Binder CreateBinderForParameterDefaultValue( ParameterSymbol parameter, EqualsValueClauseSyntax defaultValueSyntax) { var binder = new LocalScopeBinder(this.WithContainingMemberOrLambda(parameter.ContainingSymbol).WithAdditionalFlags(BinderFlags.ParameterDefaultValue)); return new ExecutableCodeBinder(defaultValueSyntax, parameter.ContainingSymbol, binder); } internal BoundParameterEqualsValue BindParameterDefaultValue( EqualsValueClauseSyntax defaultValueSyntax, ParameterSymbol parameter, BindingDiagnosticBag diagnostics, out BoundExpression valueBeforeConversion) { Debug.Assert(this.InParameterDefaultValue); Debug.Assert(this.ContainingMemberOrLambda.Kind == SymbolKind.Method || this.ContainingMemberOrLambda.Kind == SymbolKind.Property); // UNDONE: The binding and conversion has to be executed in a checked context. Binder defaultValueBinder = this.GetBinder(defaultValueSyntax); Debug.Assert(defaultValueBinder != null); valueBeforeConversion = defaultValueBinder.BindValue(defaultValueSyntax.Value, diagnostics, BindValueKind.RValue); // Always generate the conversion, even if the expression is not convertible to the given type. // We want the erroneous conversion in the tree. var result = new BoundParameterEqualsValue(defaultValueSyntax, parameter, defaultValueBinder.GetDeclaredLocalsForScope(defaultValueSyntax), defaultValueBinder.GenerateConversionForAssignment(parameter.Type, valueBeforeConversion, diagnostics, isDefaultParameter: true)); return result; } internal BoundFieldEqualsValue BindEnumConstantInitializer( SourceEnumConstantSymbol symbol, EqualsValueClauseSyntax equalsValueSyntax, BindingDiagnosticBag diagnostics) { Binder initializerBinder = this.GetBinder(equalsValueSyntax); Debug.Assert(initializerBinder != null); var initializer = initializerBinder.BindValue(equalsValueSyntax.Value, diagnostics, BindValueKind.RValue); initializer = initializerBinder.GenerateConversionForAssignment(symbol.ContainingType.EnumUnderlyingType, initializer, diagnostics); return new BoundFieldEqualsValue(equalsValueSyntax, symbol, initializerBinder.GetDeclaredLocalsForScope(equalsValueSyntax), initializer); } public BoundExpression BindExpression(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { return BindExpression(node, diagnostics: diagnostics, invoked: false, indexed: false); } protected BoundExpression BindExpression(ExpressionSyntax node, BindingDiagnosticBag diagnostics, bool invoked, bool indexed) { BoundExpression expr = BindExpressionInternal(node, diagnostics, invoked, indexed); VerifyUnchecked(node, diagnostics, expr); if (expr.Kind == BoundKind.ArgListOperator) { // CS0226: An __arglist expression may only appear inside of a call or new expression Error(diagnostics, ErrorCode.ERR_IllegalArglist, node); expr = ToBadExpression(expr); } return expr; } // PERF: allowArgList is not a parameter because it is fairly uncommon case where arglists are allowed // so we do not want to pass that argument to every BindExpression which is often recursive // and extra arguments contribute to the stack size. protected BoundExpression BindExpressionAllowArgList(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression expr = BindExpressionInternal(node, diagnostics, invoked: false, indexed: false); VerifyUnchecked(node, diagnostics, expr); return expr; } private void VerifyUnchecked(ExpressionSyntax node, BindingDiagnosticBag diagnostics, BoundExpression expr) { if (!expr.HasAnyErrors && !IsInsideNameof) { TypeSymbol exprType = expr.Type; if ((object)exprType != null && exprType.IsUnsafe()) { ReportUnsafeIfNotAllowed(node, diagnostics); //CONSIDER: Return a bad expression so that HasErrors is true? } } } private BoundExpression BindExpressionInternal(ExpressionSyntax node, BindingDiagnosticBag diagnostics, bool invoked, bool indexed) { if (IsEarlyAttributeBinder && !EarlyWellKnownAttributeBinder.CanBeValidAttributeArgument(node, this)) { return BadExpression(node, LookupResultKind.NotAValue); } Debug.Assert(node != null); switch (node.Kind()) { case SyntaxKind.AnonymousMethodExpression: case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: return BindAnonymousFunction((AnonymousFunctionExpressionSyntax)node, diagnostics); case SyntaxKind.ThisExpression: return BindThis((ThisExpressionSyntax)node, diagnostics); case SyntaxKind.BaseExpression: return BindBase((BaseExpressionSyntax)node, diagnostics); case SyntaxKind.InvocationExpression: return BindInvocationExpression((InvocationExpressionSyntax)node, diagnostics); case SyntaxKind.ArrayInitializerExpression: return BindUnexpectedArrayInitializer((InitializerExpressionSyntax)node, diagnostics, ErrorCode.ERR_ArrayInitInBadPlace); case SyntaxKind.ArrayCreationExpression: return BindArrayCreationExpression((ArrayCreationExpressionSyntax)node, diagnostics); case SyntaxKind.ImplicitArrayCreationExpression: return BindImplicitArrayCreationExpression((ImplicitArrayCreationExpressionSyntax)node, diagnostics); case SyntaxKind.StackAllocArrayCreationExpression: return BindStackAllocArrayCreationExpression((StackAllocArrayCreationExpressionSyntax)node, diagnostics); case SyntaxKind.ImplicitStackAllocArrayCreationExpression: return BindImplicitStackAllocArrayCreationExpression((ImplicitStackAllocArrayCreationExpressionSyntax)node, diagnostics); case SyntaxKind.ObjectCreationExpression: return BindObjectCreationExpression((ObjectCreationExpressionSyntax)node, diagnostics); case SyntaxKind.ImplicitObjectCreationExpression: return BindImplicitObjectCreationExpression((ImplicitObjectCreationExpressionSyntax)node, diagnostics); case SyntaxKind.IdentifierName: case SyntaxKind.GenericName: return BindIdentifier((SimpleNameSyntax)node, invoked, indexed, diagnostics); case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: return BindMemberAccess((MemberAccessExpressionSyntax)node, invoked, indexed, diagnostics: diagnostics); case SyntaxKind.SimpleAssignmentExpression: return BindAssignment((AssignmentExpressionSyntax)node, diagnostics); case SyntaxKind.CastExpression: return BindCast((CastExpressionSyntax)node, diagnostics); case SyntaxKind.ElementAccessExpression: return BindElementAccess((ElementAccessExpressionSyntax)node, diagnostics); case SyntaxKind.AddExpression: case SyntaxKind.MultiplyExpression: case SyntaxKind.SubtractExpression: case SyntaxKind.DivideExpression: case SyntaxKind.ModuloExpression: case SyntaxKind.EqualsExpression: case SyntaxKind.NotEqualsExpression: case SyntaxKind.GreaterThanExpression: case SyntaxKind.LessThanExpression: case SyntaxKind.GreaterThanOrEqualExpression: case SyntaxKind.LessThanOrEqualExpression: case SyntaxKind.BitwiseAndExpression: case SyntaxKind.BitwiseOrExpression: case SyntaxKind.ExclusiveOrExpression: case SyntaxKind.LeftShiftExpression: case SyntaxKind.RightShiftExpression: return BindSimpleBinaryOperator((BinaryExpressionSyntax)node, diagnostics); case SyntaxKind.LogicalAndExpression: case SyntaxKind.LogicalOrExpression: return BindConditionalLogicalOperator((BinaryExpressionSyntax)node, diagnostics); case SyntaxKind.CoalesceExpression: return BindNullCoalescingOperator((BinaryExpressionSyntax)node, diagnostics); case SyntaxKind.ConditionalAccessExpression: return BindConditionalAccessExpression((ConditionalAccessExpressionSyntax)node, diagnostics); case SyntaxKind.MemberBindingExpression: return BindMemberBindingExpression((MemberBindingExpressionSyntax)node, invoked, indexed, diagnostics); case SyntaxKind.ElementBindingExpression: return BindElementBindingExpression((ElementBindingExpressionSyntax)node, diagnostics); case SyntaxKind.IsExpression: return BindIsOperator((BinaryExpressionSyntax)node, diagnostics); case SyntaxKind.AsExpression: return BindAsOperator((BinaryExpressionSyntax)node, diagnostics); case SyntaxKind.UnaryPlusExpression: case SyntaxKind.UnaryMinusExpression: case SyntaxKind.LogicalNotExpression: case SyntaxKind.BitwiseNotExpression: return BindUnaryOperator((PrefixUnaryExpressionSyntax)node, diagnostics); case SyntaxKind.IndexExpression: return BindFromEndIndexExpression((PrefixUnaryExpressionSyntax)node, diagnostics); case SyntaxKind.RangeExpression: return BindRangeExpression((RangeExpressionSyntax)node, diagnostics); case SyntaxKind.AddressOfExpression: return BindAddressOfExpression((PrefixUnaryExpressionSyntax)node, diagnostics); case SyntaxKind.PointerIndirectionExpression: return BindPointerIndirectionExpression((PrefixUnaryExpressionSyntax)node, diagnostics); case SyntaxKind.PostIncrementExpression: case SyntaxKind.PostDecrementExpression: return BindIncrementOperator(node, ((PostfixUnaryExpressionSyntax)node).Operand, ((PostfixUnaryExpressionSyntax)node).OperatorToken, diagnostics); case SyntaxKind.PreIncrementExpression: case SyntaxKind.PreDecrementExpression: return BindIncrementOperator(node, ((PrefixUnaryExpressionSyntax)node).Operand, ((PrefixUnaryExpressionSyntax)node).OperatorToken, diagnostics); case SyntaxKind.ConditionalExpression: return BindConditionalOperator((ConditionalExpressionSyntax)node, diagnostics); case SyntaxKind.SwitchExpression: return BindSwitchExpression((SwitchExpressionSyntax)node, diagnostics); case SyntaxKind.NumericLiteralExpression: case SyntaxKind.StringLiteralExpression: case SyntaxKind.CharacterLiteralExpression: case SyntaxKind.TrueLiteralExpression: case SyntaxKind.FalseLiteralExpression: case SyntaxKind.NullLiteralExpression: return BindLiteralConstant((LiteralExpressionSyntax)node, diagnostics); case SyntaxKind.DefaultLiteralExpression: return new BoundDefaultLiteral(node); case SyntaxKind.ParenthesizedExpression: // Parenthesis tokens are ignored, and operand is bound in the context of parent // expression. return BindParenthesizedExpression(((ParenthesizedExpressionSyntax)node).Expression, diagnostics); case SyntaxKind.UncheckedExpression: case SyntaxKind.CheckedExpression: return BindCheckedExpression((CheckedExpressionSyntax)node, diagnostics); case SyntaxKind.DefaultExpression: return BindDefaultExpression((DefaultExpressionSyntax)node, diagnostics); case SyntaxKind.TypeOfExpression: return BindTypeOf((TypeOfExpressionSyntax)node, diagnostics); case SyntaxKind.SizeOfExpression: return BindSizeOf((SizeOfExpressionSyntax)node, diagnostics); 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: return BindCompoundAssignment((AssignmentExpressionSyntax)node, diagnostics); case SyntaxKind.CoalesceAssignmentExpression: return BindNullCoalescingAssignmentOperator((AssignmentExpressionSyntax)node, diagnostics); case SyntaxKind.AliasQualifiedName: case SyntaxKind.PredefinedType: return this.BindNamespaceOrType(node, diagnostics); case SyntaxKind.QueryExpression: return this.BindQuery((QueryExpressionSyntax)node, diagnostics); case SyntaxKind.AnonymousObjectCreationExpression: return BindAnonymousObjectCreation((AnonymousObjectCreationExpressionSyntax)node, diagnostics); case SyntaxKind.QualifiedName: return BindQualifiedName((QualifiedNameSyntax)node, diagnostics); case SyntaxKind.ComplexElementInitializerExpression: return BindUnexpectedComplexElementInitializer((InitializerExpressionSyntax)node, diagnostics); case SyntaxKind.ArgListExpression: return BindArgList(node, diagnostics); case SyntaxKind.RefTypeExpression: return BindRefType((RefTypeExpressionSyntax)node, diagnostics); case SyntaxKind.MakeRefExpression: return BindMakeRef((MakeRefExpressionSyntax)node, diagnostics); case SyntaxKind.RefValueExpression: return BindRefValue((RefValueExpressionSyntax)node, diagnostics); case SyntaxKind.AwaitExpression: return BindAwait((AwaitExpressionSyntax)node, diagnostics); case SyntaxKind.OmittedArraySizeExpression: case SyntaxKind.OmittedTypeArgument: case SyntaxKind.ObjectInitializerExpression: // Not reachable during method body binding, but // may be used by SemanticModel for error cases. return BadExpression(node); case SyntaxKind.NullableType: // Not reachable during method body binding, but // may be used by SemanticModel for error cases. // NOTE: This happens when there's a problem with the Nullable<T> type (e.g. it's missing). // There is no corresponding problem for array or pointer types (which seem analogous), since // they are not constructed types; the element type can be an error type, but the array/pointer // type cannot. return BadExpression(node); case SyntaxKind.InterpolatedStringExpression: return BindInterpolatedString((InterpolatedStringExpressionSyntax)node, diagnostics); case SyntaxKind.IsPatternExpression: return BindIsPatternExpression((IsPatternExpressionSyntax)node, diagnostics); case SyntaxKind.TupleExpression: return BindTupleExpression((TupleExpressionSyntax)node, diagnostics); case SyntaxKind.ThrowExpression: return BindThrowExpression((ThrowExpressionSyntax)node, diagnostics); case SyntaxKind.RefType: return BindRefType(node, diagnostics); case SyntaxKind.RefExpression: return BindRefExpression(node, diagnostics); case SyntaxKind.DeclarationExpression: return BindDeclarationExpressionAsError((DeclarationExpressionSyntax)node, diagnostics); case SyntaxKind.SuppressNullableWarningExpression: return BindSuppressNullableWarningExpression((PostfixUnaryExpressionSyntax)node, diagnostics); case SyntaxKind.WithExpression: return BindWithExpression((WithExpressionSyntax)node, diagnostics); default: // NOTE: We could probably throw an exception here, but it's conceivable // that a non-parser syntax tree could reach this point with an unexpected // SyntaxKind and we don't want to throw if that occurs. Debug.Assert(false, "Unexpected SyntaxKind " + node.Kind()); diagnostics.Add(ErrorCode.ERR_InternalError, node.Location); return BadExpression(node); } } #nullable enable internal virtual BoundSwitchExpressionArm BindSwitchExpressionArm(SwitchExpressionArmSyntax node, TypeSymbol switchGoverningType, uint switchGoverningValEscape, BindingDiagnosticBag diagnostics) { return this.NextRequired.BindSwitchExpressionArm(node, switchGoverningType, switchGoverningValEscape, diagnostics); } #nullable disable private BoundExpression BindRefExpression(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { var firstToken = node.GetFirstToken(); diagnostics.Add(ErrorCode.ERR_UnexpectedToken, firstToken.GetLocation(), firstToken.ValueText); return new BoundBadExpression( node, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, ImmutableArray<BoundExpression>.Empty, CreateErrorType("ref")); } private BoundExpression BindRefType(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { var firstToken = node.GetFirstToken(); diagnostics.Add(ErrorCode.ERR_UnexpectedToken, firstToken.GetLocation(), firstToken.ValueText); return new BoundTypeExpression(node, null, CreateErrorType("ref")); } private BoundExpression BindThrowExpression(ThrowExpressionSyntax node, BindingDiagnosticBag diagnostics) { bool hasErrors = node.HasErrors; if (!IsThrowExpressionInProperContext(node)) { diagnostics.Add(ErrorCode.ERR_ThrowMisplaced, node.ThrowKeyword.GetLocation()); hasErrors = true; } var thrownExpression = BindThrownExpression(node.Expression, diagnostics, ref hasErrors); return new BoundThrowExpression(node, thrownExpression, null, hasErrors); } private static bool IsThrowExpressionInProperContext(ThrowExpressionSyntax node) { var parent = node.Parent; if (parent == null || node.HasErrors) { return true; } switch (parent.Kind()) { case SyntaxKind.ConditionalExpression: // ?: { var conditionalParent = (ConditionalExpressionSyntax)parent; return node == conditionalParent.WhenTrue || node == conditionalParent.WhenFalse; } case SyntaxKind.CoalesceExpression: // ?? { var binaryParent = (BinaryExpressionSyntax)parent; return node == binaryParent.Right; } case SyntaxKind.SwitchExpressionArm: case SyntaxKind.ArrowExpressionClause: case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: return true; // We do not support && and || because // 1. The precedence would not syntactically allow it // 2. It isn't clear what the semantics should be // 3. It isn't clear what use cases would motivate us to change the precedence to support it default: return false; } } // Bind a declaration expression where it isn't permitted. private BoundExpression BindDeclarationExpressionAsError(DeclarationExpressionSyntax node, BindingDiagnosticBag diagnostics) { // This is an error, as declaration expressions are handled specially in every context in which // they are permitted. So we have a context in which they are *not* permitted. Nevertheless, we // bind it and then give one nice message. bool isVar; bool isConst = false; AliasSymbol alias; var declType = BindVariableTypeWithAnnotations(node.Designation, diagnostics, node.Type, ref isConst, out isVar, out alias); Error(diagnostics, ErrorCode.ERR_DeclarationExpressionNotPermitted, node); return BindDeclarationVariablesForErrorRecovery(declType, node.Designation, node, diagnostics); } /// <summary> /// Bind a declaration variable where it isn't permitted. The caller is expected to produce a diagnostic. /// </summary> private BoundExpression BindDeclarationVariablesForErrorRecovery(TypeWithAnnotations declTypeWithAnnotations, VariableDesignationSyntax node, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) { declTypeWithAnnotations = declTypeWithAnnotations.HasType ? declTypeWithAnnotations : TypeWithAnnotations.Create(CreateErrorType("var")); switch (node.Kind()) { case SyntaxKind.SingleVariableDesignation: { var single = (SingleVariableDesignationSyntax)node; var result = BindDeconstructionVariable(declTypeWithAnnotations, single, syntax, diagnostics); return BindToTypeForErrorRecovery(result); } case SyntaxKind.DiscardDesignation: { return BindDiscardExpression(syntax, declTypeWithAnnotations); } case SyntaxKind.ParenthesizedVariableDesignation: { var tuple = (ParenthesizedVariableDesignationSyntax)node; int count = tuple.Variables.Count; var builder = ArrayBuilder<BoundExpression>.GetInstance(count); var namesBuilder = ArrayBuilder<string>.GetInstance(count); foreach (var n in tuple.Variables) { builder.Add(BindDeclarationVariablesForErrorRecovery(declTypeWithAnnotations, n, n, diagnostics)); namesBuilder.Add(InferTupleElementName(n)); } ImmutableArray<BoundExpression> subExpressions = builder.ToImmutableAndFree(); var uniqueFieldNames = PooledHashSet<string>.GetInstance(); RemoveDuplicateInferredTupleNamesAndFreeIfEmptied(ref namesBuilder, uniqueFieldNames); uniqueFieldNames.Free(); ImmutableArray<string> tupleNames = namesBuilder is null ? default : namesBuilder.ToImmutableAndFree(); ImmutableArray<bool> inferredPositions = tupleNames.IsDefault ? default : tupleNames.SelectAsArray(n => n != null); bool disallowInferredNames = this.Compilation.LanguageVersion.DisallowInferredTupleElementNames(); // We will not check constraints at this point as this code path // is failure-only and the caller is expected to produce a diagnostic. var tupleType = NamedTypeSymbol.CreateTuple( locationOpt: null, subExpressions.SelectAsArray(e => TypeWithAnnotations.Create(e.Type)), elementLocations: default, tupleNames, Compilation, shouldCheckConstraints: false, includeNullability: false, errorPositions: disallowInferredNames ? inferredPositions : default); return new BoundConvertedTupleLiteral(syntax, sourceTuple: null, wasTargetTyped: true, subExpressions, tupleNames, inferredPositions, tupleType); } default: throw ExceptionUtilities.UnexpectedValue(node.Kind()); } } private BoundExpression BindTupleExpression(TupleExpressionSyntax node, BindingDiagnosticBag diagnostics) { SeparatedSyntaxList<ArgumentSyntax> arguments = node.Arguments; int numElements = arguments.Count; if (numElements < 2) { // this should be a parse error already. var args = numElements == 1 ? ImmutableArray.Create(BindValue(arguments[0].Expression, diagnostics, BindValueKind.RValue)) : ImmutableArray<BoundExpression>.Empty; return BadExpression(node, args); } bool hasNaturalType = true; var boundArguments = ArrayBuilder<BoundExpression>.GetInstance(arguments.Count); var elementTypesWithAnnotations = ArrayBuilder<TypeWithAnnotations>.GetInstance(arguments.Count); var elementLocations = ArrayBuilder<Location>.GetInstance(arguments.Count); // prepare names var (elementNames, inferredPositions, hasErrors) = ExtractTupleElementNames(arguments, diagnostics); // prepare types and locations for (int i = 0; i < numElements; i++) { ArgumentSyntax argumentSyntax = arguments[i]; IdentifierNameSyntax nameSyntax = argumentSyntax.NameColon?.Name; if (nameSyntax != null) { elementLocations.Add(nameSyntax.Location); } else { elementLocations.Add(argumentSyntax.Location); } BoundExpression boundArgument = BindValue(argumentSyntax.Expression, diagnostics, BindValueKind.RValue); if (boundArgument.Type?.SpecialType == SpecialType.System_Void) { diagnostics.Add(ErrorCode.ERR_VoidInTuple, argumentSyntax.Location); boundArgument = new BoundBadExpression( argumentSyntax, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, ImmutableArray.Create<BoundExpression>(boundArgument), CreateErrorType("void")); } boundArguments.Add(boundArgument); var elementTypeWithAnnotations = TypeWithAnnotations.Create(boundArgument.Type); elementTypesWithAnnotations.Add(elementTypeWithAnnotations); if (!elementTypeWithAnnotations.HasType) { hasNaturalType = false; } } NamedTypeSymbol tupleTypeOpt = null; var elements = elementTypesWithAnnotations.ToImmutableAndFree(); var locations = elementLocations.ToImmutableAndFree(); if (hasNaturalType) { bool disallowInferredNames = this.Compilation.LanguageVersion.DisallowInferredTupleElementNames(); tupleTypeOpt = NamedTypeSymbol.CreateTuple(node.Location, elements, locations, elementNames, this.Compilation, syntax: node, diagnostics: diagnostics, shouldCheckConstraints: true, includeNullability: false, errorPositions: disallowInferredNames ? inferredPositions : default(ImmutableArray<bool>)); } else { NamedTypeSymbol.VerifyTupleTypePresent(elements.Length, node, this.Compilation, diagnostics); } // Always track the inferred positions in the bound node, so that conversions don't produce a warning // for "dropped names" on tuple literal when the name was inferred. return new BoundTupleLiteral(node, boundArguments.ToImmutableAndFree(), elementNames, inferredPositions, tupleTypeOpt, hasErrors); } private static (ImmutableArray<string> elementNamesArray, ImmutableArray<bool> inferredArray, bool hasErrors) ExtractTupleElementNames( SeparatedSyntaxList<ArgumentSyntax> arguments, BindingDiagnosticBag diagnostics) { bool hasErrors = false; int numElements = arguments.Count; var uniqueFieldNames = PooledHashSet<string>.GetInstance(); ArrayBuilder<string> elementNames = null; ArrayBuilder<string> inferredElementNames = null; for (int i = 0; i < numElements; i++) { ArgumentSyntax argumentSyntax = arguments[i]; IdentifierNameSyntax nameSyntax = argumentSyntax.NameColon?.Name; string name = null; string inferredName = null; if (nameSyntax != null) { name = nameSyntax.Identifier.ValueText; if (diagnostics != null && !CheckTupleMemberName(name, i, argumentSyntax.NameColon.Name, diagnostics, uniqueFieldNames)) { hasErrors = true; } } else { inferredName = InferTupleElementName(argumentSyntax.Expression); } CollectTupleFieldMemberName(name, i, numElements, ref elementNames); CollectTupleFieldMemberName(inferredName, i, numElements, ref inferredElementNames); } RemoveDuplicateInferredTupleNamesAndFreeIfEmptied(ref inferredElementNames, uniqueFieldNames); uniqueFieldNames.Free(); var result = MergeTupleElementNames(elementNames, inferredElementNames); elementNames?.Free(); inferredElementNames?.Free(); return (result.names, result.inferred, hasErrors); } private static (ImmutableArray<string> names, ImmutableArray<bool> inferred) MergeTupleElementNames( ArrayBuilder<string> elementNames, ArrayBuilder<string> inferredElementNames) { if (elementNames == null) { if (inferredElementNames == null) { return (default(ImmutableArray<string>), default(ImmutableArray<bool>)); } else { var finalNames = inferredElementNames.ToImmutable(); return (finalNames, finalNames.SelectAsArray(n => n != null)); } } if (inferredElementNames == null) { return (elementNames.ToImmutable(), default(ImmutableArray<bool>)); } Debug.Assert(elementNames.Count == inferredElementNames.Count); var builder = ArrayBuilder<bool>.GetInstance(elementNames.Count); for (int i = 0; i < elementNames.Count; i++) { string inferredName = inferredElementNames[i]; if (elementNames[i] == null && inferredName != null) { elementNames[i] = inferredName; builder.Add(true); } else { builder.Add(false); } } return (elementNames.ToImmutable(), builder.ToImmutableAndFree()); } /// <summary> /// Removes duplicate entries in <paramref name="inferredElementNames"/> and frees it if only nulls remain. /// </summary> private static void RemoveDuplicateInferredTupleNamesAndFreeIfEmptied(ref ArrayBuilder<string> inferredElementNames, HashSet<string> uniqueFieldNames) { if (inferredElementNames == null) { return; } // Inferred names that duplicate an explicit name or a previous inferred name are tagged for removal var toRemove = PooledHashSet<string>.GetInstance(); foreach (var name in inferredElementNames) { if (name != null && !uniqueFieldNames.Add(name)) { toRemove.Add(name); } } for (int i = 0; i < inferredElementNames.Count; i++) { var inferredName = inferredElementNames[i]; if (inferredName != null && toRemove.Contains(inferredName)) { inferredElementNames[i] = null; } } toRemove.Free(); if (inferredElementNames.All(n => n is null)) { inferredElementNames.Free(); inferredElementNames = null; } } private static string InferTupleElementName(SyntaxNode syntax) { string name = syntax.TryGetInferredMemberName(); // Reserved names are never candidates to be inferred names, at any position if (name == null || NamedTypeSymbol.IsTupleElementNameReserved(name) != -1) { return null; } return name; } private BoundExpression BindRefValue(RefValueExpressionSyntax node, BindingDiagnosticBag diagnostics) { // __refvalue(tr, T) requires that tr be a TypedReference and T be a type. // The result is a *variable* of type T. BoundExpression argument = BindValue(node.Expression, diagnostics, BindValueKind.RValue); bool hasErrors = argument.HasAnyErrors; TypeSymbol typedReferenceType = this.Compilation.GetSpecialType(SpecialType.System_TypedReference); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = this.Conversions.ClassifyConversionFromExpression(argument, typedReferenceType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!conversion.IsImplicit || !conversion.IsValid) { hasErrors = true; GenerateImplicitConversionError(diagnostics, node, conversion, argument, typedReferenceType); } argument = CreateConversion(argument, conversion, typedReferenceType, diagnostics); TypeWithAnnotations typeWithAnnotations = BindType(node.Type, diagnostics); return new BoundRefValueOperator(node, typeWithAnnotations.NullableAnnotation, argument, typeWithAnnotations.Type, hasErrors); } private BoundExpression BindMakeRef(MakeRefExpressionSyntax node, BindingDiagnosticBag diagnostics) { // __makeref(x) requires that x be a variable, and not be of a restricted type. BoundExpression argument = this.BindValue(node.Expression, diagnostics, BindValueKind.RefOrOut); bool hasErrors = argument.HasAnyErrors; TypeSymbol typedReferenceType = GetSpecialType(SpecialType.System_TypedReference, diagnostics, node); if ((object)argument.Type != null && argument.Type.IsRestrictedType()) { // CS1601: Cannot make reference to variable of type '{0}' Error(diagnostics, ErrorCode.ERR_MethodArgCantBeRefAny, node, argument.Type); hasErrors = true; } // UNDONE: We do not yet implement warnings anywhere for: // UNDONE: * taking a ref to a volatile field // UNDONE: * taking a ref to a "non-agile" field // UNDONE: We should do so here when we implement this feature for regular out/ref parameters. return new BoundMakeRefOperator(node, argument, typedReferenceType, hasErrors); } private BoundExpression BindRefType(RefTypeExpressionSyntax node, BindingDiagnosticBag diagnostics) { // __reftype(x) requires that x be implicitly convertible to TypedReference. BoundExpression argument = BindValue(node.Expression, diagnostics, BindValueKind.RValue); bool hasErrors = argument.HasAnyErrors; TypeSymbol typedReferenceType = this.Compilation.GetSpecialType(SpecialType.System_TypedReference); TypeSymbol typeType = this.GetWellKnownType(WellKnownType.System_Type, diagnostics, node); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = this.Conversions.ClassifyConversionFromExpression(argument, typedReferenceType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!conversion.IsImplicit || !conversion.IsValid) { hasErrors = true; GenerateImplicitConversionError(diagnostics, node, conversion, argument, typedReferenceType); } argument = CreateConversion(argument, conversion, typedReferenceType, diagnostics); return new BoundRefTypeOperator(node, argument, null, typeType, hasErrors); } private BoundExpression BindArgList(CSharpSyntaxNode node, BindingDiagnosticBag diagnostics) { // There are two forms of __arglist expression. In a method with an __arglist parameter, // it is legal to use __arglist as an expression of type RuntimeArgumentHandle. In // a call to such a method, it is legal to use __arglist(x, y, z) as the final argument. // This method only handles the first usage; the second usage is parsed as a call syntax. // The native compiler allows __arglist in a lambda: // // class C // { // delegate int D(RuntimeArgumentHandle r); // static void M(__arglist) // { // D f = null; // f = r=>f(__arglist); // } // } // // This is clearly wrong. Either the developer intends __arglist to refer to the // arg list of the *lambda*, or to the arg list of *M*. The former makes no sense; // lambdas cannot have an arg list. The latter we have no way to generate code for; // you cannot hoist the arg list to a field of a closure class. // // The native compiler allows this and generates code as though the developer // was attempting to access the arg list of the lambda! We should simply disallow it. TypeSymbol runtimeArgumentHandleType = GetSpecialType(SpecialType.System_RuntimeArgumentHandle, diagnostics, node); MethodSymbol method = this.ContainingMember() as MethodSymbol; bool hasError = false; if ((object)method == null || !method.IsVararg) { // CS0190: The __arglist construct is valid only within a variable argument method Error(diagnostics, ErrorCode.ERR_ArgsInvalid, node); hasError = true; } else { // We're in a varargs method; are we also inside a lambda? Symbol container = this.ContainingMemberOrLambda; if (container != method) { // We also need to report this any time a local variable of a restricted type // would be hoisted into a closure for an anonymous function, iterator or async method. // We do that during the actual rewrites. // CS4013: Instance of type '{0}' cannot be used inside an anonymous function, query expression, iterator block or async method Error(diagnostics, ErrorCode.ERR_SpecialByRefInLambda, node, runtimeArgumentHandleType); hasError = true; } } return new BoundArgList(node, runtimeArgumentHandleType, hasError); } /// <summary> /// This can be reached for the qualified name on the right-hand-side of an `is` operator. /// For compatibility we parse it as a qualified name, as the is-type expression only permitted /// a type on the right-hand-side in C# 6. But the same syntax now, in C# 7 and later, can /// refer to a constant, which would normally be represented as a *simple member access expression*. /// Since the parser cannot distinguish, it parses it as before and depends on the binder /// to handle a qualified name appearing as an expression. /// </summary> private BoundExpression BindQualifiedName(QualifiedNameSyntax node, BindingDiagnosticBag diagnostics) { return BindMemberAccessWithBoundLeft(node, this.BindLeftOfPotentialColorColorMemberAccess(node.Left, diagnostics), node.Right, node.DotToken, invoked: false, indexed: false, diagnostics: diagnostics); } private BoundExpression BindParenthesizedExpression(ExpressionSyntax innerExpression, BindingDiagnosticBag diagnostics) { var result = BindExpression(innerExpression, diagnostics); // A parenthesized expression may not be a namespace or a type. If it is a parenthesized // namespace or type then report the error but let it go; we'll just ignore the // parenthesis and keep on trucking. CheckNotNamespaceOrType(result, diagnostics); return result; } #nullable enable private BoundExpression BindTypeOf(TypeOfExpressionSyntax node, BindingDiagnosticBag diagnostics) { ExpressionSyntax typeSyntax = node.Type; TypeofBinder typeofBinder = new TypeofBinder(typeSyntax, this); //has special handling for unbound types AliasSymbol alias; TypeWithAnnotations typeWithAnnotations = typeofBinder.BindType(typeSyntax, diagnostics, out alias); TypeSymbol type = typeWithAnnotations.Type; bool hasError = false; // NB: Dev10 has an error for typeof(dynamic), but allows typeof(dynamic[]), // typeof(C<dynamic>), etc. if (type.IsDynamic()) { diagnostics.Add(ErrorCode.ERR_BadDynamicTypeof, node.Location); hasError = true; } else if (typeWithAnnotations.NullableAnnotation.IsAnnotated() && type.IsReferenceType) { // error: cannot take the `typeof` a nullable reference type. diagnostics.Add(ErrorCode.ERR_BadNullableTypeof, node.Location); hasError = true; } else if (this.InAttributeArgument && type.ContainsFunctionPointer()) { // https://github.com/dotnet/roslyn/issues/48765 tracks removing this error and properly supporting function // pointers in attribute types. Until then, we don't know how serialize them, so error instead of crashing // during emit. diagnostics.Add(ErrorCode.ERR_FunctionPointerTypesInAttributeNotSupported, node.Location); hasError = true; } BoundTypeExpression boundType = new BoundTypeExpression(typeSyntax, alias, typeWithAnnotations, type.IsErrorType()); return new BoundTypeOfOperator(node, boundType, null, this.GetWellKnownType(WellKnownType.System_Type, diagnostics, node), hasError); } private BoundExpression BindSizeOf(SizeOfExpressionSyntax node, BindingDiagnosticBag diagnostics) { ExpressionSyntax typeSyntax = node.Type; AliasSymbol alias; TypeWithAnnotations typeWithAnnotations = this.BindType(typeSyntax, diagnostics, out alias); TypeSymbol type = typeWithAnnotations.Type; bool typeHasErrors = type.IsErrorType() || CheckManagedAddr(Compilation, type, node.Location, diagnostics); BoundTypeExpression boundType = new BoundTypeExpression(typeSyntax, alias, typeWithAnnotations, typeHasErrors); ConstantValue constantValue = GetConstantSizeOf(type); bool hasErrors = constantValue is null && ReportUnsafeIfNotAllowed(node, diagnostics, type); return new BoundSizeOfOperator(node, boundType, constantValue, this.GetSpecialType(SpecialType.System_Int32, diagnostics, node), hasErrors); } /// <returns>true if managed type-related errors were found, otherwise false.</returns> internal static bool CheckManagedAddr(CSharpCompilation compilation, TypeSymbol type, Location location, BindingDiagnosticBag diagnostics) { var useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(diagnostics, compilation.Assembly); var managedKind = type.GetManagedKind(ref useSiteInfo); diagnostics.Add(location, useSiteInfo); return CheckManagedAddr(compilation, type, managedKind, location, diagnostics); } /// <returns>true if managed type-related errors were found, otherwise false.</returns> internal static bool CheckManagedAddr(CSharpCompilation compilation, TypeSymbol type, ManagedKind managedKind, Location location, BindingDiagnosticBag diagnostics) { switch (managedKind) { case ManagedKind.Managed: diagnostics.Add(ErrorCode.ERR_ManagedAddr, location, type); return true; case ManagedKind.UnmanagedWithGenerics when MessageID.IDS_FeatureUnmanagedConstructedTypes.GetFeatureAvailabilityDiagnosticInfo(compilation) is CSDiagnosticInfo diagnosticInfo: diagnostics.Add(diagnosticInfo, location); return true; case ManagedKind.Unknown: throw ExceptionUtilities.UnexpectedValue(managedKind); default: return false; } } #nullable disable internal static ConstantValue GetConstantSizeOf(TypeSymbol type) { return ConstantValue.CreateSizeOf((type.GetEnumUnderlyingType() ?? type).SpecialType); } private BoundExpression BindDefaultExpression(DefaultExpressionSyntax node, BindingDiagnosticBag diagnostics) { TypeWithAnnotations typeWithAnnotations = this.BindType(node.Type, diagnostics, out AliasSymbol alias); var typeExpression = new BoundTypeExpression(node.Type, aliasOpt: alias, typeWithAnnotations); TypeSymbol type = typeWithAnnotations.Type; return new BoundDefaultExpression(node, typeExpression, constantValueOpt: type.GetDefaultValue(), type); } /// <summary> /// Binds a simple identifier. /// </summary> private BoundExpression BindIdentifier( SimpleNameSyntax node, bool invoked, bool indexed, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); // If the syntax tree is ill-formed and the identifier is missing then we've already // given a parse error. Just return an error local and continue with analysis. if (node.IsMissing) { return BadExpression(node); } // A simple-name is either of the form I or of the form I<A1, ..., AK>, where I is a // single identifier and <A1, ..., AK> is an optional type-argument-list. When no // type-argument-list is specified, consider K to be zero. The simple-name is evaluated // and classified as follows: // If K is zero and the simple-name appears within a block and if the block's (or an // enclosing block's) local variable declaration space contains a local variable, // parameter or constant with name I, then the simple-name refers to that local // variable, parameter or constant and is classified as a variable or value. // If K is zero and the simple-name appears within the body of a generic method // declaration and if that declaration includes a type parameter with name I, then the // simple-name refers to that type parameter. BoundExpression expression; // It's possible that the argument list is malformed; if so, do not attempt to bind it; // just use the null array. int arity = node.Arity; bool hasTypeArguments = arity > 0; SeparatedSyntaxList<TypeSyntax> typeArgumentList = node.Kind() == SyntaxKind.GenericName ? ((GenericNameSyntax)node).TypeArgumentList.Arguments : default(SeparatedSyntaxList<TypeSyntax>); Debug.Assert(arity == typeArgumentList.Count); var typeArgumentsWithAnnotations = hasTypeArguments ? BindTypeArguments(typeArgumentList, diagnostics) : default(ImmutableArray<TypeWithAnnotations>); var lookupResult = LookupResult.GetInstance(); LookupOptions options = LookupOptions.AllMethodsOnArityZero; if (invoked) { options |= LookupOptions.MustBeInvocableIfMember; } if (!IsInMethodBody && !IsInsideNameof) { Debug.Assert((options & LookupOptions.NamespacesOrTypesOnly) == 0); options |= LookupOptions.MustNotBeMethodTypeParameter; } var name = node.Identifier.ValueText; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupSymbolsWithFallback(lookupResult, name, arity: arity, useSiteInfo: ref useSiteInfo, options: options); diagnostics.Add(node, useSiteInfo); if (lookupResult.Kind != LookupResultKind.Empty) { // have we detected an error with the current node? bool isError; var members = ArrayBuilder<Symbol>.GetInstance(); Symbol symbol = GetSymbolOrMethodOrPropertyGroup(lookupResult, node, name, node.Arity, members, diagnostics, out isError, qualifierOpt: null); // reports diagnostics in result. if ((object)symbol == null) { Debug.Assert(members.Count > 0); var receiver = SynthesizeMethodGroupReceiver(node, members); expression = ConstructBoundMemberGroupAndReportOmittedTypeArguments( node, typeArgumentList, typeArgumentsWithAnnotations, receiver, name, members, lookupResult, receiver != null ? BoundMethodGroupFlags.HasImplicitReceiver : BoundMethodGroupFlags.None, isError, diagnostics); ReportSimpleProgramLocalReferencedOutsideOfTopLevelStatement(node, members[0], diagnostics); } else { bool isNamedType = (symbol.Kind == SymbolKind.NamedType) || (symbol.Kind == SymbolKind.ErrorType); if (hasTypeArguments && isNamedType) { symbol = ConstructNamedTypeUnlessTypeArgumentOmitted(node, (NamedTypeSymbol)symbol, typeArgumentList, typeArgumentsWithAnnotations, diagnostics); } expression = BindNonMethod(node, symbol, diagnostics, lookupResult.Kind, indexed, isError); if (!isNamedType && (hasTypeArguments || node.Kind() == SyntaxKind.GenericName)) { Debug.Assert(isError); // Should have been reported by GetSymbolOrMethodOrPropertyGroup. expression = new BoundBadExpression( syntax: node, resultKind: LookupResultKind.WrongArity, symbols: ImmutableArray.Create(symbol), childBoundNodes: ImmutableArray.Create(BindToTypeForErrorRecovery(expression)), type: expression.Type, hasErrors: isError); } } members.Free(); } else { expression = null; if (node is IdentifierNameSyntax identifier) { var type = BindNativeIntegerSymbolIfAny(identifier, diagnostics); if (type is { }) { expression = new BoundTypeExpression(node, null, type); } else if (FallBackOnDiscard(identifier, diagnostics)) { expression = new BoundDiscardExpression(node, type: null); } } // Otherwise, the simple-name is undefined and a compile-time error occurs. if (expression is null) { expression = BadExpression(node); if (lookupResult.Error != null) { Error(diagnostics, lookupResult.Error, node); } else if (IsJoinRangeVariableInLeftKey(node)) { Error(diagnostics, ErrorCode.ERR_QueryOuterKey, node, name); } else if (IsInJoinRightKey(node)) { Error(diagnostics, ErrorCode.ERR_QueryInnerKey, node, name); } else { Error(diagnostics, ErrorCode.ERR_NameNotInContext, node, name); } } } lookupResult.Free(); return expression; } /// <summary> /// Is this is an _ identifier in a context where discards are allowed? /// </summary> private static bool FallBackOnDiscard(IdentifierNameSyntax node, BindingDiagnosticBag diagnostics) { if (!node.Identifier.IsUnderscoreToken()) { return false; } CSharpSyntaxNode containingDeconstruction = node.GetContainingDeconstruction(); bool isDiscard = containingDeconstruction != null || IsOutVarDiscardIdentifier(node); if (isDiscard) { CheckFeatureAvailability(node, MessageID.IDS_FeatureDiscards, diagnostics); } return isDiscard; } private static bool IsOutVarDiscardIdentifier(SimpleNameSyntax node) { Debug.Assert(node.Identifier.IsUnderscoreToken()); CSharpSyntaxNode parent = node.Parent; return (parent?.Kind() == SyntaxKind.Argument && ((ArgumentSyntax)parent).RefOrOutKeyword.Kind() == SyntaxKind.OutKeyword); } private BoundExpression SynthesizeMethodGroupReceiver(CSharpSyntaxNode syntax, ArrayBuilder<Symbol> members) { // SPEC: For each instance type T starting with the instance type of the immediately // SPEC: enclosing type declaration, and continuing with the instance type of each // SPEC: enclosing class or struct declaration, [do a lot of things to find a match]. // SPEC: ... // SPEC: If T is the instance type of the immediately enclosing class or struct type // SPEC: and the lookup identifies one or more methods, the result is a method group // SPEC: with an associated instance expression of this. // Explanation of spec: // // We are looping over a set of types, from inner to outer, attempting to resolve the // meaning of a simple name; for example "M(123)". // // There are a number of possibilities: // // If the lookup finds M in an outer class: // // class Outer { // static void M(int x) {} // class Inner { // void X() { M(123); } // } // } // // or the base class of an outer class: // // class Base { // public static void M(int x) {} // } // class Outer : Base { // class Inner { // void X() { M(123); } // } // } // // Then there is no "associated instance expression" of the method group. That is, there // is no possibility of there being an "implicit this". // // If the lookup finds M on the class that triggered the lookup on the other hand, or // one of its base classes: // // class Base { // public static void M(int x) {} // } // class Derived : Base { // void X() { M(123); } // } // // Then the associated instance expression is "this" *even if one or more methods in the // method group are static*. If it turns out that the method was static, then we'll // check later to determine if there was a receiver actually present in the source code // or not. (That happens during the "final validation" phase of overload resolution. // Implementation explanation: // // If we're here, then lookup has identified one or more methods. Debug.Assert(members.Count > 0); // The lookup implementation loops over the set of types from inner to outer, and stops // when it makes a match. (This is correct because any matches found on more-outer types // would be hidden, and discarded.) This means that we only find members associated with // one containing class or struct. The method is possibly on that type directly, or via // inheritance from a base type of the type. // // The question then is what the "associated instance expression" is; is it "this" or // nothing at all? If the type that we found the method on is the current type, or is a // base type of the current type, then there should be a "this" associated with the // method group. Otherwise, it should be null. var currentType = this.ContainingType; if ((object)currentType == null) { // This may happen if there is no containing type, // e.g. we are binding an expression in an assembly-level attribute return null; } var declaringType = members[0].ContainingType; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; if (currentType.IsEqualToOrDerivedFrom(declaringType, TypeCompareKind.ConsiderEverything, useSiteInfo: ref discardedUseSiteInfo) || (currentType.IsInterface && (declaringType.IsObjectType() || currentType.AllInterfacesNoUseSiteDiagnostics.Contains(declaringType)))) { return ThisReference(syntax, currentType, wasCompilerGenerated: true); } else { return TryBindInteractiveReceiver(syntax, declaringType); } } private bool IsBadLocalOrParameterCapture(Symbol symbol, TypeSymbol type, RefKind refKind) { if (refKind != RefKind.None || type.IsRefLikeType) { var containingMethod = this.ContainingMemberOrLambda as MethodSymbol; if ((object)containingMethod != null && (object)symbol.ContainingSymbol != (object)containingMethod) { // Not expecting symbol from constructed method. Debug.Assert(!symbol.ContainingSymbol.Equals(containingMethod)); // Captured in a lambda. return (containingMethod.MethodKind == MethodKind.AnonymousFunction || containingMethod.MethodKind == MethodKind.LocalFunction) && !IsInsideNameof; // false in EE evaluation method } } return false; } private BoundExpression BindNonMethod(SimpleNameSyntax node, Symbol symbol, BindingDiagnosticBag diagnostics, LookupResultKind resultKind, bool indexed, bool isError) { // Events are handled later as we don't know yet if we are binding to the event or it's backing field. if (symbol.Kind != SymbolKind.Event) { ReportDiagnosticsIfObsolete(diagnostics, symbol, node, hasBaseReceiver: false); } switch (symbol.Kind) { case SymbolKind.Local: { var localSymbol = (LocalSymbol)symbol; TypeSymbol type; bool isNullableUnknown; if (ReportSimpleProgramLocalReferencedOutsideOfTopLevelStatement(node, localSymbol, diagnostics)) { type = new ExtendedErrorTypeSymbol( this.Compilation, name: "var", arity: 0, errorInfo: null, variableUsedBeforeDeclaration: true); isNullableUnknown = true; } else if (isUsedBeforeDeclaration(node, localSymbol)) { // Here we report a local variable being used before its declaration // // There are two possible diagnostics for this: // // CS0841: ERR_VariableUsedBeforeDeclaration // Cannot use local variable 'x' before it is declared // // CS0844: ERR_VariableUsedBeforeDeclarationAndHidesField // Cannot use local variable 'x' before it is declared. The // declaration of the local variable hides the field 'C.x'. // // There are two situations in which we give these errors. // // First, the scope of a local variable -- that is, the region of program // text in which it can be looked up by name -- is throughout the entire // block which declares it. It is therefore possible to use a local // before it is declared, which is an error. // // As an additional help to the user, we give a special error for this // scenario: // // class C { // int x; // void M() { // Print(x); // int x = 5; // } } // // Because a too-clever C++ user might be attempting to deliberately // bind to "this.x" in the "Print". (In C++ the local does not come // into scope until its declaration.) // FieldSymbol possibleField = null; var lookupResult = LookupResult.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupMembersInType( lookupResult, ContainingType, localSymbol.Name, arity: 0, basesBeingResolved: null, options: LookupOptions.Default, originalBinder: this, diagnose: false, useSiteInfo: ref useSiteInfo); diagnostics.Add(node, useSiteInfo); possibleField = lookupResult.SingleSymbolOrDefault as FieldSymbol; lookupResult.Free(); if ((object)possibleField != null) { Error(diagnostics, ErrorCode.ERR_VariableUsedBeforeDeclarationAndHidesField, node, node, possibleField); } else { Error(diagnostics, ErrorCode.ERR_VariableUsedBeforeDeclaration, node, node); } type = new ExtendedErrorTypeSymbol( this.Compilation, name: "var", arity: 0, errorInfo: null, variableUsedBeforeDeclaration: true); isNullableUnknown = true; } else if ((localSymbol as SourceLocalSymbol)?.IsVar == true && localSymbol.ForbiddenZone?.Contains(node) == true) { // A var (type-inferred) local variable has been used in its own initialization (the "forbidden zone"). // There are many cases where this occurs, including: // // 1. var x = M(out x); // 2. M(out var x, out x); // 3. var (x, y) = (y, x); // // localSymbol.ForbiddenDiagnostic provides a suitable diagnostic for whichever case applies. // diagnostics.Add(localSymbol.ForbiddenDiagnostic, node.Location, node); type = new ExtendedErrorTypeSymbol( this.Compilation, name: "var", arity: 0, errorInfo: null, variableUsedBeforeDeclaration: true); isNullableUnknown = true; } else { type = localSymbol.Type; isNullableUnknown = false; if (IsBadLocalOrParameterCapture(localSymbol, type, localSymbol.RefKind)) { isError = true; Error(diagnostics, ErrorCode.ERR_AnonDelegateCantUseLocal, node, localSymbol); } } var constantValueOpt = localSymbol.IsConst && !IsInsideNameof && !type.IsErrorType() ? localSymbol.GetConstantValue(node, this.LocalInProgress, diagnostics) : null; return new BoundLocal(node, localSymbol, BoundLocalDeclarationKind.None, constantValueOpt: constantValueOpt, isNullableUnknown: isNullableUnknown, type: type, hasErrors: isError); } case SymbolKind.Parameter: { var parameter = (ParameterSymbol)symbol; if (IsBadLocalOrParameterCapture(parameter, parameter.Type, parameter.RefKind)) { isError = true; Error(diagnostics, ErrorCode.ERR_AnonDelegateCantUse, node, parameter.Name); } return new BoundParameter(node, parameter, hasErrors: isError); } case SymbolKind.NamedType: case SymbolKind.ErrorType: case SymbolKind.TypeParameter: // If I identifies a type, then the result is that type constructed with the // given type arguments. UNDONE: Construct the child type if it is generic! return new BoundTypeExpression(node, null, (TypeSymbol)symbol, hasErrors: isError); case SymbolKind.Property: { BoundExpression receiver = SynthesizeReceiver(node, symbol, diagnostics); return BindPropertyAccess(node, receiver, (PropertySymbol)symbol, diagnostics, resultKind, hasErrors: isError); } case SymbolKind.Event: { BoundExpression receiver = SynthesizeReceiver(node, symbol, diagnostics); return BindEventAccess(node, receiver, (EventSymbol)symbol, diagnostics, resultKind, hasErrors: isError); } case SymbolKind.Field: { BoundExpression receiver = SynthesizeReceiver(node, symbol, diagnostics); return BindFieldAccess(node, receiver, (FieldSymbol)symbol, diagnostics, resultKind, indexed, hasErrors: isError); } case SymbolKind.Namespace: return new BoundNamespaceExpression(node, (NamespaceSymbol)symbol, hasErrors: isError); case SymbolKind.Alias: { var alias = (AliasSymbol)symbol; symbol = alias.Target; switch (symbol.Kind) { case SymbolKind.NamedType: case SymbolKind.ErrorType: return new BoundTypeExpression(node, alias, (NamedTypeSymbol)symbol, hasErrors: isError); case SymbolKind.Namespace: return new BoundNamespaceExpression(node, (NamespaceSymbol)symbol, alias, hasErrors: isError); default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } } case SymbolKind.RangeVariable: return BindRangeVariable(node, (RangeVariableSymbol)symbol, diagnostics); default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } bool isUsedBeforeDeclaration(SimpleNameSyntax node, LocalSymbol localSymbol) { Location localSymbolLocation = localSymbol.Locations[0]; if (node.SyntaxTree == localSymbolLocation.SourceTree) { return node.SpanStart < localSymbolLocation.SourceSpan.Start; } return false; } } private static bool ReportSimpleProgramLocalReferencedOutsideOfTopLevelStatement(SimpleNameSyntax node, Symbol symbol, BindingDiagnosticBag diagnostics) { if (symbol.ContainingSymbol is SynthesizedSimpleProgramEntryPointSymbol) { if (!SyntaxFacts.IsTopLevelStatement(node.Ancestors(ascendOutOfTrivia: false).OfType<GlobalStatementSyntax>().FirstOrDefault())) { Error(diagnostics, ErrorCode.ERR_SimpleProgramLocalIsReferencedOutsideOfTopLevelStatement, node, node); return true; } } return false; } protected virtual BoundExpression BindRangeVariable(SimpleNameSyntax node, RangeVariableSymbol qv, BindingDiagnosticBag diagnostics) { return Next.BindRangeVariable(node, qv, diagnostics); } private BoundExpression SynthesizeReceiver(SyntaxNode node, Symbol member, BindingDiagnosticBag diagnostics) { // SPEC: Otherwise, if T is the instance type of the immediately enclosing class or // struct type, if the lookup identifies an instance member, and if the reference occurs // within the block of an instance constructor, an instance method, or an instance // accessor, the result is the same as a member access of the form this.I. This can only // happen when K is zero. if (!member.RequiresInstanceReceiver()) { return null; } var currentType = this.ContainingType; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; NamedTypeSymbol declaringType = member.ContainingType; if (currentType.IsEqualToOrDerivedFrom(declaringType, TypeCompareKind.ConsiderEverything, useSiteInfo: ref discardedUseSiteInfo) || (currentType.IsInterface && (declaringType.IsObjectType() || currentType.AllInterfacesNoUseSiteDiagnostics.Contains(declaringType)))) { bool hasErrors = false; if (EnclosingNameofArgument != node) { if (InFieldInitializer && !currentType.IsScriptClass) { //can't access "this" in field initializers Error(diagnostics, ErrorCode.ERR_FieldInitRefNonstatic, node, member); hasErrors = true; } else if (InConstructorInitializer || InAttributeArgument) { //can't access "this" in constructor initializers or attribute arguments Error(diagnostics, ErrorCode.ERR_ObjectRequired, node, member); hasErrors = true; } else { // not an instance member if the container is a type, like when binding default parameter values. var containingMember = ContainingMember(); bool locationIsInstanceMember = !containingMember.IsStatic && (containingMember.Kind != SymbolKind.NamedType || currentType.IsScriptClass); if (!locationIsInstanceMember) { // error CS0120: An object reference is required for the non-static field, method, or property '{0}' Error(diagnostics, ErrorCode.ERR_ObjectRequired, node, member); hasErrors = true; } } hasErrors = hasErrors || IsRefOrOutThisParameterCaptured(node, diagnostics); } return ThisReference(node, currentType, hasErrors, wasCompilerGenerated: true); } else { return TryBindInteractiveReceiver(node, declaringType); } } internal Symbol ContainingMember() { return this.ContainingMemberOrLambda.ContainingNonLambdaMember(); } private BoundExpression TryBindInteractiveReceiver(SyntaxNode syntax, NamedTypeSymbol memberDeclaringType) { if (this.ContainingType.TypeKind == TypeKind.Submission // check we have access to `this` && isInstanceContext()) { if (memberDeclaringType.TypeKind == TypeKind.Submission) { return new BoundPreviousSubmissionReference(syntax, memberDeclaringType) { WasCompilerGenerated = true }; } else { TypeSymbol hostObjectType = Compilation.GetHostObjectTypeSymbol(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; if ((object)hostObjectType != null && hostObjectType.IsEqualToOrDerivedFrom(memberDeclaringType, TypeCompareKind.ConsiderEverything, useSiteInfo: ref discardedUseSiteInfo)) { return new BoundHostObjectMemberReference(syntax, hostObjectType) { WasCompilerGenerated = true }; } } } return null; bool isInstanceContext() { var containingMember = this.ContainingMemberOrLambda; do { if (containingMember.IsStatic) { return false; } if (containingMember.Kind == SymbolKind.NamedType) { break; } containingMember = containingMember.ContainingSymbol; } while ((object)containingMember != null); return true; } } public BoundExpression BindNamespaceOrTypeOrExpression(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { if (node.Kind() == SyntaxKind.PredefinedType) { return this.BindNamespaceOrType(node, diagnostics); } if (SyntaxFacts.IsName(node.Kind())) { if (SyntaxFacts.IsNamespaceAliasQualifier(node)) { return this.BindNamespaceAlias((IdentifierNameSyntax)node, diagnostics); } else if (SyntaxFacts.IsInNamespaceOrTypeContext(node)) { return this.BindNamespaceOrType(node, diagnostics); } } else if (SyntaxFacts.IsTypeSyntax(node.Kind())) { return this.BindNamespaceOrType(node, diagnostics); } return this.BindExpression(node, diagnostics, SyntaxFacts.IsInvoked(node), SyntaxFacts.IsIndexed(node)); } public BoundExpression BindLabel(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { var name = node as IdentifierNameSyntax; if (name == null) { Debug.Assert(node.ContainsDiagnostics); return BadExpression(node, LookupResultKind.NotLabel); } var result = LookupResult.GetInstance(); string labelName = name.Identifier.ValueText; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupSymbolsWithFallback(result, labelName, arity: 0, useSiteInfo: ref useSiteInfo, options: LookupOptions.LabelsOnly); diagnostics.Add(node, useSiteInfo); if (!result.IsMultiViable) { Error(diagnostics, ErrorCode.ERR_LabelNotFound, node, labelName); result.Free(); return BadExpression(node, result.Kind); } Debug.Assert(result.IsSingleViable, "If this happens, we need to deal with multiple label definitions."); var symbol = (LabelSymbol)result.Symbols.First(); result.Free(); return new BoundLabel(node, symbol, null); } public BoundExpression BindNamespaceOrType(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { var symbol = this.BindNamespaceOrTypeOrAliasSymbol(node, diagnostics, null, false); return CreateBoundNamespaceOrTypeExpression(node, symbol.Symbol); } public BoundExpression BindNamespaceAlias(IdentifierNameSyntax node, BindingDiagnosticBag diagnostics) { var symbol = this.BindNamespaceAliasSymbol(node, diagnostics); return CreateBoundNamespaceOrTypeExpression(node, symbol); } private static BoundExpression CreateBoundNamespaceOrTypeExpression(ExpressionSyntax node, Symbol symbol) { var alias = symbol as AliasSymbol; if ((object)alias != null) { symbol = alias.Target; } var type = symbol as TypeSymbol; if ((object)type != null) { return new BoundTypeExpression(node, alias, type); } var namespaceSymbol = symbol as NamespaceSymbol; if ((object)namespaceSymbol != null) { return new BoundNamespaceExpression(node, namespaceSymbol, alias); } throw ExceptionUtilities.UnexpectedValue(symbol); } private BoundThisReference BindThis(ThisExpressionSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); bool hasErrors = true; bool inStaticContext; if (!HasThis(isExplicit: true, inStaticContext: out inStaticContext)) { //this error is returned in the field initializer case Error(diagnostics, inStaticContext ? ErrorCode.ERR_ThisInStaticMeth : ErrorCode.ERR_ThisInBadContext, node); } else { hasErrors = IsRefOrOutThisParameterCaptured(node.Token, diagnostics); } return ThisReference(node, this.ContainingType, hasErrors); } private BoundThisReference ThisReference(SyntaxNode node, NamedTypeSymbol thisTypeOpt, bool hasErrors = false, bool wasCompilerGenerated = false) { return new BoundThisReference(node, thisTypeOpt ?? CreateErrorType(), hasErrors) { WasCompilerGenerated = wasCompilerGenerated }; } private bool IsRefOrOutThisParameterCaptured(SyntaxNodeOrToken thisOrBaseToken, BindingDiagnosticBag diagnostics) { ParameterSymbol thisSymbol = this.ContainingMemberOrLambda.EnclosingThisSymbol(); // If there is no this parameter, then it is definitely not captured and // any diagnostic would be cascading. if ((object)thisSymbol != null && thisSymbol.ContainingSymbol != ContainingMemberOrLambda && thisSymbol.RefKind != RefKind.None) { Error(diagnostics, ErrorCode.ERR_ThisStructNotInAnonMeth, thisOrBaseToken); return true; } return false; } private BoundBaseReference BindBase(BaseExpressionSyntax node, BindingDiagnosticBag diagnostics) { bool hasErrors = false; TypeSymbol baseType = this.ContainingType is null ? null : this.ContainingType.BaseTypeNoUseSiteDiagnostics; bool inStaticContext; if (!HasThis(isExplicit: true, inStaticContext: out inStaticContext)) { //this error is returned in the field initializer case Error(diagnostics, inStaticContext ? ErrorCode.ERR_BaseInStaticMeth : ErrorCode.ERR_BaseInBadContext, node.Token); hasErrors = true; } else if ((object)baseType == null) // e.g. in System.Object { Error(diagnostics, ErrorCode.ERR_NoBaseClass, node); hasErrors = true; } else if (this.ContainingType is null || node.Parent is null || (node.Parent.Kind() != SyntaxKind.SimpleMemberAccessExpression && node.Parent.Kind() != SyntaxKind.ElementAccessExpression)) { Error(diagnostics, ErrorCode.ERR_BaseIllegal, node.Token); hasErrors = true; } else if (IsRefOrOutThisParameterCaptured(node.Token, diagnostics)) { // error has been reported by IsRefOrOutThisParameterCaptured hasErrors = true; } return new BoundBaseReference(node, baseType, hasErrors); } private BoundExpression BindCast(CastExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression operand = this.BindValue(node.Expression, diagnostics, BindValueKind.RValue); TypeWithAnnotations targetTypeWithAnnotations = this.BindType(node.Type, diagnostics); TypeSymbol targetType = targetTypeWithAnnotations.Type; if (targetType.IsNullableType() && !operand.HasAnyErrors && (object)operand.Type != null && !operand.Type.IsNullableType() && !TypeSymbol.Equals(targetType.GetNullableUnderlyingType(), operand.Type, TypeCompareKind.ConsiderEverything2)) { return BindExplicitNullableCastFromNonNullable(node, operand, targetTypeWithAnnotations, diagnostics); } return BindCastCore(node, operand, targetTypeWithAnnotations, wasCompilerGenerated: operand.WasCompilerGenerated, diagnostics: diagnostics); } private BoundExpression BindFromEndIndexExpression(PrefixUnaryExpressionSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node.OperatorToken.IsKind(SyntaxKind.CaretToken)); CheckFeatureAvailability(node, MessageID.IDS_FeatureIndexOperator, diagnostics); // Used in lowering as the second argument to the constructor. Example: new Index(value, fromEnd: true) GetSpecialType(SpecialType.System_Boolean, diagnostics, node); BoundExpression boundOperand = BindValue(node.Operand, diagnostics, BindValueKind.RValue); TypeSymbol intType = GetSpecialType(SpecialType.System_Int32, diagnostics, node); TypeSymbol indexType = GetWellKnownType(WellKnownType.System_Index, diagnostics, node); if ((object)boundOperand.Type != null && boundOperand.Type.IsNullableType()) { // Used in lowering to construct the nullable GetSpecialTypeMember(SpecialMember.System_Nullable_T__ctor, diagnostics, node); NamedTypeSymbol nullableType = GetSpecialType(SpecialType.System_Nullable_T, diagnostics, node); if (!indexType.IsNonNullableValueType()) { Error(diagnostics, ErrorCode.ERR_ValConstraintNotSatisfied, node, nullableType, nullableType.TypeParameters.Single(), indexType); } intType = nullableType.Construct(intType); indexType = nullableType.Construct(indexType); } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = this.Conversions.ClassifyImplicitConversionFromExpression(boundOperand, intType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!conversion.IsValid) { GenerateImplicitConversionError(diagnostics, node, conversion, boundOperand, intType); } BoundExpression boundConversion = CreateConversion(boundOperand, conversion, intType, diagnostics); MethodSymbol symbolOpt = GetWellKnownTypeMember(WellKnownMember.System_Index__ctor, diagnostics, syntax: node) as MethodSymbol; return new BoundFromEndIndexExpression(node, boundConversion, symbolOpt, indexType); } private BoundExpression BindRangeExpression(RangeExpressionSyntax node, BindingDiagnosticBag diagnostics) { CheckFeatureAvailability(node, MessageID.IDS_FeatureRangeOperator, diagnostics); TypeSymbol rangeType = GetWellKnownType(WellKnownType.System_Range, diagnostics, node); MethodSymbol symbolOpt = null; if (!rangeType.IsErrorType()) { // Depending on the available arguments to the range expression, there are four // possible well-known members we could bind to. The constructor is always the // fallback member, usable in any situation. However, if any of the other members // are available and applicable, we will prefer that. WellKnownMember? memberOpt = null; if (node.LeftOperand is null && node.RightOperand is null) { memberOpt = WellKnownMember.System_Range__get_All; } else if (node.LeftOperand is null) { memberOpt = WellKnownMember.System_Range__EndAt; } else if (node.RightOperand is null) { memberOpt = WellKnownMember.System_Range__StartAt; } if (memberOpt is object) { symbolOpt = (MethodSymbol)GetWellKnownTypeMember( memberOpt.GetValueOrDefault(), diagnostics, syntax: node, isOptional: true); } if (symbolOpt is null) { symbolOpt = (MethodSymbol)GetWellKnownTypeMember( WellKnownMember.System_Range__ctor, diagnostics, syntax: node); } } BoundExpression left = BindRangeExpressionOperand(node.LeftOperand, diagnostics); BoundExpression right = BindRangeExpressionOperand(node.RightOperand, diagnostics); if (left?.Type.IsNullableType() == true || right?.Type.IsNullableType() == true) { // Used in lowering to construct the nullable GetSpecialType(SpecialType.System_Boolean, diagnostics, node); GetSpecialTypeMember(SpecialMember.System_Nullable_T__ctor, diagnostics, node); NamedTypeSymbol nullableType = GetSpecialType(SpecialType.System_Nullable_T, diagnostics, node); if (!rangeType.IsNonNullableValueType()) { Error(diagnostics, ErrorCode.ERR_ValConstraintNotSatisfied, node, nullableType, nullableType.TypeParameters.Single(), rangeType); } rangeType = nullableType.Construct(rangeType); } return new BoundRangeExpression(node, left, right, symbolOpt, rangeType); } private BoundExpression BindRangeExpressionOperand(ExpressionSyntax operand, BindingDiagnosticBag diagnostics) { if (operand is null) { return null; } BoundExpression boundOperand = BindValue(operand, diagnostics, BindValueKind.RValue); TypeSymbol indexType = GetWellKnownType(WellKnownType.System_Index, diagnostics, operand); if (boundOperand.Type?.IsNullableType() == true) { // Used in lowering to construct the nullable GetSpecialTypeMember(SpecialMember.System_Nullable_T__ctor, diagnostics, operand); NamedTypeSymbol nullableType = GetSpecialType(SpecialType.System_Nullable_T, diagnostics, operand); if (!indexType.IsNonNullableValueType()) { Error(diagnostics, ErrorCode.ERR_ValConstraintNotSatisfied, operand, nullableType, nullableType.TypeParameters.Single(), indexType); } indexType = nullableType.Construct(indexType); } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = this.Conversions.ClassifyImplicitConversionFromExpression(boundOperand, indexType, ref useSiteInfo); diagnostics.Add(operand, useSiteInfo); if (!conversion.IsValid) { GenerateImplicitConversionError(diagnostics, operand, conversion, boundOperand, indexType); } return CreateConversion(boundOperand, conversion, indexType, diagnostics); } private BoundExpression BindCastCore(ExpressionSyntax node, BoundExpression operand, TypeWithAnnotations targetTypeWithAnnotations, bool wasCompilerGenerated, BindingDiagnosticBag diagnostics) { TypeSymbol targetType = targetTypeWithAnnotations.Type; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = this.Conversions.ClassifyConversionFromExpression(operand, targetType, ref useSiteInfo, forCast: true); diagnostics.Add(node, useSiteInfo); var conversionGroup = new ConversionGroup(conversion, targetTypeWithAnnotations); bool suppressErrors = operand.HasAnyErrors || targetType.IsErrorType(); bool hasErrors = !conversion.IsValid || targetType.IsStatic; if (hasErrors && !suppressErrors) { GenerateExplicitConversionErrors(diagnostics, node, conversion, operand, targetType); } return CreateConversion(node, operand, conversion, isCast: true, conversionGroupOpt: conversionGroup, wasCompilerGenerated: wasCompilerGenerated, destination: targetType, diagnostics: diagnostics, hasErrors: hasErrors | suppressErrors); } private void GenerateExplicitConversionErrors( BindingDiagnosticBag diagnostics, SyntaxNode syntax, Conversion conversion, BoundExpression operand, TypeSymbol targetType) { // Make sure that errors within the unbound lambda don't get lost. if (operand.Kind == BoundKind.UnboundLambda) { GenerateAnonymousFunctionConversionError(diagnostics, operand.Syntax, (UnboundLambda)operand, targetType); return; } if (operand.HasAnyErrors || targetType.IsErrorType()) { // an error has already been reported elsewhere return; } if (targetType.IsStatic) { // The specification states in the section titled "Referencing Static // Class Types" that it is always illegal to have a static class in a // cast operator. diagnostics.Add(ErrorCode.ERR_ConvertToStaticClass, syntax.Location, targetType); return; } if (!targetType.IsReferenceType && !targetType.IsNullableType() && operand.IsLiteralNull()) { diagnostics.Add(ErrorCode.ERR_ValueCantBeNull, syntax.Location, targetType); return; } if (conversion.ResultKind == LookupResultKind.OverloadResolutionFailure) { Debug.Assert(conversion.IsUserDefined); ImmutableArray<MethodSymbol> originalUserDefinedConversions = conversion.OriginalUserDefinedConversions; if (originalUserDefinedConversions.Length > 1) { diagnostics.Add(ErrorCode.ERR_AmbigUDConv, syntax.Location, originalUserDefinedConversions[0], originalUserDefinedConversions[1], operand.Display, targetType); } else { Debug.Assert(originalUserDefinedConversions.Length == 0, "How can there be exactly one applicable user-defined conversion if the conversion doesn't exist?"); SymbolDistinguisher distinguisher1 = new SymbolDistinguisher(this.Compilation, operand.Type, targetType); diagnostics.Add(ErrorCode.ERR_NoExplicitConv, syntax.Location, distinguisher1.First, distinguisher1.Second); } return; } switch (operand.Kind) { case BoundKind.MethodGroup: { if (targetType.TypeKind != TypeKind.Delegate || !MethodGroupConversionDoesNotExistOrHasErrors((BoundMethodGroup)operand, (NamedTypeSymbol)targetType, syntax.Location, diagnostics, out _)) { diagnostics.Add(ErrorCode.ERR_NoExplicitConv, syntax.Location, MessageID.IDS_SK_METHOD.Localize(), targetType); } return; } case BoundKind.TupleLiteral: { var tuple = (BoundTupleLiteral)operand; var targetElementTypesWithAnnotations = default(ImmutableArray<TypeWithAnnotations>); // If target is a tuple or compatible type with the same number of elements, // report errors for tuple arguments that failed to convert, which would be more useful. if (targetType.TryGetElementTypesWithAnnotationsIfTupleType(out targetElementTypesWithAnnotations) && targetElementTypesWithAnnotations.Length == tuple.Arguments.Length) { GenerateExplicitConversionErrorsForTupleLiteralArguments(diagnostics, tuple.Arguments, targetElementTypesWithAnnotations); return; } // target is not compatible with source and source does not have a type if ((object)tuple.Type == null) { Error(diagnostics, ErrorCode.ERR_ConversionNotTupleCompatible, syntax, tuple.Arguments.Length, targetType); return; } // Otherwise it is just a regular conversion failure from T1 to T2. break; } case BoundKind.StackAllocArrayCreation: { var stackAllocExpression = (BoundStackAllocArrayCreation)operand; Error(diagnostics, ErrorCode.ERR_StackAllocConversionNotPossible, syntax, stackAllocExpression.ElementType, targetType); return; } case BoundKind.UnconvertedConditionalOperator when operand.Type is null: case BoundKind.UnconvertedSwitchExpression when operand.Type is null: { GenerateImplicitConversionError(diagnostics, operand.Syntax, conversion, operand, targetType); return; } case BoundKind.UnconvertedAddressOfOperator: { var errorCode = targetType.TypeKind switch { TypeKind.FunctionPointer => ErrorCode.ERR_MethFuncPtrMismatch, TypeKind.Delegate => ErrorCode.ERR_CannotConvertAddressOfToDelegate, _ => ErrorCode.ERR_AddressOfToNonFunctionPointer }; diagnostics.Add(errorCode, syntax.Location, ((BoundUnconvertedAddressOfOperator)operand).Operand.Name, targetType); return; } } Debug.Assert((object)operand.Type != null); SymbolDistinguisher distinguisher = new SymbolDistinguisher(this.Compilation, operand.Type, targetType); diagnostics.Add(ErrorCode.ERR_NoExplicitConv, syntax.Location, distinguisher.First, distinguisher.Second); } private void GenerateExplicitConversionErrorsForTupleLiteralArguments( BindingDiagnosticBag diagnostics, ImmutableArray<BoundExpression> tupleArguments, ImmutableArray<TypeWithAnnotations> targetElementTypesWithAnnotations) { // report all leaf elements of the tuple literal that failed to convert // NOTE: we are not responsible for reporting use site errors here, just the failed leaf conversions. // By the time we get here we have done analysis and know we have failed the cast in general, and diagnostics collected in the process is already in the bag. // The only thing left is to form a diagnostics about the actually failing conversion(s). // This whole method does not itself collect any usesite diagnostics. Its only purpose is to produce an error better than "conversion failed here" var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; for (int i = 0; i < targetElementTypesWithAnnotations.Length; i++) { var argument = tupleArguments[i]; var targetElementType = targetElementTypesWithAnnotations[i].Type; var elementConversion = Conversions.ClassifyConversionFromExpression(argument, targetElementType, ref discardedUseSiteInfo); if (!elementConversion.IsValid) { GenerateExplicitConversionErrors(diagnostics, argument.Syntax, elementConversion, argument, targetElementType); } } } /// <summary> /// This implements the casting behavior described in section 6.2.3 of the spec: /// /// - If the nullable conversion is from S to T?, the conversion is evaluated as the underlying conversion /// from S to T followed by a wrapping from T to T?. /// /// This particular check is done in the binder because it involves conversion processing rules (like overflow /// checking and constant folding) which are not handled by Conversions. /// </summary> private BoundExpression BindExplicitNullableCastFromNonNullable(ExpressionSyntax node, BoundExpression operand, TypeWithAnnotations targetTypeWithAnnotations, BindingDiagnosticBag diagnostics) { Debug.Assert(targetTypeWithAnnotations.HasType && targetTypeWithAnnotations.IsNullableType()); Debug.Assert((object)operand.Type != null && !operand.Type.IsNullableType()); // Section 6.2.3 of the spec only applies when the non-null version of the types involved have a // built in conversion. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; TypeWithAnnotations underlyingTargetTypeWithAnnotations = targetTypeWithAnnotations.Type.GetNullableUnderlyingTypeWithAnnotations(); var underlyingConversion = Conversions.ClassifyBuiltInConversion(operand.Type, underlyingTargetTypeWithAnnotations.Type, ref discardedUseSiteInfo); if (!underlyingConversion.Exists) { return BindCastCore(node, operand, targetTypeWithAnnotations, wasCompilerGenerated: operand.WasCompilerGenerated, diagnostics: diagnostics); } var bag = new BindingDiagnosticBag(DiagnosticBag.GetInstance(), diagnostics.DependenciesBag); try { var underlyingExpr = BindCastCore(node, operand, underlyingTargetTypeWithAnnotations, wasCompilerGenerated: false, diagnostics: bag); if (underlyingExpr.HasErrors || bag.HasAnyErrors()) { Error(diagnostics, ErrorCode.ERR_NoExplicitConv, node, operand.Type, targetTypeWithAnnotations.Type); return new BoundConversion( node, operand, Conversion.NoConversion, @checked: CheckOverflowAtRuntime, explicitCastInCode: true, conversionGroupOpt: new ConversionGroup(Conversion.NoConversion, explicitType: targetTypeWithAnnotations), constantValueOpt: ConstantValue.NotAvailable, type: targetTypeWithAnnotations.Type, hasErrors: true); } // It's possible for the S -> T conversion to produce a 'better' constant value. If this // constant value is produced place it in the tree so that it gets emitted. This maintains // parity with the native compiler which also evaluated the conversion at compile time. if (underlyingExpr.ConstantValue != null) { underlyingExpr.WasCompilerGenerated = true; return BindCastCore(node, underlyingExpr, targetTypeWithAnnotations, wasCompilerGenerated: operand.WasCompilerGenerated, diagnostics: diagnostics); } return BindCastCore(node, operand, targetTypeWithAnnotations, wasCompilerGenerated: operand.WasCompilerGenerated, diagnostics: diagnostics); } finally { bag.DiagnosticBag.Free(); } } private static NameSyntax GetNameSyntax(SyntaxNode syntax) { string nameString; return GetNameSyntax(syntax, out nameString); } /// <summary> /// Gets the NameSyntax associated with the syntax node /// If no syntax is attached it sets the nameString to plain text /// name and returns a null NameSyntax /// </summary> /// <param name="syntax">Syntax node</param> /// <param name="nameString">Plain text name</param> internal static NameSyntax GetNameSyntax(SyntaxNode syntax, out string nameString) { nameString = string.Empty; while (true) { switch (syntax.Kind()) { case SyntaxKind.PredefinedType: nameString = ((PredefinedTypeSyntax)syntax).Keyword.ValueText; return null; case SyntaxKind.SimpleLambdaExpression: nameString = MessageID.IDS_Lambda.Localize().ToString(); return null; case SyntaxKind.ParenthesizedExpression: syntax = ((ParenthesizedExpressionSyntax)syntax).Expression; continue; case SyntaxKind.CastExpression: syntax = ((CastExpressionSyntax)syntax).Expression; continue; case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: return ((MemberAccessExpressionSyntax)syntax).Name; case SyntaxKind.MemberBindingExpression: return ((MemberBindingExpressionSyntax)syntax).Name; default: return syntax as NameSyntax; } } } /// <summary> /// Gets the plain text name associated with the expression syntax node /// </summary> /// <param name="syntax">Expression syntax node</param> /// <returns>Plain text name</returns> private static string GetName(ExpressionSyntax syntax) { string nameString; var nameSyntax = GetNameSyntax(syntax, out nameString); if (nameSyntax != null) { return nameSyntax.GetUnqualifiedName().Identifier.ValueText; } return nameString; } // Given a list of arguments, create arrays of the bound arguments and the names of those // arguments. private void BindArgumentsAndNames(ArgumentListSyntax argumentListOpt, BindingDiagnosticBag diagnostics, AnalyzedArguments result, bool allowArglist = false, bool isDelegateCreation = false) { if (argumentListOpt != null) { BindArgumentsAndNames(argumentListOpt.Arguments, diagnostics, result, allowArglist, isDelegateCreation: isDelegateCreation); } } private void BindArgumentsAndNames(BracketedArgumentListSyntax argumentListOpt, BindingDiagnosticBag diagnostics, AnalyzedArguments result) { if (argumentListOpt != null) { BindArgumentsAndNames(argumentListOpt.Arguments, diagnostics, result, allowArglist: false); } } private void BindArgumentsAndNames( SeparatedSyntaxList<ArgumentSyntax> arguments, BindingDiagnosticBag diagnostics, AnalyzedArguments result, bool allowArglist, bool isDelegateCreation = false) { // Only report the first "duplicate name" or "named before positional" error, // so as to avoid "cascading" errors. bool hadError = false; // Only report the first "non-trailing named args required C# 7.2" error, // so as to avoid "cascading" errors. bool hadLangVersionError = false; foreach (var argumentSyntax in arguments) { BindArgumentAndName(result, diagnostics, ref hadError, ref hadLangVersionError, argumentSyntax, allowArglist, isDelegateCreation: isDelegateCreation); } } private bool RefMustBeObeyed(bool isDelegateCreation, ArgumentSyntax argumentSyntax) { if (Compilation.FeatureStrictEnabled || !isDelegateCreation) { return true; } switch (argumentSyntax.Expression.Kind()) { // The next 3 cases should never be allowed as they cannot be ref/out. Assuming a bug in legacy compiler. case SyntaxKind.ParenthesizedLambdaExpression: case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.AnonymousMethodExpression: case SyntaxKind.InvocationExpression: case SyntaxKind.ObjectCreationExpression: case SyntaxKind.ImplicitObjectCreationExpression: case SyntaxKind.ParenthesizedExpression: // this is never allowed in legacy compiler case SyntaxKind.DeclarationExpression: // A property/indexer is also invalid as it cannot be ref/out, but cannot be checked here. Assuming a bug in legacy compiler. return true; default: // The only ones that concern us here for compat is: locals, params, fields // BindArgumentAndName correctly rejects all other cases, except for properties and indexers. // They are handled after BindArgumentAndName returns and the binding can be checked. return false; } } private void BindArgumentAndName( AnalyzedArguments result, BindingDiagnosticBag diagnostics, ref bool hadError, ref bool hadLangVersionError, ArgumentSyntax argumentSyntax, bool allowArglist, bool isDelegateCreation = false) { RefKind origRefKind = argumentSyntax.RefOrOutKeyword.Kind().GetRefKind(); // The old native compiler ignores ref/out in a delegate creation expression. // For compatibility we implement the same bug except in strict mode. // Note: Some others should still be rejected when ref/out present. See RefMustBeObeyed. RefKind refKind = origRefKind == RefKind.None || RefMustBeObeyed(isDelegateCreation, argumentSyntax) ? origRefKind : RefKind.None; BoundExpression boundArgument = BindArgumentValue(diagnostics, argumentSyntax, allowArglist, refKind); BindArgumentAndName( result, diagnostics, ref hadLangVersionError, argumentSyntax, boundArgument, argumentSyntax.NameColon, refKind); // check for ref/out property/indexer, only needed for 1 parameter version if (!hadError && isDelegateCreation && origRefKind != RefKind.None && result.Arguments.Count == 1) { var arg = result.Argument(0); switch (arg.Kind) { case BoundKind.PropertyAccess: case BoundKind.IndexerAccess: var requiredValueKind = origRefKind == RefKind.In ? BindValueKind.ReadonlyRef : BindValueKind.RefOrOut; hadError = !CheckValueKind(argumentSyntax, arg, requiredValueKind, false, diagnostics); return; } } if (argumentSyntax.RefOrOutKeyword.Kind() != SyntaxKind.None) { argumentSyntax.Expression.CheckDeconstructionCompatibleArgument(diagnostics); } } private BoundExpression BindArgumentValue(BindingDiagnosticBag diagnostics, ArgumentSyntax argumentSyntax, bool allowArglist, RefKind refKind) { if (argumentSyntax.Expression.Kind() == SyntaxKind.DeclarationExpression) { var declarationExpression = (DeclarationExpressionSyntax)argumentSyntax.Expression; if (declarationExpression.IsOutDeclaration()) { return BindOutDeclarationArgument(declarationExpression, diagnostics); } } return BindArgumentExpression(diagnostics, argumentSyntax.Expression, refKind, allowArglist); } private BoundExpression BindOutDeclarationArgument(DeclarationExpressionSyntax declarationExpression, BindingDiagnosticBag diagnostics) { TypeSyntax typeSyntax = declarationExpression.Type; VariableDesignationSyntax designation = declarationExpression.Designation; if (typeSyntax.GetRefKind() != RefKind.None) { diagnostics.Add(ErrorCode.ERR_OutVariableCannotBeByRef, declarationExpression.Type.Location); } switch (designation.Kind()) { case SyntaxKind.DiscardDesignation: { bool isVar; bool isConst = false; AliasSymbol alias; var declType = BindVariableTypeWithAnnotations(designation, diagnostics, typeSyntax, ref isConst, out isVar, out alias); Debug.Assert(isVar != declType.HasType); return new BoundDiscardExpression(declarationExpression, declType.Type); } case SyntaxKind.SingleVariableDesignation: return BindOutVariableDeclarationArgument(declarationExpression, diagnostics); default: throw ExceptionUtilities.UnexpectedValue(designation.Kind()); } } private BoundExpression BindOutVariableDeclarationArgument( DeclarationExpressionSyntax declarationExpression, BindingDiagnosticBag diagnostics) { Debug.Assert(declarationExpression.IsOutVarDeclaration()); bool isVar; var designation = (SingleVariableDesignationSyntax)declarationExpression.Designation; TypeSyntax typeSyntax = declarationExpression.Type; // Is this a local? SourceLocalSymbol localSymbol = this.LookupLocal(designation.Identifier); if ((object)localSymbol != null) { Debug.Assert(localSymbol.DeclarationKind == LocalDeclarationKind.OutVariable); if ((InConstructorInitializer || InFieldInitializer) && ContainingMemberOrLambda.ContainingSymbol.Kind == SymbolKind.NamedType) { CheckFeatureAvailability(declarationExpression, MessageID.IDS_FeatureExpressionVariablesInQueriesAndInitializers, diagnostics); } bool isConst = false; AliasSymbol alias; var declType = BindVariableTypeWithAnnotations(declarationExpression, diagnostics, typeSyntax, ref isConst, out isVar, out alias); localSymbol.ScopeBinder.ValidateDeclarationNameConflictsInScope(localSymbol, diagnostics); if (isVar) { return new OutVariablePendingInference(declarationExpression, localSymbol, null); } CheckRestrictedTypeInAsyncMethod(this.ContainingMemberOrLambda, declType.Type, diagnostics, typeSyntax); return new BoundLocal(declarationExpression, localSymbol, BoundLocalDeclarationKind.WithExplicitType, constantValueOpt: null, isNullableUnknown: false, type: declType.Type); } // Is this a field? GlobalExpressionVariable expressionVariableField = LookupDeclaredField(designation); if ((object)expressionVariableField == null) { // We should have the right binder in the chain, cannot continue otherwise. throw ExceptionUtilities.Unreachable; } BoundExpression receiver = SynthesizeReceiver(designation, expressionVariableField, diagnostics); if (typeSyntax.IsVar) { BindTypeOrAliasOrVarKeyword(typeSyntax, BindingDiagnosticBag.Discarded, out isVar); if (isVar) { return new OutVariablePendingInference(declarationExpression, expressionVariableField, receiver); } } TypeSymbol fieldType = expressionVariableField.GetFieldType(this.FieldsBeingBound).Type; return new BoundFieldAccess(declarationExpression, receiver, expressionVariableField, null, LookupResultKind.Viable, isDeclaration: true, type: fieldType); } /// <summary> /// Returns true if a bad special by ref local was found. /// </summary> internal static bool CheckRestrictedTypeInAsyncMethod(Symbol containingSymbol, TypeSymbol type, BindingDiagnosticBag diagnostics, SyntaxNode syntax) { if (containingSymbol.Kind == SymbolKind.Method && ((MethodSymbol)containingSymbol).IsAsync && type.IsRestrictedType()) { Error(diagnostics, ErrorCode.ERR_BadSpecialByRefLocal, syntax, type); return true; } return false; } internal GlobalExpressionVariable LookupDeclaredField(SingleVariableDesignationSyntax variableDesignator) { return LookupDeclaredField(variableDesignator, variableDesignator.Identifier.ValueText); } internal GlobalExpressionVariable LookupDeclaredField(SyntaxNode node, string identifier) { foreach (Symbol member in ContainingType?.GetMembers(identifier) ?? ImmutableArray<Symbol>.Empty) { GlobalExpressionVariable field; if (member.Kind == SymbolKind.Field && (field = member as GlobalExpressionVariable)?.SyntaxTree == node.SyntaxTree && field.SyntaxNode == node) { return field; } } return null; } // Bind a named/positional argument. // Prevent cascading diagnostic by considering the previous // error state and returning the updated error state. private void BindArgumentAndName( AnalyzedArguments result, BindingDiagnosticBag diagnostics, ref bool hadLangVersionError, CSharpSyntaxNode argumentSyntax, BoundExpression boundArgumentExpression, NameColonSyntax nameColonSyntax, RefKind refKind) { Debug.Assert(argumentSyntax is ArgumentSyntax || argumentSyntax is AttributeArgumentSyntax); bool hasRefKinds = result.RefKinds.Any(); if (refKind != RefKind.None) { // The common case is no ref or out arguments. So we defer all work until the first one is seen. if (!hasRefKinds) { hasRefKinds = true; int argCount = result.Arguments.Count; for (int i = 0; i < argCount; ++i) { result.RefKinds.Add(RefKind.None); } } } if (hasRefKinds) { result.RefKinds.Add(refKind); } bool hasNames = result.Names.Any(); if (nameColonSyntax != null) { // The common case is no named arguments. So we defer all work until the first named argument is seen. if (!hasNames) { hasNames = true; int argCount = result.Arguments.Count; for (int i = 0; i < argCount; ++i) { result.Names.Add(null); } } result.AddName(nameColonSyntax.Name); } else if (hasNames) { // We just saw a fixed-position argument after a named argument. if (!hadLangVersionError && !Compilation.LanguageVersion.AllowNonTrailingNamedArguments()) { // CS1738: Named argument specifications must appear after all fixed arguments have been specified Error(diagnostics, ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, argumentSyntax, new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureNonTrailingNamedArguments.RequiredVersion())); hadLangVersionError = true; } result.Names.Add(null); } result.Arguments.Add(boundArgumentExpression); } /// <summary> /// Bind argument and verify argument matches rvalue or out param requirements. /// </summary> private BoundExpression BindArgumentExpression(BindingDiagnosticBag diagnostics, ExpressionSyntax argumentExpression, RefKind refKind, bool allowArglist) { BindValueKind valueKind = refKind == RefKind.None ? BindValueKind.RValue : refKind == RefKind.In ? BindValueKind.ReadonlyRef : BindValueKind.RefOrOut; BoundExpression argument; if (allowArglist) { argument = this.BindValueAllowArgList(argumentExpression, diagnostics, valueKind); } else { argument = this.BindValue(argumentExpression, diagnostics, valueKind); } return argument; } #nullable enable private void CoerceArguments<TMember>( MemberResolutionResult<TMember> methodResult, ArrayBuilder<BoundExpression> arguments, BindingDiagnosticBag diagnostics, TypeSymbol? receiverType, RefKind? receiverRefKind, uint receiverEscapeScope) where TMember : Symbol { var result = methodResult.Result; // Parameter types should be taken from the least overridden member: var parameters = methodResult.LeastOverriddenMember.GetParameters(); for (int arg = 0; arg < arguments.Count; ++arg) { var kind = result.ConversionForArg(arg); BoundExpression argument = arguments[arg]; if (kind.IsInterpolatedStringHandler) { Debug.Assert(argument is BoundUnconvertedInterpolatedString); TypeWithAnnotations parameterTypeWithAnnotations = GetCorrespondingParameterTypeWithAnnotations(ref result, parameters, arg); reportUnsafeIfNeeded(methodResult, diagnostics, argument, parameterTypeWithAnnotations); arguments[arg] = BindInterpolatedStringHandlerInMemberCall((BoundUnconvertedInterpolatedString)argument, arguments, parameters, ref result, arg, receiverType, receiverRefKind, receiverEscapeScope, diagnostics); } // https://github.com/dotnet/roslyn/issues/37119 : should we create an (Identity) conversion when the kind is Identity but the types differ? else if (!kind.IsIdentity) { TypeWithAnnotations parameterTypeWithAnnotations = GetCorrespondingParameterTypeWithAnnotations(ref result, parameters, arg); reportUnsafeIfNeeded(methodResult, diagnostics, argument, parameterTypeWithAnnotations); arguments[arg] = CreateConversion(argument.Syntax, argument, kind, isCast: false, conversionGroupOpt: null, parameterTypeWithAnnotations.Type, diagnostics); } else if (argument.Kind == BoundKind.OutVariablePendingInference) { TypeWithAnnotations parameterTypeWithAnnotations = GetCorrespondingParameterTypeWithAnnotations(ref result, parameters, arg); arguments[arg] = ((OutVariablePendingInference)argument).SetInferredTypeWithAnnotations(parameterTypeWithAnnotations, diagnostics); } else if (argument.Kind == BoundKind.OutDeconstructVarPendingInference) { TypeWithAnnotations parameterTypeWithAnnotations = GetCorrespondingParameterTypeWithAnnotations(ref result, parameters, arg); arguments[arg] = ((OutDeconstructVarPendingInference)argument).SetInferredTypeWithAnnotations(parameterTypeWithAnnotations, this, success: true); } else if (argument.Kind == BoundKind.DiscardExpression && !argument.HasExpressionType()) { TypeWithAnnotations parameterTypeWithAnnotations = GetCorrespondingParameterTypeWithAnnotations(ref result, parameters, arg); Debug.Assert(parameterTypeWithAnnotations.HasType); arguments[arg] = ((BoundDiscardExpression)argument).SetInferredTypeWithAnnotations(parameterTypeWithAnnotations); } else if (argument.NeedsToBeConverted()) { Debug.Assert(kind.IsIdentity); if (argument is BoundTupleLiteral) { TypeWithAnnotations parameterTypeWithAnnotations = GetCorrespondingParameterTypeWithAnnotations(ref result, parameters, arg); // CreateConversion reports tuple literal name mismatches, and constructs the expected pattern of bound nodes. arguments[arg] = CreateConversion(argument.Syntax, argument, kind, isCast: false, conversionGroupOpt: null, parameterTypeWithAnnotations.Type, diagnostics); } else { arguments[arg] = BindToNaturalType(argument, diagnostics); } } } void reportUnsafeIfNeeded(MemberResolutionResult<TMember> methodResult, BindingDiagnosticBag diagnostics, BoundExpression argument, TypeWithAnnotations parameterTypeWithAnnotations) { // NOTE: for some reason, dev10 doesn't report this for indexer accesses. if (!methodResult.Member.IsIndexer() && !argument.HasAnyErrors && parameterTypeWithAnnotations.Type.IsUnsafe()) { // CONSIDER: dev10 uses the call syntax, but this seems clearer. ReportUnsafeIfNotAllowed(argument.Syntax, diagnostics); //CONSIDER: Return a bad expression so that HasErrors is true? } } } private static ParameterSymbol GetCorrespondingParameter(ref MemberAnalysisResult result, ImmutableArray<ParameterSymbol> parameters, int arg) { int paramNum = result.ParameterFromArgument(arg); return parameters[paramNum]; } #nullable disable private static TypeWithAnnotations GetCorrespondingParameterTypeWithAnnotations(ref MemberAnalysisResult result, ImmutableArray<ParameterSymbol> parameters, int arg) { int paramNum = result.ParameterFromArgument(arg); var type = parameters[paramNum].TypeWithAnnotations; if (paramNum == parameters.Length - 1 && result.Kind == MemberResolutionKind.ApplicableInExpandedForm) { type = ((ArrayTypeSymbol)type.Type).ElementTypeWithAnnotations; } return type; } private BoundExpression BindArrayCreationExpression(ArrayCreationExpressionSyntax node, BindingDiagnosticBag diagnostics) { // SPEC begins // // An array-creation-expression is used to create a new instance of an array-type. // // array-creation-expression: // new non-array-type[expression-list] rank-specifiersopt array-initializeropt // new array-type array-initializer // new rank-specifier array-initializer // // An array creation expression of the first form allocates an array instance of the // type that results from deleting each of the individual expressions from the // expression list. For example, the array creation expression new int[10, 20] produces // an array instance of type int[,], and the array creation expression new int[10][,] // produces an array of type int[][,]. Each expression in the expression list must be of // type int, uint, long, or ulong, or implicitly convertible to one or more of these // types. The value of each expression determines the length of the corresponding // dimension in the newly allocated array instance. Since the length of an array // dimension must be nonnegative, it is a compile-time error to have a // constant-expression with a negative value in the expression list. // // If an array creation expression of the first form includes an array initializer, each // expression in the expression list must be a constant and the rank and dimension // lengths specified by the expression list must match those of the array initializer. // // In an array creation expression of the second or third form, the rank of the // specified array type or rank specifier must match that of the array initializer. The // individual dimension lengths are inferred from the number of elements in each of the // corresponding nesting levels of the array initializer. Thus, the expression new // int[,] {{0, 1}, {2, 3}, {4, 5}} exactly corresponds to new int[3, 2] {{0, 1}, {2, 3}, // {4, 5}} // // An array creation expression of the third form is referred to as an implicitly typed // array creation expression. It is similar to the second form, except that the element // type of the array is not explicitly given, but determined as the best common type // (7.5.2.14) of the set of expressions in the array initializer. For a multidimensional // array, i.e., one where the rank-specifier contains at least one comma, this set // comprises all expressions found in nested array-initializers. // // An array creation expression permits instantiation of an array with elements of an // array type, but the elements of such an array must be manually initialized. For // example, the statement // // int[][] a = new int[100][]; // // creates a single-dimensional array with 100 elements of type int[]. The initial value // of each element is null. It is not possible for the same array creation expression to // also instantiate the sub-arrays, and the statement // // int[][] a = new int[100][5]; // Error // // results in a compile-time error. // // The following are examples of implicitly typed array creation expressions: // // var a = new[] { 1, 10, 100, 1000 }; // int[] // var b = new[] { 1, 1.5, 2, 2.5 }; // double[] // var c = new[,] { { "hello", null }, { "world", "!" } }; // string[,] // var d = new[] { 1, "one", 2, "two" }; // Error // // The last expression causes a compile-time error because neither int nor string is // implicitly convertible to the other, and so there is no best common type. An // explicitly typed array creation expression must be used in this case, for example // specifying the type to be object[]. Alternatively, one of the elements can be cast to // a common base type, which would then become the inferred element type. // // SPEC ends var type = (ArrayTypeSymbol)BindArrayType(node.Type, diagnostics, permitDimensions: true, basesBeingResolved: null, disallowRestrictedTypes: true).Type; // CONSIDER: // // There may be erroneous rank specifiers in the source code, for example: // // int y = 123; // int[][] z = new int[10][y]; // // The "10" is legal but the "y" is not. If we are in such a situation we do have the // "y" expression syntax stashed away in the syntax tree. However, we do *not* perform // semantic analysis. This means that "go to definition" on "y" does not work, and so // on. We might consider doing a semantic analysis here (with error suppression; a parse // error has already been reported) so that "go to definition" works. ArrayBuilder<BoundExpression> sizes = ArrayBuilder<BoundExpression>.GetInstance(); ArrayRankSpecifierSyntax firstRankSpecifier = node.Type.RankSpecifiers[0]; bool hasErrors = false; foreach (var arg in firstRankSpecifier.Sizes) { var size = BindArrayDimension(arg, diagnostics, ref hasErrors); if (size != null) { sizes.Add(size); } else if (node.Initializer is null && arg == firstRankSpecifier.Sizes[0]) { Error(diagnostics, ErrorCode.ERR_MissingArraySize, firstRankSpecifier); hasErrors = true; } } // produce errors for additional sizes in the ranks for (int additionalRankIndex = 1; additionalRankIndex < node.Type.RankSpecifiers.Count; additionalRankIndex++) { var rank = node.Type.RankSpecifiers[additionalRankIndex]; var dimension = rank.Sizes; foreach (var arg in dimension) { if (arg.Kind() != SyntaxKind.OmittedArraySizeExpression) { var size = BindRValueWithoutTargetType(arg, diagnostics); Error(diagnostics, ErrorCode.ERR_InvalidArray, arg); hasErrors = true; // Capture the invalid sizes for `SemanticModel` and `IOperation` sizes.Add(size); } } } ImmutableArray<BoundExpression> arraySizes = sizes.ToImmutableAndFree(); return node.Initializer == null ? new BoundArrayCreation(node, arraySizes, null, type, hasErrors) : BindArrayCreationWithInitializer(diagnostics, node, node.Initializer, type, arraySizes, hasErrors: hasErrors); } private BoundExpression BindArrayDimension(ExpressionSyntax dimension, BindingDiagnosticBag diagnostics, ref bool hasErrors) { // These make the parse tree nicer, but they shouldn't actually appear in the bound tree. if (dimension.Kind() != SyntaxKind.OmittedArraySizeExpression) { var size = BindValue(dimension, diagnostics, BindValueKind.RValue); if (!size.HasAnyErrors) { size = ConvertToArrayIndex(size, diagnostics, allowIndexAndRange: false); if (IsNegativeConstantForArraySize(size)) { Error(diagnostics, ErrorCode.ERR_NegativeArraySize, dimension); hasErrors = true; } } else { size = BindToTypeForErrorRecovery(size); } return size; } return null; } private BoundExpression BindImplicitArrayCreationExpression(ImplicitArrayCreationExpressionSyntax node, BindingDiagnosticBag diagnostics) { // See BindArrayCreationExpression method above for implicitly typed array creation SPEC. InitializerExpressionSyntax initializer = node.Initializer; int rank = node.Commas.Count + 1; ImmutableArray<BoundExpression> boundInitializerExpressions = BindArrayInitializerExpressions(initializer, diagnostics, dimension: 1, rank: rank); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); TypeSymbol bestType = BestTypeInferrer.InferBestType(boundInitializerExpressions, this.Conversions, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if ((object)bestType == null || bestType.IsVoidType()) // Dev10 also reports ERR_ImplicitlyTypedArrayNoBestType for void. { Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, node); bestType = CreateErrorType(); } if (bestType.IsRestrictedType()) { // CS0611: Array elements cannot be of type '{0}' Error(diagnostics, ErrorCode.ERR_ArrayElementCantBeRefAny, node, bestType); } // Element type nullability will be inferred in flow analysis and does not need to be set here. var arrayType = ArrayTypeSymbol.CreateCSharpArray(Compilation.Assembly, TypeWithAnnotations.Create(bestType), rank); return BindArrayCreationWithInitializer(diagnostics, node, initializer, arrayType, sizes: ImmutableArray<BoundExpression>.Empty, boundInitExprOpt: boundInitializerExpressions); } private BoundExpression BindImplicitStackAllocArrayCreationExpression(ImplicitStackAllocArrayCreationExpressionSyntax node, BindingDiagnosticBag diagnostics) { InitializerExpressionSyntax initializer = node.Initializer; ImmutableArray<BoundExpression> boundInitializerExpressions = BindArrayInitializerExpressions(initializer, diagnostics, dimension: 1, rank: 1); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); TypeSymbol bestType = BestTypeInferrer.InferBestType(boundInitializerExpressions, this.Conversions, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if ((object)bestType == null || bestType.IsVoidType()) { Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, node); bestType = CreateErrorType(); } if (!bestType.IsErrorType()) { CheckManagedAddr(Compilation, bestType, node.Location, diagnostics); } return BindStackAllocWithInitializer( node, initializer, type: GetStackAllocType(node, TypeWithAnnotations.Create(bestType), diagnostics, out bool hasErrors), elementType: bestType, sizeOpt: null, diagnostics, hasErrors: hasErrors, boundInitializerExpressions); } // This method binds all the array initializer expressions. // NOTE: It doesn't convert the bound initializer expressions to array's element type. // NOTE: This is done separately in ConvertAndBindArrayInitialization method below. private ImmutableArray<BoundExpression> BindArrayInitializerExpressions(InitializerExpressionSyntax initializer, BindingDiagnosticBag diagnostics, int dimension, int rank) { var exprBuilder = ArrayBuilder<BoundExpression>.GetInstance(); BindArrayInitializerExpressions(initializer, exprBuilder, diagnostics, dimension, rank); return exprBuilder.ToImmutableAndFree(); } /// <summary> /// This method walks through the array's InitializerExpressionSyntax and binds all the initializer expressions recursively. /// NOTE: It doesn't convert the bound initializer expressions to array's element type. /// NOTE: This is done separately in ConvertAndBindArrayInitialization method below. /// </summary> /// <param name="initializer">Initializer Syntax.</param> /// <param name="exprBuilder">Bound expression builder.</param> /// <param name="diagnostics">Diagnostics.</param> /// <param name="dimension">Current array dimension being processed.</param> /// <param name="rank">Rank of the array type.</param> private void BindArrayInitializerExpressions(InitializerExpressionSyntax initializer, ArrayBuilder<BoundExpression> exprBuilder, BindingDiagnosticBag diagnostics, int dimension, int rank) { Debug.Assert(rank > 0); Debug.Assert(dimension > 0 && dimension <= rank); Debug.Assert(exprBuilder != null); if (dimension == rank) { // We are processing the nth dimension of a rank-n array. We expect that these will // only be values, not array initializers. foreach (var expression in initializer.Expressions) { var boundExpression = BindValue(expression, diagnostics, BindValueKind.RValue); exprBuilder.Add(boundExpression); } } else { // Inductive case; we'd better have another array initializer foreach (var expression in initializer.Expressions) { if (expression.Kind() == SyntaxKind.ArrayInitializerExpression) { BindArrayInitializerExpressions((InitializerExpressionSyntax)expression, exprBuilder, diagnostics, dimension + 1, rank); } else { // We have non-array initializer expression, but we expected an array initializer expression. var boundExpression = BindValue(expression, diagnostics, BindValueKind.RValue); if ((object)boundExpression.Type == null || !boundExpression.Type.IsErrorType()) { if (!boundExpression.HasAnyErrors) { Error(diagnostics, ErrorCode.ERR_ArrayInitializerExpected, expression); } // Wrap the expression with a bound bad expression with error type. boundExpression = BadExpression( expression, LookupResultKind.Empty, ImmutableArray.Create(boundExpression.ExpressionSymbol), ImmutableArray.Create(boundExpression)); } exprBuilder.Add(boundExpression); } } } } /// <summary> /// Given an array of bound initializer expressions, this method converts these bound expressions /// to array's element type and generates a BoundArrayInitialization with the converted initializers. /// </summary> /// <param name="diagnostics">Diagnostics.</param> /// <param name="node">Initializer Syntax.</param> /// <param name="type">Array type.</param> /// <param name="knownSizes">Known array bounds.</param> /// <param name="dimension">Current array dimension being processed.</param> /// <param name="boundInitExpr">Array of bound initializer expressions.</param> /// <param name="boundInitExprIndex"> /// Index into the array of bound initializer expressions to fetch the next bound expression. /// </param> /// <returns></returns> private BoundArrayInitialization ConvertAndBindArrayInitialization( BindingDiagnosticBag diagnostics, InitializerExpressionSyntax node, ArrayTypeSymbol type, int?[] knownSizes, int dimension, ImmutableArray<BoundExpression> boundInitExpr, ref int boundInitExprIndex) { Debug.Assert(!boundInitExpr.IsDefault); ArrayBuilder<BoundExpression> initializers = ArrayBuilder<BoundExpression>.GetInstance(); if (dimension == type.Rank) { // We are processing the nth dimension of a rank-n array. We expect that these will // only be values, not array initializers. TypeSymbol elemType = type.ElementType; foreach (var expressionSyntax in node.Expressions) { Debug.Assert(boundInitExprIndex >= 0 && boundInitExprIndex < boundInitExpr.Length); BoundExpression boundExpression = boundInitExpr[boundInitExprIndex]; boundInitExprIndex++; BoundExpression convertedExpression = GenerateConversionForAssignment(elemType, boundExpression, diagnostics); initializers.Add(convertedExpression); } } else { // Inductive case; we'd better have another array initializer foreach (var expr in node.Expressions) { BoundExpression init = null; if (expr.Kind() == SyntaxKind.ArrayInitializerExpression) { init = ConvertAndBindArrayInitialization(diagnostics, (InitializerExpressionSyntax)expr, type, knownSizes, dimension + 1, boundInitExpr, ref boundInitExprIndex); } else { // We have non-array initializer expression, but we expected an array initializer expression. // We have already generated the diagnostics during binding, so just fetch the bound expression. Debug.Assert(boundInitExprIndex >= 0 && boundInitExprIndex < boundInitExpr.Length); init = boundInitExpr[boundInitExprIndex]; Debug.Assert(init.HasAnyErrors); Debug.Assert(init.Type.IsErrorType()); boundInitExprIndex++; } initializers.Add(init); } } bool hasErrors = false; var knownSizeOpt = knownSizes[dimension - 1]; if (knownSizeOpt == null) { knownSizes[dimension - 1] = initializers.Count; } else if (knownSizeOpt != initializers.Count) { // No need to report an error if the known size is negative // since we've already reported CS0248 earlier and it's // expected that the number of initializers won't match. if (knownSizeOpt >= 0) { Error(diagnostics, ErrorCode.ERR_ArrayInitializerIncorrectLength, node, knownSizeOpt.Value); hasErrors = true; } } return new BoundArrayInitialization(node, initializers.ToImmutableAndFree(), hasErrors: hasErrors); } private BoundArrayInitialization BindArrayInitializerList( BindingDiagnosticBag diagnostics, InitializerExpressionSyntax node, ArrayTypeSymbol type, int?[] knownSizes, int dimension, ImmutableArray<BoundExpression> boundInitExprOpt = default(ImmutableArray<BoundExpression>)) { // Bind the array initializer expressions, if not already bound. // NOTE: Initializer expressions might already be bound for implicitly type array creation // NOTE: during array's element type inference. if (boundInitExprOpt.IsDefault) { boundInitExprOpt = BindArrayInitializerExpressions(node, diagnostics, dimension, type.Rank); } // Convert the bound array initializer expressions to array's element type and // generate BoundArrayInitialization with the converted initializers. int boundInitExprIndex = 0; return ConvertAndBindArrayInitialization(diagnostics, node, type, knownSizes, dimension, boundInitExprOpt, ref boundInitExprIndex); } private BoundArrayInitialization BindUnexpectedArrayInitializer( InitializerExpressionSyntax node, BindingDiagnosticBag diagnostics, ErrorCode errorCode, CSharpSyntaxNode errorNode = null) { var result = BindArrayInitializerList( diagnostics, node, this.Compilation.CreateArrayTypeSymbol(GetSpecialType(SpecialType.System_Object, diagnostics, node)), new int?[1], dimension: 1); if (!result.HasAnyErrors) { result = new BoundArrayInitialization(node, result.Initializers, hasErrors: true); } Error(diagnostics, errorCode, errorNode ?? node); return result; } // We could be in the cases // // (1) int[] x = { a, b } // (2) new int[] { a, b } // (3) new int[2] { a, b } // (4) new [] { a, b } // // In case (1) there is no creation syntax. // In cases (2) and (3) creation syntax is an ArrayCreationExpression. // In case (4) creation syntax is an ImplicitArrayCreationExpression. // // In cases (1), (2) and (4) there are no sizes. // // The initializer syntax is always provided. // // If we are in case (3) and sizes are provided then the number of sizes must match the rank // of the array type passed in. // For case (4), i.e. ImplicitArrayCreationExpression, we must have already bound the // initializer expressions for best type inference. // These bound expressions are stored in boundInitExprOpt and reused in creating // BoundArrayInitialization to avoid binding them twice. private BoundArrayCreation BindArrayCreationWithInitializer( BindingDiagnosticBag diagnostics, ExpressionSyntax creationSyntax, InitializerExpressionSyntax initSyntax, ArrayTypeSymbol type, ImmutableArray<BoundExpression> sizes, ImmutableArray<BoundExpression> boundInitExprOpt = default(ImmutableArray<BoundExpression>), bool hasErrors = false) { Debug.Assert(creationSyntax == null || creationSyntax.Kind() == SyntaxKind.ArrayCreationExpression || creationSyntax.Kind() == SyntaxKind.ImplicitArrayCreationExpression); Debug.Assert(initSyntax != null); Debug.Assert((object)type != null); Debug.Assert(boundInitExprOpt.IsDefault || creationSyntax.Kind() == SyntaxKind.ImplicitArrayCreationExpression); // NOTE: In error scenarios, it may be the case sizes.Count > type.Rank. // For example, new int[1 2] has 2 sizes, but rank 1 (since there are 0 commas). int rank = type.Rank; int numSizes = sizes.Length; int?[] knownSizes = new int?[Math.Max(rank, numSizes)]; // If there are sizes given and there is an array initializer, then every size must be a // constant. (We'll check later that it matches) for (int i = 0; i < numSizes; ++i) { // Here we are being bug-for-bug compatible with C# 4. When you have code like // byte[] b = new[uint.MaxValue] { 2 }; // you might expect an error that says that the number of elements in the initializer does // not match the size of the array. But in C# 4 if the constant does not fit into an integer // then we confusingly give the error "that's not a constant". // NOTE: in the example above, GetIntegerConstantForArraySize is returning null because the // size doesn't fit in an int - not because it doesn't match the initializer length. var size = sizes[i]; knownSizes[i] = GetIntegerConstantForArraySize(size); if (!size.HasAnyErrors && knownSizes[i] == null) { Error(diagnostics, ErrorCode.ERR_ConstantExpected, size.Syntax); hasErrors = true; } } // KnownSizes is further mutated by BindArrayInitializerList as it works out more // information about the sizes. BoundArrayInitialization initializer = BindArrayInitializerList(diagnostics, initSyntax, type, knownSizes, 1, boundInitExprOpt); hasErrors = hasErrors || initializer.HasAnyErrors; bool hasCreationSyntax = creationSyntax != null; CSharpSyntaxNode nonNullSyntax = (CSharpSyntaxNode)creationSyntax ?? initSyntax; // Construct a set of size expressions if we were not given any. // // It is possible in error scenarios that some of the bounds were not determined. Substitute // zeroes for those. if (numSizes == 0) { BoundExpression[] sizeArray = new BoundExpression[rank]; for (int i = 0; i < rank; i++) { sizeArray[i] = new BoundLiteral( nonNullSyntax, ConstantValue.Create(knownSizes[i] ?? 0), GetSpecialType(SpecialType.System_Int32, diagnostics, nonNullSyntax)) { WasCompilerGenerated = true }; } sizes = sizeArray.AsImmutableOrNull(); } else if (!hasErrors && rank != numSizes) { Error(diagnostics, ErrorCode.ERR_BadIndexCount, nonNullSyntax, type.Rank); hasErrors = true; } return new BoundArrayCreation(nonNullSyntax, sizes, initializer, type, hasErrors: hasErrors) { WasCompilerGenerated = !hasCreationSyntax && (initSyntax.Parent == null || initSyntax.Parent.Kind() != SyntaxKind.EqualsValueClause || ((EqualsValueClauseSyntax)initSyntax.Parent).Value != initSyntax) }; } private BoundExpression BindStackAllocArrayCreationExpression( StackAllocArrayCreationExpressionSyntax node, BindingDiagnosticBag diagnostics) { TypeSyntax typeSyntax = node.Type; if (typeSyntax.Kind() != SyntaxKind.ArrayType) { Error(diagnostics, ErrorCode.ERR_BadStackAllocExpr, typeSyntax); return new BoundBadExpression( node, LookupResultKind.NotCreatable, //in this context, anyway ImmutableArray<Symbol>.Empty, ImmutableArray<BoundExpression>.Empty, new PointerTypeSymbol(BindType(typeSyntax, diagnostics))); } ArrayTypeSyntax arrayTypeSyntax = (ArrayTypeSyntax)typeSyntax; var elementTypeSyntax = arrayTypeSyntax.ElementType; var arrayType = (ArrayTypeSymbol)BindArrayType(arrayTypeSyntax, diagnostics, permitDimensions: true, basesBeingResolved: null, disallowRestrictedTypes: false).Type; var elementType = arrayType.ElementTypeWithAnnotations; TypeSymbol type = GetStackAllocType(node, elementType, diagnostics, out bool hasErrors); if (!elementType.Type.IsErrorType()) { hasErrors = hasErrors || CheckManagedAddr(Compilation, elementType.Type, elementTypeSyntax.Location, diagnostics); } SyntaxList<ArrayRankSpecifierSyntax> rankSpecifiers = arrayTypeSyntax.RankSpecifiers; if (rankSpecifiers.Count != 1 || rankSpecifiers[0].Sizes.Count != 1) { // NOTE: Dev10 reported several parse errors here. Error(diagnostics, ErrorCode.ERR_BadStackAllocExpr, typeSyntax); var builder = ArrayBuilder<BoundExpression>.GetInstance(); foreach (ArrayRankSpecifierSyntax rankSpecifier in rankSpecifiers) { foreach (ExpressionSyntax size in rankSpecifier.Sizes) { if (size.Kind() != SyntaxKind.OmittedArraySizeExpression) { builder.Add(BindExpression(size, BindingDiagnosticBag.Discarded)); } } } return new BoundBadExpression( node, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, builder.ToImmutableAndFree(), new PointerTypeSymbol(elementType)); } ExpressionSyntax countSyntax = rankSpecifiers[0].Sizes[0]; BoundExpression count = null; if (countSyntax.Kind() != SyntaxKind.OmittedArraySizeExpression) { count = BindValue(countSyntax, diagnostics, BindValueKind.RValue); count = GenerateConversionForAssignment(GetSpecialType(SpecialType.System_Int32, diagnostics, node), count, diagnostics); if (IsNegativeConstantForArraySize(count)) { Error(diagnostics, ErrorCode.ERR_NegativeStackAllocSize, countSyntax); hasErrors = true; } } else if (node.Initializer == null) { Error(diagnostics, ErrorCode.ERR_MissingArraySize, rankSpecifiers[0]); count = BadExpression(countSyntax); hasErrors = true; } return node.Initializer == null ? new BoundStackAllocArrayCreation(node, elementType.Type, count, initializerOpt: null, type, hasErrors: hasErrors) : BindStackAllocWithInitializer(node, node.Initializer, type, elementType.Type, count, diagnostics, hasErrors); } private bool ReportBadStackAllocPosition(SyntaxNode node, BindingDiagnosticBag diagnostics) { Debug.Assert(node is StackAllocArrayCreationExpressionSyntax || node is ImplicitStackAllocArrayCreationExpressionSyntax); bool inLegalPosition = true; // If we are using a language version that does not restrict the position of a stackalloc expression, skip that test. LanguageVersion requiredVersion = MessageID.IDS_FeatureNestedStackalloc.RequiredVersion(); if (requiredVersion > Compilation.LanguageVersion) { inLegalPosition = (IsInMethodBody || IsLocalFunctionsScopeBinder) && node.IsLegalCSharp73SpanStackAllocPosition(); if (!inLegalPosition) { MessageID.IDS_FeatureNestedStackalloc.CheckFeatureAvailability(diagnostics, node, node.GetFirstToken().GetLocation()); } } // Check if we're syntactically within a catch or finally clause. if (this.Flags.IncludesAny(BinderFlags.InCatchBlock | BinderFlags.InCatchFilter | BinderFlags.InFinallyBlock)) { Error(diagnostics, ErrorCode.ERR_StackallocInCatchFinally, node); } return inLegalPosition; } private TypeSymbol GetStackAllocType(SyntaxNode node, TypeWithAnnotations elementTypeWithAnnotations, BindingDiagnosticBag diagnostics, out bool hasErrors) { var inLegalPosition = ReportBadStackAllocPosition(node, diagnostics); hasErrors = !inLegalPosition; if (inLegalPosition && !isStackallocTargetTyped(node)) { CheckFeatureAvailability(node, MessageID.IDS_FeatureRefStructs, diagnostics); var spanType = GetWellKnownType(WellKnownType.System_Span_T, diagnostics, node); return ConstructNamedType( type: spanType, typeSyntax: node.Kind() == SyntaxKind.StackAllocArrayCreationExpression ? ((StackAllocArrayCreationExpressionSyntax)node).Type : node, typeArgumentsSyntax: default, typeArguments: ImmutableArray.Create(elementTypeWithAnnotations), basesBeingResolved: null, diagnostics: diagnostics); } // We treat the stackalloc as target-typed, so we give it a null type for now. return null; // Is this a context in which a stackalloc expression could be converted to the corresponding pointer // type? The only context that permits it is the initialization of a local variable declaration (when // the declaration appears as a statement or as the first part of a for loop). static bool isStackallocTargetTyped(SyntaxNode node) { Debug.Assert(node != null); SyntaxNode equalsValueClause = node.Parent; if (!equalsValueClause.IsKind(SyntaxKind.EqualsValueClause)) { return false; } SyntaxNode variableDeclarator = equalsValueClause.Parent; if (!variableDeclarator.IsKind(SyntaxKind.VariableDeclarator)) { return false; } SyntaxNode variableDeclaration = variableDeclarator.Parent; if (!variableDeclaration.IsKind(SyntaxKind.VariableDeclaration)) { return false; } return variableDeclaration.Parent.IsKind(SyntaxKind.LocalDeclarationStatement) || variableDeclaration.Parent.IsKind(SyntaxKind.ForStatement); } } private BoundExpression BindStackAllocWithInitializer( SyntaxNode node, InitializerExpressionSyntax initSyntax, TypeSymbol type, TypeSymbol elementType, BoundExpression sizeOpt, BindingDiagnosticBag diagnostics, bool hasErrors, ImmutableArray<BoundExpression> boundInitExprOpt = default) { Debug.Assert(node.IsKind(SyntaxKind.ImplicitStackAllocArrayCreationExpression) || node.IsKind(SyntaxKind.StackAllocArrayCreationExpression)); if (boundInitExprOpt.IsDefault) { boundInitExprOpt = BindArrayInitializerExpressions(initSyntax, diagnostics, dimension: 1, rank: 1); } boundInitExprOpt = boundInitExprOpt.SelectAsArray((expr, t) => GenerateConversionForAssignment(t.elementType, expr, t.diagnostics), (elementType, diagnostics)); if (sizeOpt != null) { if (!sizeOpt.HasAnyErrors) { int? constantSizeOpt = GetIntegerConstantForArraySize(sizeOpt); if (constantSizeOpt == null) { Error(diagnostics, ErrorCode.ERR_ConstantExpected, sizeOpt.Syntax); hasErrors = true; } else if (boundInitExprOpt.Length != constantSizeOpt) { Error(diagnostics, ErrorCode.ERR_ArrayInitializerIncorrectLength, node, constantSizeOpt.Value); hasErrors = true; } } } else { sizeOpt = new BoundLiteral( node, ConstantValue.Create(boundInitExprOpt.Length), GetSpecialType(SpecialType.System_Int32, diagnostics, node)) { WasCompilerGenerated = true }; } return new BoundStackAllocArrayCreation(node, elementType, sizeOpt, new BoundArrayInitialization(initSyntax, boundInitExprOpt), type, hasErrors); } private static int? GetIntegerConstantForArraySize(BoundExpression expression) { // If the bound could have been converted to int, then it was. If it could not have been // converted to int, and it was a constant, then it was out of range. Debug.Assert(expression != null); if (expression.HasAnyErrors) { return null; } var constantValue = expression.ConstantValue; if (constantValue == null || constantValue.IsBad || expression.Type.SpecialType != SpecialType.System_Int32) { return null; } return constantValue.Int32Value; } private static bool IsNegativeConstantForArraySize(BoundExpression expression) { Debug.Assert(expression != null); if (expression.HasAnyErrors) { return false; } var constantValue = expression.ConstantValue; if (constantValue == null || constantValue.IsBad) { return false; } var type = expression.Type.SpecialType; if (type == SpecialType.System_Int32) { return constantValue.Int32Value < 0; } if (type == SpecialType.System_Int64) { return constantValue.Int64Value < 0; } // By the time we get here we definitely have int, long, uint or ulong. Obviously the // latter two are never negative. Debug.Assert(type == SpecialType.System_UInt32 || type == SpecialType.System_UInt64); return false; } /// <summary> /// Bind the (implicit or explicit) constructor initializer of a constructor symbol (in source). /// </summary> /// <param name="initializerArgumentListOpt"> /// Null for implicit, /// <see cref="ConstructorInitializerSyntax.ArgumentList"/>, or /// <see cref="PrimaryConstructorBaseTypeSyntax.ArgumentList"/> for explicit.</param> /// <param name="constructor">Constructor containing the initializer.</param> /// <param name="diagnostics">Accumulates errors (e.g. unable to find constructor to invoke).</param> /// <returns>A bound expression for the constructor initializer call.</returns> /// <remarks> /// This method should be kept consistent with Compiler.BindConstructorInitializer (e.g. same error codes). /// </remarks> internal BoundExpression BindConstructorInitializer( ArgumentListSyntax initializerArgumentListOpt, MethodSymbol constructor, BindingDiagnosticBag diagnostics) { Binder argumentListBinder = null; if (initializerArgumentListOpt != null) { argumentListBinder = this.GetBinder(initializerArgumentListOpt); } var result = (argumentListBinder ?? this).BindConstructorInitializerCore(initializerArgumentListOpt, constructor, diagnostics); if (argumentListBinder != null) { // This code is reachable only for speculative SemanticModel. Debug.Assert(argumentListBinder.IsSemanticModelBinder); result = argumentListBinder.WrapWithVariablesIfAny(initializerArgumentListOpt, result); } return result; } private BoundExpression BindConstructorInitializerCore( ArgumentListSyntax initializerArgumentListOpt, MethodSymbol constructor, BindingDiagnosticBag diagnostics) { // Either our base type is not object, or we have an initializer syntax, or both. We're going to // need to do overload resolution on the set of constructors of the base type, either on // the provided initializer syntax, or on an implicit ": base()" syntax. // SPEC ERROR: The specification states that if you have the situation // SPEC ERROR: class B { ... } class D1 : B {} then the default constructor // SPEC ERROR: generated for D1 must call an accessible *parameterless* constructor // SPEC ERROR: in B. However, it also states that if you have // SPEC ERROR: class B { ... } class D2 : B { D2() {} } or // SPEC ERROR: class B { ... } class D3 : B { D3() : base() {} } then // SPEC ERROR: the compiler performs *overload resolution* to determine // SPEC ERROR: which accessible constructor of B is called. Since B might have // SPEC ERROR: a ctor with all optional parameters, overload resolution might // SPEC ERROR: succeed even if there is no parameterless constructor. This // SPEC ERROR: is unintentionally inconsistent, and the native compiler does not // SPEC ERROR: implement this behavior. Rather, we should say in the spec that // SPEC ERROR: if there is no ctor in D1, then a ctor is created for you exactly // SPEC ERROR: as though you'd said "D1() : base() {}". // SPEC ERROR: This is what we now do in Roslyn. Debug.Assert((object)constructor != null); Debug.Assert(constructor.MethodKind == MethodKind.Constructor || constructor.MethodKind == MethodKind.StaticConstructor); // error scenario: constructor initializer on static constructor Debug.Assert(diagnostics != null); NamedTypeSymbol containingType = constructor.ContainingType; // Structs and enums do not have implicit constructor initializers. if ((containingType.TypeKind == TypeKind.Enum || containingType.TypeKind == TypeKind.Struct) && initializerArgumentListOpt == null) { return null; } AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance(); try { TypeSymbol constructorReturnType = constructor.ReturnType; Debug.Assert(constructorReturnType.IsVoidType()); //true of all constructors NamedTypeSymbol baseType = containingType.BaseTypeNoUseSiteDiagnostics; // Get the bound arguments and the argument names. // : this(__arglist()) is legal if (initializerArgumentListOpt != null) { this.BindArgumentsAndNames(initializerArgumentListOpt, diagnostics, analyzedArguments, allowArglist: true); } NamedTypeSymbol initializerType = containingType; bool isBaseConstructorInitializer = initializerArgumentListOpt == null || initializerArgumentListOpt.Parent.Kind() != SyntaxKind.ThisConstructorInitializer; if (isBaseConstructorInitializer) { initializerType = initializerType.BaseTypeNoUseSiteDiagnostics; // Soft assert: we think this is the case, and we're asserting to catch scenarios that violate our expectations Debug.Assert((object)initializerType != null || containingType.SpecialType == SpecialType.System_Object || containingType.IsInterface); if ((object)initializerType == null || containingType.SpecialType == SpecialType.System_Object) //e.g. when defining System.Object in source { // If the constructor initializer is implicit and there is no base type, we're done. // Otherwise, if the constructor initializer is explicit, we're in an error state. if (initializerArgumentListOpt == null) { return null; } else { diagnostics.Add(ErrorCode.ERR_ObjectCallingBaseConstructor, constructor.Locations[0], containingType); return new BoundBadExpression( syntax: initializerArgumentListOpt.Parent, resultKind: LookupResultKind.Empty, symbols: ImmutableArray<Symbol>.Empty, childBoundNodes: BuildArgumentsForErrorRecovery(analyzedArguments), type: constructorReturnType); } } else if (initializerArgumentListOpt != null && containingType.TypeKind == TypeKind.Struct) { diagnostics.Add(ErrorCode.ERR_StructWithBaseConstructorCall, constructor.Locations[0], containingType); return new BoundBadExpression( syntax: initializerArgumentListOpt.Parent, resultKind: LookupResultKind.Empty, symbols: ImmutableArray<Symbol>.Empty, //CONSIDER: we could look for a matching constructor on System.ValueType childBoundNodes: BuildArgumentsForErrorRecovery(analyzedArguments), type: constructorReturnType); } } else { Debug.Assert(initializerArgumentListOpt.Parent.Kind() == SyntaxKind.ThisConstructorInitializer); } CSharpSyntaxNode nonNullSyntax; Location errorLocation; bool enableCallerInfo; switch (initializerArgumentListOpt?.Parent) { case ConstructorInitializerSyntax initializerSyntax: nonNullSyntax = initializerSyntax; errorLocation = initializerSyntax.ThisOrBaseKeyword.GetLocation(); enableCallerInfo = true; break; case PrimaryConstructorBaseTypeSyntax baseWithArguments: nonNullSyntax = baseWithArguments; errorLocation = initializerArgumentListOpt.GetLocation(); enableCallerInfo = true; break; default: // Note: use syntax node of constructor with initializer, not constructor invoked by initializer (i.e. methodResolutionResult). nonNullSyntax = constructor.GetNonNullSyntaxNode(); errorLocation = constructor.Locations[0]; enableCallerInfo = false; break; } if (initializerArgumentListOpt != null && analyzedArguments.HasDynamicArgument) { diagnostics.Add(ErrorCode.ERR_NoDynamicPhantomOnBaseCtor, errorLocation); return new BoundBadExpression( syntax: initializerArgumentListOpt.Parent, resultKind: LookupResultKind.Empty, symbols: ImmutableArray<Symbol>.Empty, //CONSIDER: we could look for a matching constructor on System.ValueType childBoundNodes: BuildArgumentsForErrorRecovery(analyzedArguments), type: constructorReturnType); } BoundExpression receiver = ThisReference(nonNullSyntax, initializerType, wasCompilerGenerated: true); MemberResolutionResult<MethodSymbol> memberResolutionResult; ImmutableArray<MethodSymbol> candidateConstructors; bool found = TryPerformConstructorOverloadResolution( initializerType, analyzedArguments, WellKnownMemberNames.InstanceConstructorName, errorLocation, false, // Don't suppress result diagnostics diagnostics, out memberResolutionResult, out candidateConstructors, allowProtectedConstructorsOfBaseType: true); MethodSymbol resultMember = memberResolutionResult.Member; validateRecordCopyConstructor(constructor, baseType, resultMember, errorLocation, diagnostics); if (found) { bool hasErrors = false; if (resultMember == constructor) { Debug.Assert(initializerType.IsErrorType() || (initializerArgumentListOpt != null && initializerArgumentListOpt.Parent.Kind() == SyntaxKind.ThisConstructorInitializer)); diagnostics.Add(ErrorCode.ERR_RecursiveConstructorCall, errorLocation, constructor); hasErrors = true; // prevent recursive constructor from being emitted } else if (resultMember.HasUnsafeParameter()) { // What if some of the arguments are implicit? Dev10 reports unsafe errors // if the implied argument would have an unsafe type. We need to check // the parameters explicitly, since there won't be bound nodes for the implied // arguments until lowering. // Don't worry about double reporting (i.e. for both the argument and the parameter) // because only one unsafe diagnostic is allowed per scope - the others are suppressed. hasErrors = ReportUnsafeIfNotAllowed(errorLocation, diagnostics); } ReportDiagnosticsIfObsolete(diagnostics, resultMember, nonNullSyntax, hasBaseReceiver: isBaseConstructorInitializer); var expanded = memberResolutionResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm; var argsToParamsOpt = memberResolutionResult.Result.ArgsToParamsOpt; BindDefaultArguments(nonNullSyntax, resultMember.Parameters, analyzedArguments.Arguments, analyzedArguments.RefKinds, ref argsToParamsOpt, out var defaultArguments, expanded, enableCallerInfo, diagnostics); var arguments = analyzedArguments.Arguments.ToImmutable(); var refKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); if (!hasErrors) { hasErrors = !CheckInvocationArgMixing( nonNullSyntax, resultMember, receiver, resultMember.Parameters, arguments, argsToParamsOpt, this.LocalScopeDepth, diagnostics); } return new BoundCall( nonNullSyntax, receiver, resultMember, arguments, analyzedArguments.GetNames(), refKinds, isDelegateCall: false, expanded, invokedAsExtensionMethod: false, argsToParamsOpt: argsToParamsOpt, defaultArguments: defaultArguments, resultKind: LookupResultKind.Viable, type: constructorReturnType, hasErrors: hasErrors) { WasCompilerGenerated = initializerArgumentListOpt == null }; } else { var result = CreateBadCall( node: nonNullSyntax, name: WellKnownMemberNames.InstanceConstructorName, receiver: receiver, methods: candidateConstructors, resultKind: LookupResultKind.OverloadResolutionFailure, typeArgumentsWithAnnotations: ImmutableArray<TypeWithAnnotations>.Empty, analyzedArguments: analyzedArguments, invokedAsExtensionMethod: false, isDelegate: false); result.WasCompilerGenerated = initializerArgumentListOpt == null; return result; } } finally { analyzedArguments.Free(); } static void validateRecordCopyConstructor(MethodSymbol constructor, NamedTypeSymbol baseType, MethodSymbol resultMember, Location errorLocation, BindingDiagnosticBag diagnostics) { if (IsUserDefinedRecordCopyConstructor(constructor)) { if (baseType.SpecialType == SpecialType.System_Object) { if (resultMember is null || resultMember.ContainingType.SpecialType != SpecialType.System_Object) { // Record deriving from object must use `base()`, not `this()` diagnostics.Add(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, errorLocation); } return; } // Unless the base type is 'object', the constructor should invoke a base type copy constructor if (resultMember is null || !SynthesizedRecordCopyCtor.HasCopyConstructorSignature(resultMember)) { diagnostics.Add(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, errorLocation); } } } } internal static bool IsUserDefinedRecordCopyConstructor(MethodSymbol constructor) { return constructor.ContainingType is SourceNamedTypeSymbol sourceType && sourceType.IsRecord && constructor is not SynthesizedRecordConstructor && SynthesizedRecordCopyCtor.HasCopyConstructorSignature(constructor); } private BoundExpression BindImplicitObjectCreationExpression(ImplicitObjectCreationExpressionSyntax node, BindingDiagnosticBag diagnostics) { var arguments = AnalyzedArguments.GetInstance(); BindArgumentsAndNames(node.ArgumentList, diagnostics, arguments, allowArglist: true); var result = new BoundUnconvertedObjectCreationExpression( node, arguments.Arguments.ToImmutable(), arguments.Names.ToImmutableOrNull(), arguments.RefKinds.ToImmutableOrNull(), node.Initializer); arguments.Free(); return result; } protected BoundExpression BindObjectCreationExpression(ObjectCreationExpressionSyntax node, BindingDiagnosticBag diagnostics) { var typeWithAnnotations = BindType(node.Type, diagnostics); var type = typeWithAnnotations.Type; var originalType = type; if (typeWithAnnotations.NullableAnnotation.IsAnnotated() && !type.IsNullableType()) { diagnostics.Add(ErrorCode.ERR_AnnotationDisallowedInObjectCreation, node.Location, type); } switch (type.TypeKind) { case TypeKind.Struct: case TypeKind.Class: case TypeKind.Enum: case TypeKind.Error: return BindClassCreationExpression(node, (NamedTypeSymbol)type, GetName(node.Type), diagnostics, originalType); case TypeKind.Delegate: return BindDelegateCreationExpression(node, (NamedTypeSymbol)type, diagnostics); case TypeKind.Interface: return BindInterfaceCreationExpression(node, (NamedTypeSymbol)type, diagnostics); case TypeKind.TypeParameter: return BindTypeParameterCreationExpression(node, (TypeParameterSymbol)type, diagnostics); case TypeKind.Submission: // script class is synthesized and should not be used as a type of a new expression: throw ExceptionUtilities.UnexpectedValue(type.TypeKind); case TypeKind.Pointer: case TypeKind.FunctionPointer: type = new ExtendedErrorTypeSymbol(type, LookupResultKind.NotCreatable, diagnostics.Add(ErrorCode.ERR_UnsafeTypeInObjectCreation, node.Location, type)); goto case TypeKind.Class; case TypeKind.Dynamic: // we didn't find any type called "dynamic" so we are using the builtin dynamic type, which has no constructors: case TypeKind.Array: // ex: new ref[] type = new ExtendedErrorTypeSymbol(type, LookupResultKind.NotCreatable, diagnostics.Add(ErrorCode.ERR_InvalidObjectCreation, node.Type.Location, type)); goto case TypeKind.Class; default: throw ExceptionUtilities.UnexpectedValue(type.TypeKind); } } private BoundExpression BindDelegateCreationExpression(ObjectCreationExpressionSyntax node, NamedTypeSymbol type, BindingDiagnosticBag diagnostics) { AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance(); BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments, isDelegateCreation: true); var result = BindDelegateCreationExpression(node, type, analyzedArguments, node.Initializer, diagnostics); analyzedArguments.Free(); return result; } private BoundExpression BindDelegateCreationExpression(SyntaxNode node, NamedTypeSymbol type, AnalyzedArguments analyzedArguments, InitializerExpressionSyntax initializerOpt, BindingDiagnosticBag diagnostics) { bool hasErrors = false; if (analyzedArguments.HasErrors) { // Let's skip this part of further error checking without marking hasErrors = true here, // as the argument could be an unbound lambda, and the error could come from inside. // We'll check analyzedArguments.HasErrors again after we find if this is not the case. } else if (analyzedArguments.Arguments.Count == 0) { diagnostics.Add(ErrorCode.ERR_BadCtorArgCount, node.Location, type, 0); hasErrors = true; } else if (analyzedArguments.Names.Count != 0 || analyzedArguments.RefKinds.Count != 0 || analyzedArguments.Arguments.Count != 1) { // Use a smaller span that excludes the parens. var argSyntax = analyzedArguments.Arguments[0].Syntax; var start = argSyntax.SpanStart; var end = analyzedArguments.Arguments[analyzedArguments.Arguments.Count - 1].Syntax.Span.End; var errorSpan = new TextSpan(start, end - start); var loc = new SourceLocation(argSyntax.SyntaxTree, errorSpan); diagnostics.Add(ErrorCode.ERR_MethodNameExpected, loc); hasErrors = true; } if (initializerOpt != null) { Error(diagnostics, ErrorCode.ERR_ObjectOrCollectionInitializerWithDelegateCreation, node); hasErrors = true; } BoundExpression argument = analyzedArguments.Arguments.Count >= 1 ? BindToNaturalType(analyzedArguments.Arguments[0], diagnostics) : null; if (hasErrors) { // skip the rest of this binding } // There are four cases for a delegate creation expression (7.6.10.5): // 1. An anonymous function is treated as a conversion from the anonymous function to the delegate type. else if (argument is UnboundLambda unboundLambda) { // analyzedArguments.HasErrors could be true, // but here the argument is an unbound lambda, the error comes from inside // eg: new Action<int>(x => x.) // We should try to bind it anyway in order for intellisense to work. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var conversion = this.Conversions.ClassifyConversionFromExpression(unboundLambda, type, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); // Attempting to make the conversion caches the diagnostics and the bound state inside // the unbound lambda. Fetch the result from the cache. Debug.Assert(!type.IsGenericOrNonGenericExpressionType(out _)); BoundLambda boundLambda = unboundLambda.Bind(type, isExpressionTree: false); if (!conversion.IsImplicit || !conversion.IsValid) { GenerateImplicitConversionError(diagnostics, unboundLambda.Syntax, conversion, unboundLambda, type); } else { // We're not going to produce an error, but it is possible that the conversion from // the lambda to the delegate type produced a warning, which we have not reported. // Instead, we've cached it in the bound lambda. Report it now. diagnostics.AddRange(boundLambda.Diagnostics); } // Just stuff the bound lambda into the delegate creation expression. When we lower the lambda to // its method form we will rewrite this expression to refer to the method. return new BoundDelegateCreationExpression(node, boundLambda, methodOpt: null, isExtensionMethod: false, type: type, hasErrors: !conversion.IsImplicit); } else if (analyzedArguments.HasErrors) { // There is no hope, skip. } // 2. A method group else if (argument.Kind == BoundKind.MethodGroup) { Conversion conversion; BoundMethodGroup methodGroup = (BoundMethodGroup)argument; hasErrors = MethodGroupConversionDoesNotExistOrHasErrors(methodGroup, type, node.Location, diagnostics, out conversion); methodGroup = FixMethodGroupWithTypeOrValue(methodGroup, conversion, diagnostics); return new BoundDelegateCreationExpression(node, methodGroup, conversion.Method, conversion.IsExtensionMethod, type, hasErrors); } else if ((object)argument.Type == null) { diagnostics.Add(ErrorCode.ERR_MethodNameExpected, argument.Syntax.Location); } // 3. A value of the compile-time type dynamic (which is dynamically case 4), or else if (argument.HasDynamicType()) { return new BoundDelegateCreationExpression(node, argument, methodOpt: null, isExtensionMethod: false, type: type); } // 4. A delegate type. else if (argument.Type.TypeKind == TypeKind.Delegate) { var sourceDelegate = (NamedTypeSymbol)argument.Type; MethodGroup methodGroup = MethodGroup.GetInstance(); try { if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, argument.Type, node: node)) { // We want failed "new" expression to use the constructors as their symbols. return new BoundBadExpression(node, LookupResultKind.NotInvocable, StaticCast<Symbol>.From(type.InstanceConstructors), ImmutableArray.Create(argument), type); } methodGroup.PopulateWithSingleMethod(argument, sourceDelegate.DelegateInvokeMethod); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conv = Conversions.MethodGroupConversion(argument.Syntax, methodGroup, type, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!conv.Exists) { var boundMethodGroup = new BoundMethodGroup( argument.Syntax, default, WellKnownMemberNames.DelegateInvokeName, ImmutableArray.Create(sourceDelegate.DelegateInvokeMethod), sourceDelegate.DelegateInvokeMethod, null, BoundMethodGroupFlags.None, argument, LookupResultKind.Viable); if (!Conversions.ReportDelegateOrFunctionPointerMethodGroupDiagnostics(this, boundMethodGroup, type, diagnostics)) { // If we could not produce a more specialized diagnostic, we report // No overload for '{0}' matches delegate '{1}' diagnostics.Add(ErrorCode.ERR_MethDelegateMismatch, node.Location, sourceDelegate.DelegateInvokeMethod, type); } } else { Debug.Assert(!conv.IsExtensionMethod); Debug.Assert(conv.IsValid); // i.e. if it exists, then it is valid. if (!this.MethodGroupConversionHasErrors(argument.Syntax, conv, argument, conv.IsExtensionMethod, isAddressOf: false, type, diagnostics)) { // we do not place the "Invoke" method in the node, indicating that it did not appear in source. return new BoundDelegateCreationExpression(node, argument, methodOpt: null, isExtensionMethod: false, type: type); } } } finally { methodGroup.Free(); } } // Not a valid delegate creation expression else { diagnostics.Add(ErrorCode.ERR_MethodNameExpected, argument.Syntax.Location); } // Note that we want failed "new" expression to use the constructors as their symbols. var childNodes = BuildArgumentsForErrorRecovery(analyzedArguments); return new BoundBadExpression(node, LookupResultKind.OverloadResolutionFailure, StaticCast<Symbol>.From(type.InstanceConstructors), childNodes, type); } private BoundExpression BindClassCreationExpression(ObjectCreationExpressionSyntax node, NamedTypeSymbol type, string typeName, BindingDiagnosticBag diagnostics, TypeSymbol initializerType = null) { // Get the bound arguments and the argument names. AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance(); try { // new C(__arglist()) is legal BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments, allowArglist: true); // No point in performing overload resolution if the type is static or a tuple literal. // Just return a bad expression containing the arguments. if (type.IsStatic) { diagnostics.Add(ErrorCode.ERR_InstantiatingStaticClass, node.Location, type); return MakeBadExpressionForObjectCreation(node, type, analyzedArguments, diagnostics); } else if (node.Type.Kind() == SyntaxKind.TupleType) { diagnostics.Add(ErrorCode.ERR_NewWithTupleTypeSyntax, node.Type.GetLocation()); return MakeBadExpressionForObjectCreation(node, type, analyzedArguments, diagnostics); } return BindClassCreationExpression(node, typeName, node.Type, type, analyzedArguments, diagnostics, node.Initializer, initializerType); } finally { analyzedArguments.Free(); } } #nullable enable /// <summary> /// Helper method to create a synthesized constructor invocation. /// </summary> private BoundExpression MakeConstructorInvocation( NamedTypeSymbol type, ArrayBuilder<BoundExpression> arguments, ArrayBuilder<RefKind> refKinds, SyntaxNode node, BindingDiagnosticBag diagnostics) { Debug.Assert(type.TypeKind is TypeKind.Class or TypeKind.Struct); var analyzedArguments = AnalyzedArguments.GetInstance(); try { analyzedArguments.Arguments.AddRange(arguments); analyzedArguments.RefKinds.AddRange(refKinds); if (type.IsStatic) { diagnostics.Add(ErrorCode.ERR_InstantiatingStaticClass, node.Location, type); return MakeBadExpressionForObjectCreation(node, type, analyzedArguments, initializerOpt: null, typeSyntax: null, diagnostics, wasCompilerGenerated: true); } var creation = BindClassCreationExpression(node, type.Name, node, type, analyzedArguments, diagnostics); creation.WasCompilerGenerated = true; return creation; } finally { analyzedArguments.Free(); } } internal BoundExpression BindObjectCreationForErrorRecovery(BoundUnconvertedObjectCreationExpression node, BindingDiagnosticBag diagnostics) { var arguments = AnalyzedArguments.GetInstance(node.Arguments, node.ArgumentRefKindsOpt, node.ArgumentNamesOpt); var result = MakeBadExpressionForObjectCreation(node.Syntax, CreateErrorType(), arguments, node.InitializerOpt, typeSyntax: node.Syntax, diagnostics); arguments.Free(); return result; } private BoundExpression MakeBadExpressionForObjectCreation(ObjectCreationExpressionSyntax node, TypeSymbol type, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics, bool wasCompilerGenerated = false) { return MakeBadExpressionForObjectCreation(node, type, analyzedArguments, node.Initializer, node.Type, diagnostics, wasCompilerGenerated); } /// <param name="typeSyntax">Shouldn't be null if <paramref name="initializerOpt"/> is not null.</param> private BoundExpression MakeBadExpressionForObjectCreation(SyntaxNode node, TypeSymbol type, AnalyzedArguments analyzedArguments, InitializerExpressionSyntax? initializerOpt, SyntaxNode? typeSyntax, BindingDiagnosticBag diagnostics, bool wasCompilerGenerated = false) { var children = ArrayBuilder<BoundExpression>.GetInstance(); children.AddRange(BuildArgumentsForErrorRecovery(analyzedArguments)); if (initializerOpt != null) { Debug.Assert(typeSyntax is not null); var boundInitializer = BindInitializerExpression(syntax: initializerOpt, type: type, typeSyntax: typeSyntax, isForNewInstance: true, diagnostics: diagnostics); children.Add(boundInitializer); } return new BoundBadExpression(node, LookupResultKind.NotCreatable, ImmutableArray.Create<Symbol?>(type), children.ToImmutableAndFree(), type) { WasCompilerGenerated = wasCompilerGenerated }; } #nullable disable private BoundObjectInitializerExpressionBase BindInitializerExpression( InitializerExpressionSyntax syntax, TypeSymbol type, SyntaxNode typeSyntax, bool isForNewInstance, BindingDiagnosticBag diagnostics) { Debug.Assert(syntax != null); Debug.Assert((object)type != null); var implicitReceiver = new BoundObjectOrCollectionValuePlaceholder(typeSyntax, isForNewInstance, type) { WasCompilerGenerated = true }; switch (syntax.Kind()) { case SyntaxKind.ObjectInitializerExpression: // Uses a special binder to produce customized diagnostics for the object initializer return BindObjectInitializerExpression( syntax, type, diagnostics, implicitReceiver, useObjectInitDiagnostics: true); case SyntaxKind.WithInitializerExpression: return BindObjectInitializerExpression( syntax, type, diagnostics, implicitReceiver, useObjectInitDiagnostics: false); case SyntaxKind.CollectionInitializerExpression: return BindCollectionInitializerExpression(syntax, type, diagnostics, implicitReceiver); default: throw ExceptionUtilities.Unreachable; } } private BoundExpression BindInitializerExpressionOrValue( ExpressionSyntax syntax, TypeSymbol type, SyntaxNode typeSyntax, BindingDiagnosticBag diagnostics) { Debug.Assert(syntax != null); Debug.Assert((object)type != null); switch (syntax.Kind()) { case SyntaxKind.ObjectInitializerExpression: case SyntaxKind.CollectionInitializerExpression: Debug.Assert(syntax.Parent.Parent.Kind() != SyntaxKind.WithInitializerExpression); return BindInitializerExpression((InitializerExpressionSyntax)syntax, type, typeSyntax, isForNewInstance: false, diagnostics); default: return BindValue(syntax, diagnostics, BindValueKind.RValue); } } private BoundObjectInitializerExpression BindObjectInitializerExpression( InitializerExpressionSyntax initializerSyntax, TypeSymbol initializerType, BindingDiagnosticBag diagnostics, BoundObjectOrCollectionValuePlaceholder implicitReceiver, bool useObjectInitDiagnostics) { // SPEC: 7.6.10.2 Object initializers // // SPEC: An object initializer consists of a sequence of member initializers, enclosed by { and } tokens and separated by commas. // SPEC: Each member initializer must name an accessible field or property of the object being initialized, followed by an equals sign and // SPEC: an expression or an object initializer or collection initializer. Debug.Assert(initializerSyntax.Kind() == SyntaxKind.ObjectInitializerExpression || initializerSyntax.Kind() == SyntaxKind.WithInitializerExpression); Debug.Assert((object)initializerType != null); // We use a location specific binder for binding object initializer field/property access to generate object initializer specific diagnostics: // 1) CS1914 (ERR_StaticMemberInObjectInitializer) // 2) CS1917 (ERR_ReadonlyValueTypeInObjectInitializer) // 3) CS1918 (ERR_ValueTypePropertyInObjectInitializer) // Note that this is only used for the LHS of the assignment - these diagnostics do not apply on the RHS. // For this reason, we will actually need two binders: this and this.WithAdditionalFlags. var objectInitializerMemberBinder = useObjectInitDiagnostics ? this.WithAdditionalFlags(BinderFlags.ObjectInitializerMember) : this; var initializers = ArrayBuilder<BoundExpression>.GetInstance(initializerSyntax.Expressions.Count); // Member name map to report duplicate assignments to a field/property. var memberNameMap = PooledHashSet<string>.GetInstance(); foreach (var memberInitializer in initializerSyntax.Expressions) { BoundExpression boundMemberInitializer = BindInitializerMemberAssignment( memberInitializer, initializerType, objectInitializerMemberBinder, diagnostics, implicitReceiver); initializers.Add(boundMemberInitializer); ReportDuplicateObjectMemberInitializers(boundMemberInitializer, memberNameMap, diagnostics); } return new BoundObjectInitializerExpression( initializerSyntax, implicitReceiver, initializers.ToImmutableAndFree(), initializerType); } private BoundExpression BindInitializerMemberAssignment( ExpressionSyntax memberInitializer, TypeSymbol initializerType, Binder objectInitializerMemberBinder, BindingDiagnosticBag diagnostics, BoundObjectOrCollectionValuePlaceholder implicitReceiver) { // SPEC: A member initializer that specifies an expression after the equals sign is processed in the same way as an assignment (spec 7.17.1) to the field or property. if (memberInitializer.Kind() == SyntaxKind.SimpleAssignmentExpression) { var initializer = (AssignmentExpressionSyntax)memberInitializer; // Bind member initializer identifier, i.e. left part of assignment BoundExpression boundLeft = null; var leftSyntax = initializer.Left; if (initializerType.IsDynamic() && leftSyntax.Kind() == SyntaxKind.IdentifierName) { { // D = { ..., <identifier> = <expr>, ... }, where D : dynamic var memberName = ((IdentifierNameSyntax)leftSyntax).Identifier.Text; boundLeft = new BoundDynamicObjectInitializerMember(leftSyntax, memberName, implicitReceiver.Type, initializerType, hasErrors: false); } } else { // We use a location specific binder for binding object initializer field/property access to generate object initializer specific diagnostics: // 1) CS1914 (ERR_StaticMemberInObjectInitializer) // 2) CS1917 (ERR_ReadonlyValueTypeInObjectInitializer) // 3) CS1918 (ERR_ValueTypePropertyInObjectInitializer) // See comments in BindObjectInitializerExpression for more details. Debug.Assert(objectInitializerMemberBinder != null); boundLeft = objectInitializerMemberBinder.BindObjectInitializerMember(initializer, implicitReceiver, diagnostics); } if (boundLeft != null) { Debug.Assert((object)boundLeft.Type != null); // Bind member initializer value, i.e. right part of assignment BoundExpression boundRight = BindInitializerExpressionOrValue( syntax: initializer.Right, type: boundLeft.Type, typeSyntax: boundLeft.Syntax, diagnostics: diagnostics); // Bind member initializer assignment expression return BindAssignment(initializer, boundLeft, boundRight, isRef: false, diagnostics); } } var boundExpression = BindValue(memberInitializer, diagnostics, BindValueKind.RValue); Error(diagnostics, ErrorCode.ERR_InvalidInitializerElementInitializer, memberInitializer); return ToBadExpression(boundExpression, LookupResultKind.NotAValue); } // returns BadBoundExpression or BoundObjectInitializerMember private BoundExpression BindObjectInitializerMember( AssignmentExpressionSyntax namedAssignment, BoundObjectOrCollectionValuePlaceholder implicitReceiver, BindingDiagnosticBag diagnostics) { BoundExpression boundMember; LookupResultKind resultKind; bool hasErrors; if (namedAssignment.Left.Kind() == SyntaxKind.IdentifierName) { var memberName = (IdentifierNameSyntax)namedAssignment.Left; // SPEC: Each member initializer must name an accessible field or property of the object being initialized, followed by an equals sign and // SPEC: an expression or an object initializer or collection initializer. // SPEC: A member initializer that specifies an expression after the equals sign is processed in the same way as an assignment (7.17.1) to the field or property. // SPEC VIOLATION: Native compiler also allows initialization of field-like events in object initializers, so we allow it as well. boundMember = BindInstanceMemberAccess( node: memberName, right: memberName, boundLeft: implicitReceiver, rightName: memberName.Identifier.ValueText, rightArity: 0, typeArgumentsSyntax: default(SeparatedSyntaxList<TypeSyntax>), typeArgumentsWithAnnotations: default(ImmutableArray<TypeWithAnnotations>), invoked: false, indexed: false, diagnostics: diagnostics); resultKind = boundMember.ResultKind; hasErrors = boundMember.HasAnyErrors || implicitReceiver.HasAnyErrors; if (boundMember.Kind == BoundKind.PropertyGroup) { boundMember = BindIndexedPropertyAccess((BoundPropertyGroup)boundMember, mustHaveAllOptionalParameters: true, diagnostics: diagnostics); if (boundMember.HasAnyErrors) { hasErrors = true; } } } else if (namedAssignment.Left.Kind() == SyntaxKind.ImplicitElementAccess) { var implicitIndexing = (ImplicitElementAccessSyntax)namedAssignment.Left; boundMember = BindElementAccess(implicitIndexing, implicitReceiver, implicitIndexing.ArgumentList, diagnostics); resultKind = boundMember.ResultKind; hasErrors = boundMember.HasAnyErrors || implicitReceiver.HasAnyErrors; } else { return null; } // SPEC: A member initializer that specifies an object initializer after the equals sign is a nested object initializer, // SPEC: i.e. an initialization of an embedded object. Instead of assigning a new value to the field or property, // SPEC: the assignments in the nested object initializer are treated as assignments to members of the field or property. // SPEC: Nested object initializers cannot be applied to properties with a value type, or to read-only fields with a value type. // NOTE: The dev11 behavior does not match the spec that was current at the time (quoted above). However, in the roslyn // NOTE: timeframe, the spec will be updated to apply the same restriction to nested collection initializers. Therefore, // NOTE: roslyn will implement the dev11 behavior and it will be spec-compliant. // NOTE: In the roslyn timeframe, an additional restriction will (likely) be added to the spec - it is not sufficient for the // NOTE: type of the member to not be a value type - it must actually be a reference type (i.e. unconstrained type parameters // NOTE: should be prohibited). To avoid breaking existing code, roslyn will not implement this new spec clause. // TODO: If/when we have a way to version warnings, we should add a warning for this. BoundKind boundMemberKind = boundMember.Kind; SyntaxKind rhsKind = namedAssignment.Right.Kind(); bool isRhsNestedInitializer = rhsKind == SyntaxKind.ObjectInitializerExpression || rhsKind == SyntaxKind.CollectionInitializerExpression; BindValueKind valueKind = isRhsNestedInitializer ? BindValueKind.RValue : BindValueKind.Assignable; ImmutableArray<BoundExpression> arguments = ImmutableArray<BoundExpression>.Empty; ImmutableArray<string> argumentNamesOpt = default(ImmutableArray<string>); ImmutableArray<int> argsToParamsOpt = default(ImmutableArray<int>); ImmutableArray<RefKind> argumentRefKindsOpt = default(ImmutableArray<RefKind>); BitVector defaultArguments = default(BitVector); bool expanded = false; switch (boundMemberKind) { case BoundKind.FieldAccess: { var fieldSymbol = ((BoundFieldAccess)boundMember).FieldSymbol; if (isRhsNestedInitializer && fieldSymbol.IsReadOnly && fieldSymbol.Type.IsValueType) { if (!hasErrors) { // TODO: distinct error code for collection initializers? (Dev11 doesn't have one.) Error(diagnostics, ErrorCode.ERR_ReadonlyValueTypeInObjectInitializer, namedAssignment.Left, fieldSymbol, fieldSymbol.Type); hasErrors = true; } resultKind = LookupResultKind.NotAValue; } break; } case BoundKind.EventAccess: break; case BoundKind.PropertyAccess: hasErrors |= isRhsNestedInitializer && !CheckNestedObjectInitializerPropertySymbol(((BoundPropertyAccess)boundMember).PropertySymbol, namedAssignment.Left, diagnostics, hasErrors, ref resultKind); break; case BoundKind.IndexerAccess: { var indexer = BindIndexerDefaultArguments((BoundIndexerAccess)boundMember, valueKind, diagnostics); boundMember = indexer; hasErrors |= isRhsNestedInitializer && !CheckNestedObjectInitializerPropertySymbol(indexer.Indexer, namedAssignment.Left, diagnostics, hasErrors, ref resultKind); arguments = indexer.Arguments; argumentNamesOpt = indexer.ArgumentNamesOpt; argsToParamsOpt = indexer.ArgsToParamsOpt; argumentRefKindsOpt = indexer.ArgumentRefKindsOpt; defaultArguments = indexer.DefaultArguments; expanded = indexer.Expanded; break; } case BoundKind.DynamicIndexerAccess: { var indexer = (BoundDynamicIndexerAccess)boundMember; arguments = indexer.Arguments; argumentNamesOpt = indexer.ArgumentNamesOpt; argumentRefKindsOpt = indexer.ArgumentRefKindsOpt; } break; case BoundKind.ArrayAccess: case BoundKind.PointerElementAccess: return boundMember; default: return BadObjectInitializerMemberAccess(boundMember, implicitReceiver, namedAssignment.Left, diagnostics, valueKind, hasErrors); } if (!hasErrors) { // CheckValueKind to generate possible diagnostics for invalid initializers non-viable member lookup result: // 1) CS0154 (ERR_PropertyLacksGet) // 2) CS0200 (ERR_AssgReadonlyProp) if (!CheckValueKind(boundMember.Syntax, boundMember, valueKind, checkingReceiver: false, diagnostics: diagnostics)) { hasErrors = true; resultKind = isRhsNestedInitializer ? LookupResultKind.NotAValue : LookupResultKind.NotAVariable; } } return new BoundObjectInitializerMember( namedAssignment.Left, boundMember.ExpressionSymbol, arguments, argumentNamesOpt, argumentRefKindsOpt, expanded, argsToParamsOpt, defaultArguments, resultKind, implicitReceiver.Type, type: boundMember.Type, hasErrors: hasErrors); } private static bool CheckNestedObjectInitializerPropertySymbol( PropertySymbol propertySymbol, ExpressionSyntax memberNameSyntax, BindingDiagnosticBag diagnostics, bool suppressErrors, ref LookupResultKind resultKind) { bool hasErrors = false; if (propertySymbol.Type.IsValueType) { if (!suppressErrors) { // TODO: distinct error code for collection initializers? (Dev11 doesn't have one.) Error(diagnostics, ErrorCode.ERR_ValueTypePropertyInObjectInitializer, memberNameSyntax, propertySymbol, propertySymbol.Type); hasErrors = true; } resultKind = LookupResultKind.NotAValue; } return !hasErrors; } private BoundExpression BadObjectInitializerMemberAccess( BoundExpression boundMember, BoundObjectOrCollectionValuePlaceholder implicitReceiver, ExpressionSyntax memberNameSyntax, BindingDiagnosticBag diagnostics, BindValueKind valueKind, bool suppressErrors) { if (!suppressErrors) { string member; var identName = memberNameSyntax as IdentifierNameSyntax; if (identName != null) { member = identName.Identifier.ValueText; } else { member = memberNameSyntax.ToString(); } switch (boundMember.ResultKind) { case LookupResultKind.Empty: Error(diagnostics, ErrorCode.ERR_NoSuchMember, memberNameSyntax, implicitReceiver.Type, member); break; case LookupResultKind.Inaccessible: boundMember = CheckValue(boundMember, valueKind, diagnostics); Debug.Assert(boundMember.HasAnyErrors); break; default: Error(diagnostics, ErrorCode.ERR_MemberCannotBeInitialized, memberNameSyntax, member); break; } } return ToBadExpression(boundMember, (valueKind == BindValueKind.RValue) ? LookupResultKind.NotAValue : LookupResultKind.NotAVariable); } private static void ReportDuplicateObjectMemberInitializers(BoundExpression boundMemberInitializer, HashSet<string> memberNameMap, BindingDiagnosticBag diagnostics) { Debug.Assert(memberNameMap != null); // SPEC: It is an error for an object initializer to include more than one member initializer for the same field or property. if (!boundMemberInitializer.HasAnyErrors) { // SPEC: A member initializer that specifies an expression after the equals sign is processed in the same way as an assignment (7.17.1) to the field or property. var memberInitializerSyntax = boundMemberInitializer.Syntax; Debug.Assert(memberInitializerSyntax.Kind() == SyntaxKind.SimpleAssignmentExpression); var namedAssignment = (AssignmentExpressionSyntax)memberInitializerSyntax; var memberNameSyntax = namedAssignment.Left as IdentifierNameSyntax; if (memberNameSyntax != null) { var memberName = memberNameSyntax.Identifier.ValueText; if (!memberNameMap.Add(memberName)) { Error(diagnostics, ErrorCode.ERR_MemberAlreadyInitialized, memberNameSyntax, memberName); } } } } private BoundCollectionInitializerExpression BindCollectionInitializerExpression( InitializerExpressionSyntax initializerSyntax, TypeSymbol initializerType, BindingDiagnosticBag diagnostics, BoundObjectOrCollectionValuePlaceholder implicitReceiver) { // SPEC: 7.6.10.3 Collection initializers // // SPEC: A collection initializer consists of a sequence of element initializers, enclosed by { and } tokens and separated by commas. // SPEC: The following is an example of an object creation expression that includes a collection initializer: // SPEC: List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // SPEC: The collection object to which a collection initializer is applied must be of a type that implements System.Collections.IEnumerable or // SPEC: a compile-time error occurs. For each specified element in order, the collection initializer invokes an Add method on the target object // SPEC: with the expression list of the element initializer as argument list, applying normal overload resolution for each invocation. // SPEC: Thus, the collection object must contain an applicable Add method for each element initializer. Debug.Assert(initializerSyntax.Kind() == SyntaxKind.CollectionInitializerExpression); Debug.Assert(initializerSyntax.Expressions.Any()); Debug.Assert((object)initializerType != null); var initializerBuilder = ArrayBuilder<BoundExpression>.GetInstance(); // SPEC: The collection object to which a collection initializer is applied must be of a type that implements System.Collections.IEnumerable or // SPEC: a compile-time error occurs. bool hasEnumerableInitializerType = CollectionInitializerTypeImplementsIEnumerable(initializerType, initializerSyntax, diagnostics); if (!hasEnumerableInitializerType && !initializerSyntax.HasErrors && !initializerType.IsErrorType()) { Error(diagnostics, ErrorCode.ERR_CollectionInitRequiresIEnumerable, initializerSyntax, initializerType); } // We use a location specific binder for binding collection initializer Add method to generate specific overload resolution diagnostics: // 1) CS1921 (ERR_InitializerAddHasWrongSignature) // 2) CS1950 (ERR_BadArgTypesForCollectionAdd) // 3) CS1954 (ERR_InitializerAddHasParamModifiers) var collectionInitializerAddMethodBinder = this.WithAdditionalFlags(BinderFlags.CollectionInitializerAddMethod); foreach (var elementInitializer in initializerSyntax.Expressions) { // NOTE: collectionInitializerAddMethodBinder is used only for binding the Add method invocation expression, but not the entire initializer. // NOTE: Hence it is being passed as a parameter to BindCollectionInitializerElement(). // NOTE: Ideally we would want to avoid this and bind the entire initializer with the collectionInitializerAddMethodBinder. // NOTE: However, this approach has few issues. These issues also occur when binding object initializer member assignment. // NOTE: See comments for objectInitializerMemberBinder in BindObjectInitializerExpression method for details about the pitfalls of alternate approaches. BoundExpression boundElementInitializer = BindCollectionInitializerElement(elementInitializer, initializerType, hasEnumerableInitializerType, collectionInitializerAddMethodBinder, diagnostics, implicitReceiver); initializerBuilder.Add(boundElementInitializer); } return new BoundCollectionInitializerExpression(initializerSyntax, implicitReceiver, initializerBuilder.ToImmutableAndFree(), initializerType); } private bool CollectionInitializerTypeImplementsIEnumerable(TypeSymbol initializerType, CSharpSyntaxNode node, BindingDiagnosticBag diagnostics) { // SPEC: The collection object to which a collection initializer is applied must be of a type that implements System.Collections.IEnumerable or // SPEC: a compile-time error occurs. if (initializerType.IsDynamic()) { // We cannot determine at compile time if initializerType implements System.Collections.IEnumerable, we must assume that it does. return true; } else if (!initializerType.IsErrorType()) { TypeSymbol collectionsIEnumerableType = this.GetSpecialType(SpecialType.System_Collections_IEnumerable, diagnostics, node); // NOTE: Ideally, to check if the initializer type implements System.Collections.IEnumerable we can walk through // NOTE: its implemented interfaces. However the native compiler checks to see if there is conversion from initializer // NOTE: type to the predefined System.Collections.IEnumerable type, so we do the same. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var result = Conversions.ClassifyImplicitConversionFromType(initializerType, collectionsIEnumerableType, ref useSiteInfo).IsValid; diagnostics.Add(node, useSiteInfo); return result; } else { return false; } } private BoundExpression BindCollectionInitializerElement( ExpressionSyntax elementInitializer, TypeSymbol initializerType, bool hasEnumerableInitializerType, Binder collectionInitializerAddMethodBinder, BindingDiagnosticBag diagnostics, BoundObjectOrCollectionValuePlaceholder implicitReceiver) { // SPEC: Each element initializer specifies an element to be added to the collection object being initialized, and consists of // SPEC: a list of expressions enclosed by { and } tokens and separated by commas. // SPEC: A single-expression element initializer can be written without braces, but cannot then be an assignment expression, // SPEC: to avoid ambiguity with member initializers. The non-assignment-expression production is defined in 7.18. if (elementInitializer.Kind() == SyntaxKind.ComplexElementInitializerExpression) { return BindComplexElementInitializerExpression( (InitializerExpressionSyntax)elementInitializer, diagnostics, hasEnumerableInitializerType, collectionInitializerAddMethodBinder, implicitReceiver); } else { // Must be a non-assignment expression. if (SyntaxFacts.IsAssignmentExpression(elementInitializer.Kind())) { Error(diagnostics, ErrorCode.ERR_InvalidInitializerElementInitializer, elementInitializer); } var boundElementInitializer = BindInitializerExpressionOrValue(elementInitializer, initializerType, implicitReceiver.Syntax, diagnostics); BoundExpression result = BindCollectionInitializerElementAddMethod( elementInitializer, ImmutableArray.Create(boundElementInitializer), hasEnumerableInitializerType, collectionInitializerAddMethodBinder, diagnostics, implicitReceiver); result.WasCompilerGenerated = true; return result; } } private BoundExpression BindComplexElementInitializerExpression( InitializerExpressionSyntax elementInitializer, BindingDiagnosticBag diagnostics, bool hasEnumerableInitializerType, Binder collectionInitializerAddMethodBinder = null, BoundObjectOrCollectionValuePlaceholder implicitReceiver = null) { var elementInitializerExpressions = elementInitializer.Expressions; if (elementInitializerExpressions.Any()) { var exprBuilder = ArrayBuilder<BoundExpression>.GetInstance(); foreach (var childElementInitializer in elementInitializerExpressions) { exprBuilder.Add(BindValue(childElementInitializer, diagnostics, BindValueKind.RValue)); } return BindCollectionInitializerElementAddMethod( elementInitializer, exprBuilder.ToImmutableAndFree(), hasEnumerableInitializerType, collectionInitializerAddMethodBinder, diagnostics, implicitReceiver); } else { Error(diagnostics, ErrorCode.ERR_EmptyElementInitializer, elementInitializer); return BadExpression(elementInitializer, LookupResultKind.NotInvocable); } } private BoundExpression BindUnexpectedComplexElementInitializer(InitializerExpressionSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node.Kind() == SyntaxKind.ComplexElementInitializerExpression); return BindComplexElementInitializerExpression(node, diagnostics, hasEnumerableInitializerType: false); } private BoundExpression BindCollectionInitializerElementAddMethod( ExpressionSyntax elementInitializer, ImmutableArray<BoundExpression> boundElementInitializerExpressions, bool hasEnumerableInitializerType, Binder collectionInitializerAddMethodBinder, BindingDiagnosticBag diagnostics, BoundObjectOrCollectionValuePlaceholder implicitReceiver) { // SPEC: For each specified element in order, the collection initializer invokes an Add method on the target object // SPEC: with the expression list of the element initializer as argument list, applying normal overload resolution for each invocation. // SPEC: Thus, the collection object must contain an applicable Add method for each element initializer. // We use a location specific binder for binding collection initializer Add method to generate specific overload resolution diagnostics. // 1) CS1921 (ERR_InitializerAddHasWrongSignature) // 2) CS1950 (ERR_BadArgTypesForCollectionAdd) // 3) CS1954 (ERR_InitializerAddHasParamModifiers) // See comments in BindCollectionInitializerExpression for more details. Debug.Assert(!boundElementInitializerExpressions.IsEmpty); if (!hasEnumerableInitializerType) { return BadExpression(elementInitializer, LookupResultKind.NotInvocable, ImmutableArray<Symbol>.Empty, boundElementInitializerExpressions); } Debug.Assert(collectionInitializerAddMethodBinder != null); Debug.Assert(collectionInitializerAddMethodBinder.Flags.Includes(BinderFlags.CollectionInitializerAddMethod)); Debug.Assert(implicitReceiver != null); Debug.Assert((object)implicitReceiver.Type != null); if (implicitReceiver.Type.IsDynamic()) { var hasErrors = ReportBadDynamicArguments(elementInitializer, boundElementInitializerExpressions, refKinds: default, diagnostics, queryClause: null); return new BoundDynamicCollectionElementInitializer( elementInitializer, applicableMethods: ImmutableArray<MethodSymbol>.Empty, implicitReceiver, arguments: boundElementInitializerExpressions.SelectAsArray(e => BindToNaturalType(e, diagnostics)), type: GetSpecialType(SpecialType.System_Void, diagnostics, elementInitializer), hasErrors: hasErrors); } // Receiver is early bound, find method Add and invoke it (may still be a dynamic invocation): var addMethodInvocation = collectionInitializerAddMethodBinder.MakeInvocationExpression( elementInitializer, implicitReceiver, methodName: WellKnownMemberNames.CollectionInitializerAddMethodName, args: boundElementInitializerExpressions, diagnostics: diagnostics); if (addMethodInvocation.Kind == BoundKind.DynamicInvocation) { var dynamicInvocation = (BoundDynamicInvocation)addMethodInvocation; return new BoundDynamicCollectionElementInitializer( elementInitializer, dynamicInvocation.ApplicableMethods, implicitReceiver, dynamicInvocation.Arguments, dynamicInvocation.Type, hasErrors: dynamicInvocation.HasAnyErrors); } else if (addMethodInvocation.Kind == BoundKind.Call) { var boundCall = (BoundCall)addMethodInvocation; // Either overload resolution succeeded for this call or it did not. If it // did not succeed then we've stashed the original method symbols from the // method group, and we should use those as the symbols displayed for the // call. If it did succeed then we did not stash any symbols. if (boundCall.HasErrors && !boundCall.OriginalMethodsOpt.IsDefault) { return boundCall; } return new BoundCollectionElementInitializer( elementInitializer, boundCall.Method, boundCall.Arguments, boundCall.ReceiverOpt, boundCall.Expanded, boundCall.ArgsToParamsOpt, boundCall.DefaultArguments, boundCall.InvokedAsExtensionMethod, boundCall.ResultKind, boundCall.Type, boundCall.HasAnyErrors) { WasCompilerGenerated = true }; } else { Debug.Assert(addMethodInvocation.Kind == BoundKind.BadExpression); return addMethodInvocation; } } internal ImmutableArray<MethodSymbol> FilterInaccessibleConstructors(ImmutableArray<MethodSymbol> constructors, bool allowProtectedConstructorsOfBaseType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { ArrayBuilder<MethodSymbol> builder = null; for (int i = 0; i < constructors.Length; i++) { MethodSymbol constructor = constructors[i]; if (!IsConstructorAccessible(constructor, ref useSiteInfo, allowProtectedConstructorsOfBaseType)) { if (builder == null) { builder = ArrayBuilder<MethodSymbol>.GetInstance(); builder.AddRange(constructors, i); } } else { builder?.Add(constructor); } } return builder == null ? constructors : builder.ToImmutableAndFree(); } private bool IsConstructorAccessible(MethodSymbol constructor, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool allowProtectedConstructorsOfBaseType = false) { Debug.Assert((object)constructor != null); Debug.Assert(constructor.MethodKind == MethodKind.Constructor || constructor.MethodKind == MethodKind.StaticConstructor); NamedTypeSymbol containingType = this.ContainingType; if ((object)containingType != null) { // SPEC VIOLATION: The specification implies that when considering // SPEC VIOLATION: instance methods or instance constructors, we first // SPEC VIOLATION: do overload resolution on the accessible members, and // SPEC VIOLATION: then if the best method chosen is protected and accessed // SPEC VIOLATION: through the wrong type, then an error occurs. The native // SPEC VIOLATION: compiler however does it in the opposite order. First it // SPEC VIOLATION: filters out the protected methods that cannot be called // SPEC VIOLATION: through the given type, and then it does overload resolution // SPEC VIOLATION: on the rest. // // That said, it is somewhat odd that the same rule applies to constructors // as instance methods. A protected constructor is never going to be called // via an instance of a *more derived but different class* the way a // virtual method might be. Nevertheless, that's what we do. // // A constructor is accessed through an instance of the type being constructed: return allowProtectedConstructorsOfBaseType ? this.IsAccessible(constructor, ref useSiteInfo, null) : this.IsSymbolAccessibleConditional(constructor, containingType, ref useSiteInfo, constructor.ContainingType); } else { Debug.Assert((object)this.Compilation.Assembly != null); return IsSymbolAccessibleConditional(constructor, this.Compilation.Assembly, ref useSiteInfo); } } protected BoundExpression BindClassCreationExpression( SyntaxNode node, string typeName, SyntaxNode typeNode, NamedTypeSymbol type, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics, InitializerExpressionSyntax initializerSyntaxOpt = null, TypeSymbol initializerTypeOpt = null, bool wasTargetTyped = false) { BoundExpression result = null; bool hasErrors = type.IsErrorType(); if (type.IsAbstract) { // Report error for new of abstract type. diagnostics.Add(ErrorCode.ERR_NoNewAbstract, node.Location, type); hasErrors = true; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); BoundObjectInitializerExpressionBase boundInitializerOpt = null; // If we have a dynamic argument then do overload resolution to see if there are one or more // applicable candidates. If there are, then this is a dynamic object creation; we'll work out // which ctor to call at runtime. If we have a dynamic argument but no applicable candidates // then we do the analysis again for error reporting purposes. if (analyzedArguments.HasDynamicArgument) { OverloadResolutionResult<MethodSymbol> overloadResolutionResult = OverloadResolutionResult<MethodSymbol>.GetInstance(); this.OverloadResolution.ObjectCreationOverloadResolution(GetAccessibleConstructorsForOverloadResolution(type, ref useSiteInfo), analyzedArguments, overloadResolutionResult, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); useSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(useSiteInfo); if (overloadResolutionResult.HasAnyApplicableMember) { var argArray = BuildArgumentsForDynamicInvocation(analyzedArguments, diagnostics); var refKindsArray = analyzedArguments.RefKinds.ToImmutableOrNull(); hasErrors &= ReportBadDynamicArguments(node, argArray, refKindsArray, diagnostics, queryClause: null); boundInitializerOpt = makeBoundInitializerOpt(); result = new BoundDynamicObjectCreationExpression( node, typeName, argArray, analyzedArguments.GetNames(), refKindsArray, boundInitializerOpt, overloadResolutionResult.GetAllApplicableMembers(), type, hasErrors); } overloadResolutionResult.Free(); if (result != null) { return result; } } if (TryPerformConstructorOverloadResolution( type, analyzedArguments, typeName, typeNode.Location, hasErrors, //don't cascade in these cases diagnostics, out MemberResolutionResult<MethodSymbol> memberResolutionResult, out ImmutableArray<MethodSymbol> candidateConstructors, allowProtectedConstructorsOfBaseType: false)) { var method = memberResolutionResult.Member; bool hasError = false; // What if some of the arguments are implicit? Dev10 reports unsafe errors // if the implied argument would have an unsafe type. We need to check // the parameters explicitly, since there won't be bound nodes for the implied // arguments until lowering. if (method.HasUnsafeParameter()) { // Don't worry about double reporting (i.e. for both the argument and the parameter) // because only one unsafe diagnostic is allowed per scope - the others are suppressed. hasError = ReportUnsafeIfNotAllowed(node, diagnostics) || hasError; } ReportDiagnosticsIfObsolete(diagnostics, method, node, hasBaseReceiver: false); // NOTE: Use-site diagnostics were reported during overload resolution. ConstantValue constantValueOpt = (initializerSyntaxOpt == null && method.IsDefaultValueTypeConstructor(requireZeroInit: true)) ? FoldParameterlessValueTypeConstructor(type) : null; var expanded = memberResolutionResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm; var argToParams = memberResolutionResult.Result.ArgsToParamsOpt; BindDefaultArguments(node, method.Parameters, analyzedArguments.Arguments, analyzedArguments.RefKinds, ref argToParams, out var defaultArguments, expanded, enableCallerInfo: true, diagnostics); var arguments = analyzedArguments.Arguments.ToImmutable(); var refKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); if (!hasError) { hasError = !CheckInvocationArgMixing( node, method, null, method.Parameters, arguments, argToParams, this.LocalScopeDepth, diagnostics); } boundInitializerOpt = makeBoundInitializerOpt(); result = new BoundObjectCreationExpression( node, method, candidateConstructors, arguments, analyzedArguments.GetNames(), refKinds, expanded, argToParams, defaultArguments, constantValueOpt, boundInitializerOpt, wasTargetTyped, type, hasError); // CONSIDER: Add ResultKind field to BoundObjectCreationExpression to avoid wrapping result with BoundBadExpression. if (type.IsAbstract) { result = BadExpression(node, LookupResultKind.NotCreatable, result); } return result; } LookupResultKind resultKind; if (type.IsAbstract) { resultKind = LookupResultKind.NotCreatable; } else if (memberResolutionResult.IsValid && !IsConstructorAccessible(memberResolutionResult.Member, ref useSiteInfo)) { resultKind = LookupResultKind.Inaccessible; } else { resultKind = LookupResultKind.OverloadResolutionFailure; } diagnostics.Add(node, useSiteInfo); ArrayBuilder<Symbol> symbols = ArrayBuilder<Symbol>.GetInstance(); symbols.AddRange(candidateConstructors); // NOTE: The use site diagnostics of the candidate constructors have already been reported (in PerformConstructorOverloadResolution). var childNodes = ArrayBuilder<BoundExpression>.GetInstance(); childNodes.AddRange(BuildArgumentsForErrorRecovery(analyzedArguments, candidateConstructors)); if (initializerSyntaxOpt != null) { childNodes.Add(boundInitializerOpt ?? makeBoundInitializerOpt()); } return new BoundBadExpression(node, resultKind, symbols.ToImmutableAndFree(), childNodes.ToImmutableAndFree(), type); BoundObjectInitializerExpressionBase makeBoundInitializerOpt() { if (initializerSyntaxOpt != null) { return BindInitializerExpression(syntax: initializerSyntaxOpt, type: initializerTypeOpt ?? type, typeSyntax: typeNode, isForNewInstance: true, diagnostics: diagnostics); } return null; } } private BoundExpression BindInterfaceCreationExpression(ObjectCreationExpressionSyntax node, NamedTypeSymbol type, BindingDiagnosticBag diagnostics) { AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance(); BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments); var result = BindInterfaceCreationExpression(node, type, diagnostics, node.Type, analyzedArguments, node.Initializer, wasTargetTyped: false); analyzedArguments.Free(); return result; } private BoundExpression BindInterfaceCreationExpression(SyntaxNode node, NamedTypeSymbol type, BindingDiagnosticBag diagnostics, SyntaxNode typeNode, AnalyzedArguments analyzedArguments, InitializerExpressionSyntax initializerOpt, bool wasTargetTyped) { Debug.Assert((object)type != null); // COM interfaces which have ComImportAttribute and CoClassAttribute can be instantiated with "new". // CoClassAttribute contains the type information of the original CoClass for the interface. // We replace the interface creation with CoClass object creation for this case. // NOTE: We don't attempt binding interface creation to CoClass creation if we are within an attribute argument. // NOTE: This is done to prevent a cycle in an error scenario where we have a "new InterfaceType" expression in an attribute argument. // NOTE: Accessing IsComImport/ComImportCoClass properties on given type symbol would attempt ForceCompeteAttributes, which would again try binding all attributes on the symbol. // NOTE: causing infinite recursion. We avoid this cycle by checking if we are within in context of an Attribute argument. if (!this.InAttributeArgument && type.IsComImport) { NamedTypeSymbol coClassType = type.ComImportCoClass; if ((object)coClassType != null) { return BindComImportCoClassCreationExpression(node, type, coClassType, diagnostics, typeNode, analyzedArguments, initializerOpt, wasTargetTyped); } } // interfaces can't be instantiated in C# diagnostics.Add(ErrorCode.ERR_NoNewAbstract, node.Location, type); return MakeBadExpressionForObjectCreation(node, type, analyzedArguments, initializerOpt, typeNode, diagnostics); } private BoundExpression BindComImportCoClassCreationExpression(SyntaxNode node, NamedTypeSymbol interfaceType, NamedTypeSymbol coClassType, BindingDiagnosticBag diagnostics, SyntaxNode typeNode, AnalyzedArguments analyzedArguments, InitializerExpressionSyntax initializerOpt, bool wasTargetTyped) { Debug.Assert((object)interfaceType != null); Debug.Assert(interfaceType.IsInterfaceType()); Debug.Assert((object)coClassType != null); Debug.Assert(TypeSymbol.Equals(interfaceType.ComImportCoClass, coClassType, TypeCompareKind.ConsiderEverything2)); Debug.Assert(coClassType.TypeKind == TypeKind.Class || coClassType.TypeKind == TypeKind.Error); if (coClassType.IsErrorType()) { Error(diagnostics, ErrorCode.ERR_MissingCoClass, node, coClassType, interfaceType); } else if (coClassType.IsUnboundGenericType) { // BREAKING CHANGE: Dev10 allows the following code to compile, even though the output assembly is not verifiable and generates a runtime exception: // // [ComImport, Guid("00020810-0000-0000-C000-000000000046")] // [CoClass(typeof(GenericClass<>))] // public interface InterfaceType {} // public class GenericClass<T>: InterfaceType {} // // public class Program // { // public static void Main() { var i = new InterfaceType(); } // } // // We disallow CoClass creation if coClassType is an unbound generic type and report a compile time error. Error(diagnostics, ErrorCode.ERR_BadCoClassSig, node, coClassType, interfaceType); } else { // NoPIA support if (interfaceType.ContainingAssembly.IsLinked) { return BindNoPiaObjectCreationExpression(node, interfaceType, coClassType, diagnostics, typeNode, analyzedArguments, initializerOpt); } var classCreation = BindClassCreationExpression( node, coClassType.Name, typeNode, coClassType, analyzedArguments, diagnostics, initializerOpt, interfaceType, wasTargetTyped); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = this.Conversions.ClassifyConversionFromExpression(classCreation, interfaceType, ref useSiteInfo, forCast: true); diagnostics.Add(node, useSiteInfo); if (!conversion.IsValid) { SymbolDistinguisher distinguisher = new SymbolDistinguisher(this.Compilation, coClassType, interfaceType); Error(diagnostics, ErrorCode.ERR_NoExplicitConv, node, distinguisher.First, distinguisher.Second); } // Bind the conversion, but drop the conversion node. CreateConversion(classCreation, conversion, interfaceType, diagnostics); // Override result type to be the interface type. switch (classCreation.Kind) { case BoundKind.ObjectCreationExpression: var creation = (BoundObjectCreationExpression)classCreation; return creation.Update(creation.Constructor, creation.ConstructorsGroup, creation.Arguments, creation.ArgumentNamesOpt, creation.ArgumentRefKindsOpt, creation.Expanded, creation.ArgsToParamsOpt, creation.DefaultArguments, creation.ConstantValueOpt, creation.InitializerExpressionOpt, interfaceType); case BoundKind.BadExpression: var bad = (BoundBadExpression)classCreation; return bad.Update(bad.ResultKind, bad.Symbols, bad.ChildBoundNodes, interfaceType); default: throw ExceptionUtilities.UnexpectedValue(classCreation.Kind); } } return MakeBadExpressionForObjectCreation(node, interfaceType, analyzedArguments, initializerOpt, typeNode, diagnostics); } private BoundExpression BindNoPiaObjectCreationExpression( SyntaxNode node, NamedTypeSymbol interfaceType, NamedTypeSymbol coClassType, BindingDiagnosticBag diagnostics, SyntaxNode typeNode, AnalyzedArguments analyzedArguments, InitializerExpressionSyntax initializerOpt) { string guidString; if (!coClassType.GetGuidString(out guidString)) { // At this point, VB reports ERRID_NoPIAAttributeMissing2 if guid isn't there. // C# doesn't complain and instead uses zero guid. guidString = System.Guid.Empty.ToString("D"); } var boundInitializerOpt = initializerOpt == null ? null : BindInitializerExpression(syntax: initializerOpt, type: interfaceType, typeSyntax: typeNode, isForNewInstance: true, diagnostics: diagnostics); var creation = new BoundNoPiaObjectCreationExpression(node, guidString, boundInitializerOpt, interfaceType); if (analyzedArguments.Arguments.Count > 0) { diagnostics.Add(ErrorCode.ERR_BadCtorArgCount, typeNode.Location, interfaceType, analyzedArguments.Arguments.Count); var children = BuildArgumentsForErrorRecovery(analyzedArguments).Add(creation); return new BoundBadExpression(node, LookupResultKind.OverloadResolutionFailure, ImmutableArray<Symbol>.Empty, children, creation.Type); } return creation; } private BoundExpression BindTypeParameterCreationExpression(ObjectCreationExpressionSyntax node, TypeParameterSymbol typeParameter, BindingDiagnosticBag diagnostics) { AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance(); BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments); var result = BindTypeParameterCreationExpression(node, typeParameter, analyzedArguments, node.Initializer, node.Type, diagnostics); analyzedArguments.Free(); return result; } private BoundExpression BindTypeParameterCreationExpression(SyntaxNode node, TypeParameterSymbol typeParameter, AnalyzedArguments analyzedArguments, InitializerExpressionSyntax initializerOpt, SyntaxNode typeSyntax, BindingDiagnosticBag diagnostics) { if (!typeParameter.HasConstructorConstraint && !typeParameter.IsValueType) { diagnostics.Add(ErrorCode.ERR_NoNewTyvar, node.Location, typeParameter); } else if (analyzedArguments.Arguments.Count > 0) { diagnostics.Add(ErrorCode.ERR_NewTyvarWithArgs, node.Location, typeParameter); } else { var boundInitializerOpt = initializerOpt == null ? null : BindInitializerExpression( syntax: initializerOpt, type: typeParameter, typeSyntax: typeSyntax, isForNewInstance: true, diagnostics: diagnostics); return new BoundNewT(node, boundInitializerOpt, typeParameter); } return MakeBadExpressionForObjectCreation(node, typeParameter, analyzedArguments, initializerOpt, typeSyntax, diagnostics); } /// <summary> /// Given the type containing constructors, gets the list of candidate instance constructors and uses overload resolution to determine which one should be called. /// </summary> /// <param name="typeContainingConstructors">The containing type of the constructors.</param> /// <param name="analyzedArguments">The already bound arguments to the constructor.</param> /// <param name="errorName">The name to use in diagnostics if overload resolution fails.</param> /// <param name="errorLocation">The location at which to report overload resolution result diagnostics.</param> /// <param name="suppressResultDiagnostics">True to suppress overload resolution result diagnostics (but not argument diagnostics).</param> /// <param name="diagnostics">Where diagnostics will be reported.</param> /// <param name="memberResolutionResult">If this method returns true, then it will contain a valid MethodResolutionResult. /// Otherwise, it may contain a MethodResolutionResult for an inaccessible constructor (in which case, it will incorrectly indicate success) or nothing at all.</param> /// <param name="candidateConstructors">Candidate instance constructors of type <paramref name="typeContainingConstructors"/> used for overload resolution.</param> /// <param name="allowProtectedConstructorsOfBaseType">It is always legal to access a protected base class constructor /// via a constructor initializer, but not from an object creation expression.</param> /// <returns>True if overload resolution successfully chose an accessible constructor.</returns> /// <remarks> /// The two-pass algorithm (accessible constructors, then all constructors) is the reason for the unusual signature /// of this method (i.e. not populating a pre-existing <see cref="OverloadResolutionResult{MethodSymbol}"/>). /// Presently, rationalizing this behavior is not worthwhile. /// </remarks> internal bool TryPerformConstructorOverloadResolution( NamedTypeSymbol typeContainingConstructors, AnalyzedArguments analyzedArguments, string errorName, Location errorLocation, bool suppressResultDiagnostics, BindingDiagnosticBag diagnostics, out MemberResolutionResult<MethodSymbol> memberResolutionResult, out ImmutableArray<MethodSymbol> candidateConstructors, bool allowProtectedConstructorsOfBaseType) // Last to make named arguments more convenient. { // Get accessible constructors for performing overload resolution. ImmutableArray<MethodSymbol> allInstanceConstructors; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); candidateConstructors = GetAccessibleConstructorsForOverloadResolution(typeContainingConstructors, allowProtectedConstructorsOfBaseType, out allInstanceConstructors, ref useSiteInfo); OverloadResolutionResult<MethodSymbol> result = OverloadResolutionResult<MethodSymbol>.GetInstance(); // Indicates whether overload resolution successfully chose an accessible constructor. bool succeededConsideringAccessibility = false; // Indicates whether overload resolution resulted in a single best match, even though it might be inaccessible. bool succeededIgnoringAccessibility = false; if (candidateConstructors.Any()) { // We have at least one accessible candidate constructor, perform overload resolution with accessible candidateConstructors. this.OverloadResolution.ObjectCreationOverloadResolution(candidateConstructors, analyzedArguments, result, ref useSiteInfo); if (result.Succeeded) { succeededConsideringAccessibility = true; succeededIgnoringAccessibility = true; } } if (!succeededConsideringAccessibility && allInstanceConstructors.Length > candidateConstructors.Length) { // Overload resolution failed on the accessible candidateConstructors, but we have at least one inaccessible constructor. // We might have a best match constructor which is inaccessible. // Try overload resolution with all instance constructors to generate correct diagnostics and semantic info for this case. OverloadResolutionResult<MethodSymbol> inaccessibleResult = OverloadResolutionResult<MethodSymbol>.GetInstance(); this.OverloadResolution.ObjectCreationOverloadResolution(allInstanceConstructors, analyzedArguments, inaccessibleResult, ref useSiteInfo); if (inaccessibleResult.Succeeded) { succeededIgnoringAccessibility = true; candidateConstructors = allInstanceConstructors; result.Free(); result = inaccessibleResult; } else { inaccessibleResult.Free(); } } diagnostics.Add(errorLocation, useSiteInfo); if (succeededIgnoringAccessibility) { this.CoerceArguments<MethodSymbol>(result.ValidResult, analyzedArguments.Arguments, diagnostics, receiverType: null, receiverRefKind: null, receiverEscapeScope: Binder.ExternalScope); } // Fill in the out parameter with the result, if there was one; it might be inaccessible. memberResolutionResult = succeededIgnoringAccessibility ? result.ValidResult : default(MemberResolutionResult<MethodSymbol>); // Invalid results are not interesting - we have enough info in candidateConstructors. // If something failed and we are reporting errors, then report the right errors. // * If the failure was due to inaccessibility, just report that. // * If the failure was not due to inaccessibility then only report an error // on the constructor if there were no errors on the arguments. if (!succeededConsideringAccessibility && !suppressResultDiagnostics) { if (succeededIgnoringAccessibility) { // It is not legal to directly call a protected constructor on a base class unless // the "this" of the call is known to be of the current type. That is, it is // perfectly legal to say ": base()" to call a protected base class ctor, but // it is not legal to say "new MyBase()" if the ctor is protected. // // The native compiler produces the error CS1540: // // Cannot access protected member 'MyBase.MyBase' via a qualifier of type 'MyBase'; // the qualifier must be of type 'Derived' (or derived from it) // // Though technically correct, this is a very confusing error message for this scenario; // one does not typically think of the constructor as being a method that is // called with an implicit "this" of a particular receiver type, even though of course // that is exactly what it is. // // The better error message here is to simply say that the best possible ctor cannot // be accessed because it is not accessible. // // CONSIDER: We might consider making up a new error message for this situation. // // CS0122: 'MyBase.MyBase' is inaccessible due to its protection level diagnostics.Add(ErrorCode.ERR_BadAccess, errorLocation, result.ValidResult.Member); } else { result.ReportDiagnostics( binder: this, location: errorLocation, nodeOpt: null, diagnostics, name: errorName, receiver: null, invokedExpression: null, analyzedArguments, memberGroup: candidateConstructors, typeContainingConstructors, delegateTypeBeingInvoked: null); } } result.Free(); return succeededConsideringAccessibility; } private ImmutableArray<MethodSymbol> GetAccessibleConstructorsForOverloadResolution(NamedTypeSymbol type, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { ImmutableArray<MethodSymbol> allInstanceConstructors; return GetAccessibleConstructorsForOverloadResolution(type, false, out allInstanceConstructors, ref useSiteInfo); } private ImmutableArray<MethodSymbol> GetAccessibleConstructorsForOverloadResolution(NamedTypeSymbol type, bool allowProtectedConstructorsOfBaseType, out ImmutableArray<MethodSymbol> allInstanceConstructors, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (type.IsErrorType()) { // For Caas, we want to supply the constructors even in error cases // We may end up supplying the constructors of an unconstructed symbol, // but that's better than nothing. type = type.GetNonErrorGuess() as NamedTypeSymbol ?? type; } allInstanceConstructors = type.InstanceConstructors; return FilterInaccessibleConstructors(allInstanceConstructors, allowProtectedConstructorsOfBaseType, ref useSiteInfo); } private static ConstantValue FoldParameterlessValueTypeConstructor(NamedTypeSymbol type) { // DELIBERATE SPEC VIOLATION: // // Object creation expressions like "new int()" are not considered constant expressions // by the specification but they are by the native compiler; we maintain compatibility // with this bug. // // Additionally, it also treats "new X()", where X is an enum type, as a // constant expression with default value 0, we maintain compatibility with it. var specialType = type.SpecialType; if (type.TypeKind == TypeKind.Enum) { specialType = type.EnumUnderlyingType.SpecialType; } switch (specialType) { case SpecialType.System_SByte: case SpecialType.System_Int16: case SpecialType.System_Int32: case SpecialType.System_Int64: case SpecialType.System_Byte: case SpecialType.System_UInt16: case SpecialType.System_UInt32: case SpecialType.System_UInt64: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: case SpecialType.System_Boolean: case SpecialType.System_Char: return ConstantValue.Default(specialType); } return null; } private BoundLiteral BindLiteralConstant(LiteralExpressionSyntax node, BindingDiagnosticBag diagnostics) { // bug.Assert(node.Kind == SyntaxKind.LiteralExpression); var value = node.Token.Value; ConstantValue cv; TypeSymbol type = null; if (value == null) { cv = ConstantValue.Null; } else { Debug.Assert(!value.GetType().GetTypeInfo().IsEnum); var specialType = SpecialTypeExtensions.FromRuntimeTypeOfLiteralValue(value); // C# literals can't be of type byte, sbyte, short, ushort: Debug.Assert( specialType != SpecialType.None && specialType != SpecialType.System_Byte && specialType != SpecialType.System_SByte && specialType != SpecialType.System_Int16 && specialType != SpecialType.System_UInt16); cv = ConstantValue.Create(value, specialType); type = GetSpecialType(specialType, diagnostics, node); } return new BoundLiteral(node, cv, type); } private BoundExpression BindCheckedExpression(CheckedExpressionSyntax node, BindingDiagnosticBag diagnostics) { // the binder is not cached since we only cache statement level binders return this.WithCheckedOrUncheckedRegion(node.Kind() == SyntaxKind.CheckedExpression). BindParenthesizedExpression(node.Expression, diagnostics); } /// <summary> /// Binds a member access expression /// </summary> private BoundExpression BindMemberAccess( MemberAccessExpressionSyntax node, bool invoked, bool indexed, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); BoundExpression boundLeft; ExpressionSyntax exprSyntax = node.Expression; if (node.Kind() == SyntaxKind.SimpleMemberAccessExpression) { // NOTE: CheckValue will be called explicitly in BindMemberAccessWithBoundLeft. boundLeft = BindLeftOfPotentialColorColorMemberAccess(exprSyntax, diagnostics); } else { Debug.Assert(node.Kind() == SyntaxKind.PointerMemberAccessExpression); boundLeft = BindRValueWithoutTargetType(exprSyntax, diagnostics); // Not Color Color issues with -> // CONSIDER: another approach would be to construct a BoundPointerMemberAccess (assuming such a type existed), // but that would be much more cumbersome because we'd be unable to build upon the BindMemberAccess infrastructure, // which expects a receiver. // Dereference before binding member; TypeSymbol pointedAtType; bool hasErrors; BindPointerIndirectionExpressionInternal(node, boundLeft, diagnostics, out pointedAtType, out hasErrors); // If there is no pointed-at type, fall back on the actual type (i.e. assume the user meant "." instead of "->"). if (ReferenceEquals(pointedAtType, null)) { boundLeft = ToBadExpression(boundLeft); } else { boundLeft = new BoundPointerIndirectionOperator(exprSyntax, boundLeft, pointedAtType, hasErrors) { WasCompilerGenerated = true, // don't interfere with the type info for exprSyntax. }; } } return BindMemberAccessWithBoundLeft(node, boundLeft, node.Name, node.OperatorToken, invoked, indexed, diagnostics); } /// <summary> /// Attempt to bind the LHS of a member access expression. If this is a Color Color case (spec 7.6.4.1), /// then return a BoundExpression if we can easily disambiguate or a BoundTypeOrValueExpression if we /// cannot. If this is not a Color Color case, then return null. /// </summary> private BoundExpression BindLeftOfPotentialColorColorMemberAccess(ExpressionSyntax left, BindingDiagnosticBag diagnostics) { if (left is IdentifierNameSyntax identifier) { return BindLeftIdentifierOfPotentialColorColorMemberAccess(identifier, diagnostics); } // NOTE: it is up to the caller to call CheckValue on the result. return BindExpression(left, diagnostics); } // Avoid inlining to minimize stack size in caller. [MethodImpl(MethodImplOptions.NoInlining)] private BoundExpression BindLeftIdentifierOfPotentialColorColorMemberAccess(IdentifierNameSyntax left, BindingDiagnosticBag diagnostics) { // SPEC: 7.6.4.1 Identical simple names and type names // SPEC: In a member access of the form E.I, if E is a single identifier, and if the meaning of E as // SPEC: a simple-name (spec 7.6.2) is a constant, field, property, local variable, or parameter with the // SPEC: same type as the meaning of E as a type-name (spec 3.8), then both possible meanings of E are // SPEC: permitted. The two possible meanings of E.I are never ambiguous, since I must necessarily be // SPEC: a member of the type E in both cases. In other words, the rule simply permits access to the // SPEC: static members and nested types of E where a compile-time error would otherwise have occurred. var valueDiagnostics = BindingDiagnosticBag.Create(diagnostics); var boundValue = BindIdentifier(left, invoked: false, indexed: false, diagnostics: valueDiagnostics); Symbol leftSymbol; if (boundValue.Kind == BoundKind.Conversion) { // BindFieldAccess may insert a conversion if binding occurs // within an enum member initializer. leftSymbol = ((BoundConversion)boundValue).Operand.ExpressionSymbol; } else { leftSymbol = boundValue.ExpressionSymbol; } if ((object)leftSymbol != null) { switch (leftSymbol.Kind) { case SymbolKind.Field: case SymbolKind.Local: case SymbolKind.Parameter: case SymbolKind.Property: case SymbolKind.RangeVariable: var leftType = boundValue.Type; Debug.Assert((object)leftType != null); var leftName = left.Identifier.ValueText; if (leftType.Name == leftName || IsUsingAliasInScope(leftName)) { var typeDiagnostics = BindingDiagnosticBag.Create(diagnostics); var boundType = BindNamespaceOrType(left, typeDiagnostics); if (TypeSymbol.Equals(boundType.Type, leftType, TypeCompareKind.ConsiderEverything2)) { // NOTE: ReplaceTypeOrValueReceiver will call CheckValue explicitly. boundValue = BindToNaturalType(boundValue, valueDiagnostics); return new BoundTypeOrValueExpression(left, new BoundTypeOrValueData(leftSymbol, boundValue, valueDiagnostics, boundType, typeDiagnostics), leftType); } } break; // case SymbolKind.Event: //SPEC: 7.6.4.1 (a.k.a. Color Color) doesn't cover events } } // Not a Color Color case; return the bound member. // NOTE: it is up to the caller to call CheckValue on the result. diagnostics.AddRange(valueDiagnostics); return boundValue; } // returns true if name matches a using alias in scope // NOTE: when true is returned, the corresponding using is also marked as "used" private bool IsUsingAliasInScope(string name) { var isSemanticModel = this.IsSemanticModelBinder; for (var chain = this.ImportChain; chain != null; chain = chain.ParentOpt) { if (IsUsingAlias(chain.Imports.UsingAliases, name, isSemanticModel)) { return true; } } return false; } private BoundExpression BindDynamicMemberAccess( ExpressionSyntax node, BoundExpression boundLeft, SimpleNameSyntax right, bool invoked, bool indexed, BindingDiagnosticBag diagnostics) { // We have an expression of the form "dynExpr.Name" or "dynExpr.Name<X>" SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax = right.Kind() == SyntaxKind.GenericName ? ((GenericNameSyntax)right).TypeArgumentList.Arguments : default(SeparatedSyntaxList<TypeSyntax>); bool rightHasTypeArguments = typeArgumentsSyntax.Count > 0; ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations = rightHasTypeArguments ? BindTypeArguments(typeArgumentsSyntax, diagnostics) : default(ImmutableArray<TypeWithAnnotations>); bool hasErrors = false; if (!invoked && rightHasTypeArguments) { // error CS0307: The property 'P' cannot be used with type arguments Error(diagnostics, ErrorCode.ERR_TypeArgsNotAllowed, right, right.Identifier.Text, SymbolKind.Property.Localize()); hasErrors = true; } if (rightHasTypeArguments) { for (int i = 0; i < typeArgumentsWithAnnotations.Length; ++i) { var typeArgument = typeArgumentsWithAnnotations[i]; if (typeArgument.Type.IsPointerOrFunctionPointer() || typeArgument.Type.IsRestrictedType()) { // "The type '{0}' may not be used as a type argument" Error(diagnostics, ErrorCode.ERR_BadTypeArgument, typeArgumentsSyntax[i], typeArgument.Type); hasErrors = true; } } } return new BoundDynamicMemberAccess( syntax: node, receiver: boundLeft, typeArgumentsOpt: typeArgumentsWithAnnotations, name: right.Identifier.ValueText, invoked: invoked, indexed: indexed, type: Compilation.DynamicType, hasErrors: hasErrors); } /// <summary> /// Bind the RHS of a member access expression, given the bound LHS. /// It is assumed that CheckValue has not been called on the LHS. /// </summary> /// <remarks> /// If new checks are added to this method, they will also need to be added to <see cref="MakeQueryInvocation(CSharpSyntaxNode, BoundExpression, string, TypeSyntax, TypeWithAnnotations, BindingDiagnosticBag)"/>. /// </remarks> private BoundExpression BindMemberAccessWithBoundLeft( ExpressionSyntax node, BoundExpression boundLeft, SimpleNameSyntax right, SyntaxToken operatorToken, bool invoked, bool indexed, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); Debug.Assert(boundLeft != null); boundLeft = MakeMemberAccessValue(boundLeft, diagnostics); TypeSymbol leftType = boundLeft.Type; if ((object)leftType != null && leftType.IsDynamic()) { // There are some sources of a `dynamic` typed value that can be known before runtime // to be invalid. For example, accessing a set-only property whose type is dynamic: // dynamic Goo { set; } // If Goo itself is a dynamic thing (e.g. in `x.Goo.Bar`, `x` is dynamic, and we're // currently checking Bar), then CheckValue will do nothing. boundLeft = CheckValue(boundLeft, BindValueKind.RValue, diagnostics); return BindDynamicMemberAccess(node, boundLeft, right, invoked, indexed, diagnostics); } // No member accesses on void if ((object)leftType != null && leftType.IsVoidType()) { diagnostics.Add(ErrorCode.ERR_BadUnaryOp, operatorToken.GetLocation(), SyntaxFacts.GetText(operatorToken.Kind()), leftType); return BadExpression(node, boundLeft); } // No member accesses on default if (boundLeft.IsLiteralDefault()) { DiagnosticInfo diagnosticInfo = new CSDiagnosticInfo(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, SyntaxFacts.GetText(operatorToken.Kind()), boundLeft.Display); diagnostics.Add(new CSDiagnostic(diagnosticInfo, operatorToken.GetLocation())); return BadExpression(node, boundLeft); } if (boundLeft.Kind == BoundKind.UnboundLambda) { Debug.Assert((object)leftType == null); var msgId = ((UnboundLambda)boundLeft).MessageID; diagnostics.Add(ErrorCode.ERR_BadUnaryOp, node.Location, SyntaxFacts.GetText(operatorToken.Kind()), msgId.Localize()); return BadExpression(node, boundLeft); } boundLeft = BindToNaturalType(boundLeft, diagnostics); leftType = boundLeft.Type; var lookupResult = LookupResult.GetInstance(); try { LookupOptions options = LookupOptions.AllMethodsOnArityZero; if (invoked) { options |= LookupOptions.MustBeInvocableIfMember; } var typeArgumentsSyntax = right.Kind() == SyntaxKind.GenericName ? ((GenericNameSyntax)right).TypeArgumentList.Arguments : default(SeparatedSyntaxList<TypeSyntax>); var typeArguments = typeArgumentsSyntax.Count > 0 ? BindTypeArguments(typeArgumentsSyntax, diagnostics) : default(ImmutableArray<TypeWithAnnotations>); // A member-access consists of a primary-expression, a predefined-type, or a // qualified-alias-member, followed by a "." token, followed by an identifier, // optionally followed by a type-argument-list. // A member-access is either of the form E.I or of the form E.I<A1, ..., AK>, where // E is a primary-expression, I is a single identifier and <A1, ..., AK> is an // optional type-argument-list. When no type-argument-list is specified, consider K // to be zero. // UNDONE: A member-access with a primary-expression of type dynamic is dynamically bound. // UNDONE: In this case the compiler classifies the member access as a property access of // UNDONE: type dynamic. The rules below to determine the meaning of the member-access are // UNDONE: then applied at run-time, using the run-time type instead of the compile-time // UNDONE: type of the primary-expression. If this run-time classification leads to a method // UNDONE: group, then the member access must be the primary-expression of an invocation-expression. // The member-access is evaluated and classified as follows: var rightName = right.Identifier.ValueText; var rightArity = right.Arity; BoundExpression result; switch (boundLeft.Kind) { case BoundKind.NamespaceExpression: { result = tryBindMemberAccessWithBoundNamespaceLeft(((BoundNamespaceExpression)boundLeft).NamespaceSymbol, node, boundLeft, right, diagnostics, lookupResult, options, typeArgumentsSyntax, typeArguments, rightName, rightArity); if (result is object) { return result; } break; } case BoundKind.TypeExpression: { result = tryBindMemberAccessWithBoundTypeLeft(node, boundLeft, right, invoked, indexed, diagnostics, leftType, lookupResult, options, typeArgumentsSyntax, typeArguments, rightName, rightArity); if (result is object) { return result; } break; } case BoundKind.TypeOrValueExpression: { // CheckValue call will occur in ReplaceTypeOrValueReceiver. // NOTE: This means that we won't get CheckValue diagnostics in error scenarios, // but they would be cascading anyway. return BindInstanceMemberAccess(node, right, boundLeft, rightName, rightArity, typeArgumentsSyntax, typeArguments, invoked, indexed, diagnostics); } default: { // Can't dot into the null literal if (boundLeft.Kind == BoundKind.Literal && ((BoundLiteral)boundLeft).ConstantValueOpt == ConstantValue.Null) { if (!boundLeft.HasAnyErrors) { Error(diagnostics, ErrorCode.ERR_BadUnaryOp, node, operatorToken.Text, boundLeft.Display); } return BadExpression(node, boundLeft); } else if ((object)leftType != null) { // NB: We don't know if we really only need RValue access, or if we are actually // passing the receiver implicitly by ref (e.g. in a struct instance method invocation). // These checks occur later. boundLeft = CheckValue(boundLeft, BindValueKind.RValue, diagnostics); boundLeft = BindToNaturalType(boundLeft, diagnostics); return BindInstanceMemberAccess(node, right, boundLeft, rightName, rightArity, typeArgumentsSyntax, typeArguments, invoked, indexed, diagnostics); } break; } } this.BindMemberAccessReportError(node, right, rightName, boundLeft, lookupResult.Error, diagnostics); return BindMemberAccessBadResult(node, rightName, boundLeft, lookupResult.Error, lookupResult.Symbols.ToImmutable(), lookupResult.Kind); } finally { lookupResult.Free(); } [MethodImpl(MethodImplOptions.NoInlining)] BoundExpression tryBindMemberAccessWithBoundNamespaceLeft( NamespaceSymbol ns, ExpressionSyntax node, BoundExpression boundLeft, SimpleNameSyntax right, BindingDiagnosticBag diagnostics, LookupResult lookupResult, LookupOptions options, SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax, ImmutableArray<TypeWithAnnotations> typeArguments, string rightName, int rightArity) { // If K is zero and E is a namespace and E contains a nested namespace with name I, // then the result is that namespace. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupMembersWithFallback(lookupResult, ns, rightName, rightArity, ref useSiteInfo, options: options); diagnostics.Add(right, useSiteInfo); ArrayBuilder<Symbol> symbols = lookupResult.Symbols; if (lookupResult.IsMultiViable) { bool wasError; Symbol sym = ResultSymbol(lookupResult, rightName, rightArity, node, diagnostics, false, out wasError, ns, options); if (wasError) { return new BoundBadExpression(node, LookupResultKind.Ambiguous, lookupResult.Symbols.AsImmutable(), ImmutableArray.Create(boundLeft), CreateErrorType(rightName), hasErrors: true); } else if (sym.Kind == SymbolKind.Namespace) { return new BoundNamespaceExpression(node, (NamespaceSymbol)sym); } else { Debug.Assert(sym.Kind == SymbolKind.NamedType); var type = (NamedTypeSymbol)sym; if (!typeArguments.IsDefault) { type = ConstructNamedTypeUnlessTypeArgumentOmitted(right, type, typeArgumentsSyntax, typeArguments, diagnostics); } ReportDiagnosticsIfObsolete(diagnostics, type, node, hasBaseReceiver: false); return new BoundTypeExpression(node, null, type); } } else if (lookupResult.Kind == LookupResultKind.WrongArity) { Debug.Assert(symbols.Count > 0); Debug.Assert(symbols[0].Kind == SymbolKind.NamedType); Error(diagnostics, lookupResult.Error, right); return new BoundTypeExpression(node, null, new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(symbols[0]), symbols.ToImmutable(), lookupResult.Kind, lookupResult.Error, rightArity)); } else if (lookupResult.Kind == LookupResultKind.Empty) { Debug.Assert(lookupResult.IsClear, "If there's a legitimate reason for having candidates without a reason, then we should produce something intelligent in such cases."); Debug.Assert(lookupResult.Error == null); NotFound(node, rightName, rightArity, rightName, diagnostics, aliasOpt: null, qualifierOpt: ns, options: options); return new BoundBadExpression(node, lookupResult.Kind, symbols.AsImmutable(), ImmutableArray.Create(boundLeft), CreateErrorType(rightName), hasErrors: true); } return null; } [MethodImpl(MethodImplOptions.NoInlining)] BoundExpression tryBindMemberAccessWithBoundTypeLeft( ExpressionSyntax node, BoundExpression boundLeft, SimpleNameSyntax right, bool invoked, bool indexed, BindingDiagnosticBag diagnostics, TypeSymbol leftType, LookupResult lookupResult, LookupOptions options, SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax, ImmutableArray<TypeWithAnnotations> typeArguments, string rightName, int rightArity) { Debug.Assert((object)leftType != null); if (leftType.TypeKind == TypeKind.TypeParameter) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupMembersWithFallback(lookupResult, leftType, rightName, rightArity, ref useSiteInfo, basesBeingResolved: null, options: options | LookupOptions.MustNotBeInstance | LookupOptions.MustBeAbstract); diagnostics.Add(right, useSiteInfo); if (lookupResult.IsMultiViable) { CheckFeatureAvailability(boundLeft.Syntax, MessageID.IDS_FeatureStaticAbstractMembersInInterfaces, diagnostics); return BindMemberOfType(node, right, rightName, rightArity, indexed, boundLeft, typeArgumentsSyntax, typeArguments, lookupResult, BoundMethodGroupFlags.None, diagnostics: diagnostics); } else if (lookupResult.IsClear) { Error(diagnostics, ErrorCode.ERR_BadSKunknown, boundLeft.Syntax, leftType, MessageID.IDS_SK_TYVAR.Localize()); return BadExpression(node, LookupResultKind.NotAValue, boundLeft); } } else if (this.EnclosingNameofArgument == node) { // Support selecting an extension method from a type name in nameof(.) return BindInstanceMemberAccess(node, right, boundLeft, rightName, rightArity, typeArgumentsSyntax, typeArguments, invoked, indexed, diagnostics); } else { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupMembersWithFallback(lookupResult, leftType, rightName, rightArity, ref useSiteInfo, basesBeingResolved: null, options: options); diagnostics.Add(right, useSiteInfo); if (lookupResult.IsMultiViable) { return BindMemberOfType(node, right, rightName, rightArity, indexed, boundLeft, typeArgumentsSyntax, typeArguments, lookupResult, BoundMethodGroupFlags.None, diagnostics: diagnostics); } } return null; } } private void WarnOnAccessOfOffDefault(SyntaxNode node, BoundExpression boundLeft, BindingDiagnosticBag diagnostics) { if ((boundLeft is BoundDefaultLiteral || boundLeft is BoundDefaultExpression) && boundLeft.ConstantValue == ConstantValue.Null && Compilation.LanguageVersion < MessageID.IDS_FeatureNullableReferenceTypes.RequiredVersion()) { Error(diagnostics, ErrorCode.WRN_DotOnDefault, node, boundLeft.Type); } } /// <summary> /// Create a value from the expression that can be used as a left-hand-side /// of a member access. This method special-cases method and property /// groups only. All other expressions are returned as is. /// </summary> private BoundExpression MakeMemberAccessValue(BoundExpression expr, BindingDiagnosticBag diagnostics) { switch (expr.Kind) { case BoundKind.MethodGroup: { var methodGroup = (BoundMethodGroup)expr; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var resolution = this.ResolveMethodGroup(methodGroup, analyzedArguments: null, isMethodGroupConversion: false, useSiteInfo: ref useSiteInfo); diagnostics.Add(expr.Syntax, useSiteInfo); if (!expr.HasAnyErrors) { diagnostics.AddRange(resolution.Diagnostics); if (resolution.MethodGroup != null && !resolution.HasAnyErrors) { Debug.Assert(!resolution.IsEmpty); var method = resolution.MethodGroup.Methods[0]; Error(diagnostics, ErrorCode.ERR_BadSKunknown, methodGroup.NameSyntax, method, MessageID.IDS_SK_METHOD.Localize()); } } expr = this.BindMemberAccessBadResult(methodGroup); resolution.Free(); return expr; } case BoundKind.PropertyGroup: return BindIndexedPropertyAccess((BoundPropertyGroup)expr, mustHaveAllOptionalParameters: false, diagnostics: diagnostics); default: return BindToNaturalType(expr, diagnostics); } } private BoundExpression BindInstanceMemberAccess( SyntaxNode node, SyntaxNode right, BoundExpression boundLeft, string rightName, int rightArity, SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax, ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations, bool invoked, bool indexed, BindingDiagnosticBag diagnostics, bool searchExtensionMethodsIfNecessary = true) { Debug.Assert(rightArity == (typeArgumentsWithAnnotations.IsDefault ? 0 : typeArgumentsWithAnnotations.Length)); var leftType = boundLeft.Type; LookupOptions options = LookupOptions.AllMethodsOnArityZero; if (invoked) { options |= LookupOptions.MustBeInvocableIfMember; } var lookupResult = LookupResult.GetInstance(); try { // If E is a property access, indexer access, variable, or value, the type of // which is T, and a member lookup of I in T with K type arguments produces a // match, then E.I is evaluated and classified as follows: // UNDONE: Classify E as prop access, indexer access, variable or value bool leftIsBaseReference = boundLeft.Kind == BoundKind.BaseReference; if (leftIsBaseReference) { options |= LookupOptions.UseBaseReferenceAccessibility; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupMembersWithFallback(lookupResult, leftType, rightName, rightArity, ref useSiteInfo, basesBeingResolved: null, options: options); diagnostics.Add(right, useSiteInfo); // SPEC: Otherwise, an attempt is made to process E.I as an extension method invocation. // SPEC: If this fails, E.I is an invalid member reference, and a binding-time error occurs. searchExtensionMethodsIfNecessary = searchExtensionMethodsIfNecessary && !leftIsBaseReference; BoundMethodGroupFlags flags = 0; if (searchExtensionMethodsIfNecessary) { flags |= BoundMethodGroupFlags.SearchExtensionMethods; } if (lookupResult.IsMultiViable) { return BindMemberOfType(node, right, rightName, rightArity, indexed, boundLeft, typeArgumentsSyntax, typeArgumentsWithAnnotations, lookupResult, flags, diagnostics); } if (searchExtensionMethodsIfNecessary) { var boundMethodGroup = new BoundMethodGroup( node, typeArgumentsWithAnnotations, boundLeft, rightName, lookupResult.Symbols.All(s => s.Kind == SymbolKind.Method) ? lookupResult.Symbols.SelectAsArray(s_toMethodSymbolFunc) : ImmutableArray<MethodSymbol>.Empty, lookupResult, flags); if (!boundMethodGroup.HasErrors && typeArgumentsSyntax.Any(SyntaxKind.OmittedTypeArgument)) { Error(diagnostics, ErrorCode.ERR_OmittedTypeArgument, node); } return boundMethodGroup; } this.BindMemberAccessReportError(node, right, rightName, boundLeft, lookupResult.Error, diagnostics); return BindMemberAccessBadResult(node, rightName, boundLeft, lookupResult.Error, lookupResult.Symbols.ToImmutable(), lookupResult.Kind); } finally { lookupResult.Free(); } } private void BindMemberAccessReportError(BoundMethodGroup node, BindingDiagnosticBag diagnostics) { var nameSyntax = node.NameSyntax; var syntax = node.MemberAccessExpressionSyntax ?? nameSyntax; this.BindMemberAccessReportError(syntax, nameSyntax, node.Name, node.ReceiverOpt, node.LookupError, diagnostics); } /// <summary> /// Report the error from member access lookup. Or, if there /// was no explicit error from lookup, report "no such member". /// </summary> private void BindMemberAccessReportError( SyntaxNode node, SyntaxNode name, string plainName, BoundExpression boundLeft, DiagnosticInfo lookupError, BindingDiagnosticBag diagnostics) { if (boundLeft.HasAnyErrors && boundLeft.Kind != BoundKind.TypeOrValueExpression) { return; } if (lookupError != null) { // CONSIDER: there are some cases where Dev10 uses the span of "node", // rather than "right". diagnostics.Add(new CSDiagnostic(lookupError, name.Location)); } else if (node.IsQuery()) { ReportQueryLookupFailed(node, boundLeft, plainName, ImmutableArray<Symbol>.Empty, diagnostics); } else { if ((object)boundLeft.Type == null) { Error(diagnostics, ErrorCode.ERR_NoSuchMember, name, boundLeft.Display, plainName); } else if (boundLeft.Kind == BoundKind.TypeExpression || boundLeft.Kind == BoundKind.BaseReference || node.Kind() == SyntaxKind.AwaitExpression && plainName == WellKnownMemberNames.GetResult) { Error(diagnostics, ErrorCode.ERR_NoSuchMember, name, boundLeft.Type, plainName); } else if (WouldUsingSystemFindExtension(boundLeft.Type, plainName)) { Error(diagnostics, ErrorCode.ERR_NoSuchMemberOrExtensionNeedUsing, name, boundLeft.Type, plainName, "System"); } else { Error(diagnostics, ErrorCode.ERR_NoSuchMemberOrExtension, name, boundLeft.Type, plainName); } } } private bool WouldUsingSystemFindExtension(TypeSymbol receiver, string methodName) { // we have a special case to make the diagnostic for await expressions more clear for Windows: // if the receiver type is a windows RT async interface and the method name is GetAwaiter, // then we would suggest a using directive for "System". // TODO: we should check if such a using directive would actually help, or if there is already one in scope. return methodName == WellKnownMemberNames.GetAwaiter && ImplementsWinRTAsyncInterface(receiver); } /// <summary> /// Return true if the given type is or implements a WinRTAsyncInterface. /// </summary> private bool ImplementsWinRTAsyncInterface(TypeSymbol type) { return IsWinRTAsyncInterface(type) || type.AllInterfacesNoUseSiteDiagnostics.Any(i => IsWinRTAsyncInterface(i)); } private bool IsWinRTAsyncInterface(TypeSymbol type) { if (!type.IsInterfaceType()) { return false; } var namedType = ((NamedTypeSymbol)type).ConstructedFrom; return TypeSymbol.Equals(namedType, Compilation.GetWellKnownType(WellKnownType.Windows_Foundation_IAsyncAction), TypeCompareKind.ConsiderEverything2) || TypeSymbol.Equals(namedType, Compilation.GetWellKnownType(WellKnownType.Windows_Foundation_IAsyncActionWithProgress_T), TypeCompareKind.ConsiderEverything2) || TypeSymbol.Equals(namedType, Compilation.GetWellKnownType(WellKnownType.Windows_Foundation_IAsyncOperation_T), TypeCompareKind.ConsiderEverything2) || TypeSymbol.Equals(namedType, Compilation.GetWellKnownType(WellKnownType.Windows_Foundation_IAsyncOperationWithProgress_T2), TypeCompareKind.ConsiderEverything2); } private BoundExpression BindMemberAccessBadResult(BoundMethodGroup node) { var nameSyntax = node.NameSyntax; var syntax = node.MemberAccessExpressionSyntax ?? nameSyntax; return this.BindMemberAccessBadResult(syntax, node.Name, node.ReceiverOpt, node.LookupError, StaticCast<Symbol>.From(node.Methods), node.ResultKind); } /// <summary> /// Return a BoundExpression representing the invalid member. /// </summary> private BoundExpression BindMemberAccessBadResult( SyntaxNode node, string nameString, BoundExpression boundLeft, DiagnosticInfo lookupError, ImmutableArray<Symbol> symbols, LookupResultKind lookupKind) { if (symbols.Length > 0 && symbols[0].Kind == SymbolKind.Method) { var builder = ArrayBuilder<MethodSymbol>.GetInstance(); foreach (var s in symbols) { var m = s as MethodSymbol; if ((object)m != null) builder.Add(m); } var methods = builder.ToImmutableAndFree(); // Expose the invalid methods as a BoundMethodGroup. // Since we do not want to perform further method // lookup, searchExtensionMethods is set to false. // Don't bother calling ConstructBoundMethodGroupAndReportOmittedTypeArguments - // we've reported other errors. return new BoundMethodGroup( node, default(ImmutableArray<TypeWithAnnotations>), nameString, methods, methods.Length == 1 ? methods[0] : null, lookupError, flags: BoundMethodGroupFlags.None, receiverOpt: boundLeft, resultKind: lookupKind, hasErrors: true); } var symbolOpt = symbols.Length == 1 ? symbols[0] : null; return new BoundBadExpression( node, lookupKind, (object)symbolOpt == null ? ImmutableArray<Symbol>.Empty : ImmutableArray.Create(symbolOpt), boundLeft == null ? ImmutableArray<BoundExpression>.Empty : ImmutableArray.Create(BindToTypeForErrorRecovery(boundLeft)), GetNonMethodMemberType(symbolOpt)); } private TypeSymbol GetNonMethodMemberType(Symbol symbolOpt) { TypeSymbol resultType = null; if ((object)symbolOpt != null) { switch (symbolOpt.Kind) { case SymbolKind.Field: resultType = ((FieldSymbol)symbolOpt).GetFieldType(this.FieldsBeingBound).Type; break; case SymbolKind.Property: resultType = ((PropertySymbol)symbolOpt).Type; break; case SymbolKind.Event: resultType = ((EventSymbol)symbolOpt).Type; break; } } return resultType ?? CreateErrorType(); } /// <summary> /// Combine the receiver and arguments of an extension method /// invocation into a single argument list to allow overload resolution /// to treat the invocation as a static method invocation with no receiver. /// </summary> private static void CombineExtensionMethodArguments(BoundExpression receiver, AnalyzedArguments originalArguments, AnalyzedArguments extensionMethodArguments) { Debug.Assert(receiver != null); Debug.Assert(extensionMethodArguments.Arguments.Count == 0); Debug.Assert(extensionMethodArguments.Names.Count == 0); Debug.Assert(extensionMethodArguments.RefKinds.Count == 0); extensionMethodArguments.IsExtensionMethodInvocation = true; extensionMethodArguments.Arguments.Add(receiver); extensionMethodArguments.Arguments.AddRange(originalArguments.Arguments); if (originalArguments.Names.Count > 0) { extensionMethodArguments.Names.Add(null); extensionMethodArguments.Names.AddRange(originalArguments.Names); } if (originalArguments.RefKinds.Count > 0) { extensionMethodArguments.RefKinds.Add(RefKind.None); extensionMethodArguments.RefKinds.AddRange(originalArguments.RefKinds); } } /// <summary> /// Binds a static or instance member access. /// </summary> private BoundExpression BindMemberOfType( SyntaxNode node, SyntaxNode right, string plainName, int arity, bool indexed, BoundExpression left, SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax, ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations, LookupResult lookupResult, BoundMethodGroupFlags methodGroupFlags, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); Debug.Assert(left != null); Debug.Assert(lookupResult.IsMultiViable); Debug.Assert(lookupResult.Symbols.Any()); var members = ArrayBuilder<Symbol>.GetInstance(); BoundExpression result; bool wasError; Symbol symbol = GetSymbolOrMethodOrPropertyGroup(lookupResult, right, plainName, arity, members, diagnostics, out wasError, qualifierOpt: left is BoundTypeExpression typeExpr ? typeExpr.Type : null); if ((object)symbol == null) { Debug.Assert(members.Count > 0); // If I identifies one or more methods, then the result is a method group with // no associated instance expression. If a type argument list was specified, it // is used in calling a generic method. // (Note that for static methods, we are stashing away the type expression in // the receiver of the method group, even though the spec notes that there is // no associated instance expression.) result = ConstructBoundMemberGroupAndReportOmittedTypeArguments( node, typeArgumentsSyntax, typeArgumentsWithAnnotations, left, plainName, members, lookupResult, methodGroupFlags, wasError, diagnostics); } else { // methods are special because of extension methods. Debug.Assert(symbol.Kind != SymbolKind.Method); left = ReplaceTypeOrValueReceiver(left, symbol.IsStatic || symbol.Kind == SymbolKind.NamedType, diagnostics); // Events are handled later as we don't know yet if we are binding to the event or it's backing field. if (symbol.Kind != SymbolKind.Event) { ReportDiagnosticsIfObsolete(diagnostics, symbol, node, hasBaseReceiver: left.Kind == BoundKind.BaseReference); } switch (symbol.Kind) { case SymbolKind.NamedType: case SymbolKind.ErrorType: if (IsInstanceReceiver(left) == true && !wasError) { // CS0572: 'B': cannot reference a type through an expression; try 'A.B' instead Error(diagnostics, ErrorCode.ERR_BadTypeReference, right, plainName, symbol); wasError = true; } // If I identifies a type, then the result is that type constructed with // the given type arguments. var type = (NamedTypeSymbol)symbol; if (!typeArgumentsWithAnnotations.IsDefault) { type = ConstructNamedTypeUnlessTypeArgumentOmitted(right, type, typeArgumentsSyntax, typeArgumentsWithAnnotations, diagnostics); } result = new BoundTypeExpression( syntax: node, aliasOpt: null, boundContainingTypeOpt: left as BoundTypeExpression, boundDimensionsOpt: ImmutableArray<BoundExpression>.Empty, typeWithAnnotations: TypeWithAnnotations.Create(type)); break; case SymbolKind.Property: // If I identifies a static property, then the result is a property // access with no associated instance expression. result = BindPropertyAccess(node, left, (PropertySymbol)symbol, diagnostics, lookupResult.Kind, hasErrors: wasError); break; case SymbolKind.Event: // If I identifies a static event, then the result is an event // access with no associated instance expression. result = BindEventAccess(node, left, (EventSymbol)symbol, diagnostics, lookupResult.Kind, hasErrors: wasError); break; case SymbolKind.Field: // If I identifies a static field: // UNDONE: If the field is readonly and the reference occurs outside the static constructor of // UNDONE: the class or struct in which the field is declared, then the result is a value, namely // UNDONE: the value of the static field I in E. // UNDONE: Otherwise, the result is a variable, namely the static field I in E. // UNDONE: Need a way to mark an expression node as "I am a variable, not a value". result = BindFieldAccess(node, left, (FieldSymbol)symbol, diagnostics, lookupResult.Kind, indexed, hasErrors: wasError); break; default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } } members.Free(); return result; } protected MethodGroupResolution BindExtensionMethod( SyntaxNode expression, string methodName, AnalyzedArguments analyzedArguments, BoundExpression left, ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations, bool isMethodGroupConversion, RefKind returnRefKind, TypeSymbol returnType, bool withDependencies) { var firstResult = new MethodGroupResolution(); AnalyzedArguments actualArguments = null; foreach (var scope in new ExtensionMethodScopes(this)) { var methodGroup = MethodGroup.GetInstance(); var diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies); this.PopulateExtensionMethodsFromSingleBinder(scope, methodGroup, expression, left, methodName, typeArgumentsWithAnnotations, diagnostics); // analyzedArguments will be null if the caller is resolving for error recovery to the first method group // that can accept that receiver, regardless of arguments, when the signature cannot be inferred. // (In the error case of nameof(o.M) or the error case of o.M = null; for instance.) if (analyzedArguments == null) { if (expression == EnclosingNameofArgument) { for (int i = methodGroup.Methods.Count - 1; i >= 0; i--) { if ((object)methodGroup.Methods[i].ReduceExtensionMethod(left.Type, this.Compilation) == null) methodGroup.Methods.RemoveAt(i); } } if (methodGroup.Methods.Count != 0) { return new MethodGroupResolution(methodGroup, diagnostics.ToReadOnlyAndFree()); } } if (methodGroup.Methods.Count == 0) { methodGroup.Free(); diagnostics.Free(); continue; } if (actualArguments == null) { // Create a set of arguments for overload resolution of the // extension methods that includes the "this" parameter. actualArguments = AnalyzedArguments.GetInstance(); CombineExtensionMethodArguments(left, analyzedArguments, actualArguments); } var overloadResolutionResult = OverloadResolutionResult<MethodSymbol>.GetInstance(); bool allowRefOmittedArguments = methodGroup.Receiver.IsExpressionOfComImportType(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); OverloadResolution.MethodInvocationOverloadResolution( methods: methodGroup.Methods, typeArguments: methodGroup.TypeArguments, receiver: methodGroup.Receiver, arguments: actualArguments, result: overloadResolutionResult, useSiteInfo: ref useSiteInfo, isMethodGroupConversion: isMethodGroupConversion, allowRefOmittedArguments: allowRefOmittedArguments, returnRefKind: returnRefKind, returnType: returnType); diagnostics.Add(expression, useSiteInfo); var sealedDiagnostics = diagnostics.ToReadOnlyAndFree(); // Note: the MethodGroupResolution instance is responsible for freeing its copy of actual arguments var result = new MethodGroupResolution(methodGroup, null, overloadResolutionResult, AnalyzedArguments.GetInstance(actualArguments), methodGroup.ResultKind, sealedDiagnostics); // If the search in the current scope resulted in any applicable method (regardless of whether a best // applicable method could be determined) then our search is complete. Otherwise, store aside the // first non-applicable result and continue searching for an applicable result. if (result.HasAnyApplicableMethod) { if (!firstResult.IsEmpty) { firstResult.MethodGroup.Free(); firstResult.OverloadResolutionResult.Free(); } return result; } else if (firstResult.IsEmpty) { firstResult = result; } else { // Neither the first result, nor applicable. No need to save result. overloadResolutionResult.Free(); methodGroup.Free(); } } Debug.Assert((actualArguments == null) || !firstResult.IsEmpty); actualArguments?.Free(); return firstResult; } private void PopulateExtensionMethodsFromSingleBinder( ExtensionMethodScope scope, MethodGroup methodGroup, SyntaxNode node, BoundExpression left, string rightName, ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations, BindingDiagnosticBag diagnostics) { int arity; LookupOptions options; if (typeArgumentsWithAnnotations.IsDefault) { arity = 0; options = LookupOptions.AllMethodsOnArityZero; } else { arity = typeArgumentsWithAnnotations.Length; options = LookupOptions.Default; } var lookupResult = LookupResult.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupExtensionMethodsInSingleBinder(scope, lookupResult, rightName, arity, options, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (lookupResult.IsMultiViable) { Debug.Assert(lookupResult.Symbols.Any()); var members = ArrayBuilder<Symbol>.GetInstance(); bool wasError; Symbol symbol = GetSymbolOrMethodOrPropertyGroup(lookupResult, node, rightName, arity, members, diagnostics, out wasError, qualifierOpt: null); Debug.Assert((object)symbol == null); Debug.Assert(members.Count > 0); methodGroup.PopulateWithExtensionMethods(left, members, typeArgumentsWithAnnotations, lookupResult.Kind); members.Free(); } lookupResult.Free(); } protected BoundExpression BindFieldAccess( SyntaxNode node, BoundExpression receiver, FieldSymbol fieldSymbol, BindingDiagnosticBag diagnostics, LookupResultKind resultKind, bool indexed, bool hasErrors) { bool hasError = false; NamedTypeSymbol type = fieldSymbol.ContainingType; var isEnumField = (fieldSymbol.IsStatic && type.IsEnumType()); if (isEnumField && !type.IsValidEnumType()) { Error(diagnostics, ErrorCode.ERR_BindToBogus, node, fieldSymbol); hasError = true; } if (!hasError) { hasError = this.CheckInstanceOrStatic(node, receiver, fieldSymbol, ref resultKind, diagnostics); } if (!hasError && fieldSymbol.IsFixedSizeBuffer && !IsInsideNameof) { // SPEC: In a member access of the form E.I, if E is of a struct type and a member lookup of I in // that struct type identifies a fixed size member, then E.I is evaluated and classified as follows: // * If the expression E.I does not occur in an unsafe context, a compile-time error occurs. // * If E is classified as a value, a compile-time error occurs. // * Otherwise, if E is a moveable variable and the expression E.I is not a fixed_pointer_initializer, // a compile-time error occurs. // * Otherwise, E references a fixed variable and the result of the expression is a pointer to the // first element of the fixed size buffer member I in E. The result is of type S*, where S is // the element type of I, and is classified as a value. TypeSymbol receiverType = receiver.Type; // Reflect errors that have been reported elsewhere... hasError = (object)receiverType == null || !receiverType.IsValueType; if (!hasError) { var isFixedStatementExpression = SyntaxFacts.IsFixedStatementExpression(node); if (IsMoveableVariable(receiver, out Symbol accessedLocalOrParameterOpt) != isFixedStatementExpression) { if (indexed) { // SPEC C# 7.3: If the fixed size buffer access is the receiver of an element_access_expression, // E may be either fixed or moveable CheckFeatureAvailability(node, MessageID.IDS_FeatureIndexingMovableFixedBuffers, diagnostics); } else { Error(diagnostics, isFixedStatementExpression ? ErrorCode.ERR_FixedNotNeeded : ErrorCode.ERR_FixedBufferNotFixed, node); hasErrors = hasError = true; } } } if (!hasError) { hasError = !CheckValueKind(node, receiver, BindValueKind.FixedReceiver, checkingReceiver: false, diagnostics: diagnostics); } } ConstantValue constantValueOpt = null; if (fieldSymbol.IsConst && !IsInsideNameof) { constantValueOpt = fieldSymbol.GetConstantValue(this.ConstantFieldsInProgress, this.IsEarlyAttributeBinder); if (constantValueOpt == ConstantValue.Unset) { // Evaluating constant expression before dependencies // have been evaluated. Treat this as a Bad value. constantValueOpt = ConstantValue.Bad; } } if (!fieldSymbol.IsStatic) { WarnOnAccessOfOffDefault(node, receiver, diagnostics); } if (!IsBadBaseAccess(node, receiver, fieldSymbol, diagnostics)) { CheckReceiverAndRuntimeSupportForSymbolAccess(node, receiver, fieldSymbol, diagnostics); } TypeSymbol fieldType = fieldSymbol.GetFieldType(this.FieldsBeingBound).Type; BoundExpression expr = new BoundFieldAccess(node, receiver, fieldSymbol, constantValueOpt, resultKind, fieldType, hasErrors: (hasErrors || hasError)); // Spec 14.3: "Within an enum member initializer, values of other enum members are // always treated as having the type of their underlying type" if (this.InEnumMemberInitializer()) { NamedTypeSymbol enumType = null; if (isEnumField) { // This is an obvious consequence of the spec. // It is for cases like: // enum E { // A, // B = A + 1, //A is implicitly converted to int (underlying type) // } enumType = type; } else if (constantValueOpt != null && fieldType.IsEnumType()) { // This seems like a borderline SPEC VIOLATION that we're preserving for back compat. // It is for cases like: // const E e = E.A; // enum E { // A, // B = e + 1, //e is implicitly converted to int (underlying type) // } enumType = (NamedTypeSymbol)fieldType; } if ((object)enumType != null) { NamedTypeSymbol underlyingType = enumType.EnumUnderlyingType; Debug.Assert((object)underlyingType != null); expr = new BoundConversion( node, expr, Conversion.ImplicitNumeric, @checked: true, explicitCastInCode: false, conversionGroupOpt: null, constantValueOpt: expr.ConstantValue, type: underlyingType); } } return expr; } private bool InEnumMemberInitializer() { var containingType = this.ContainingType; return this.InFieldInitializer && (object)containingType != null && containingType.IsEnumType(); } private BoundExpression BindPropertyAccess( SyntaxNode node, BoundExpression receiver, PropertySymbol propertySymbol, BindingDiagnosticBag diagnostics, LookupResultKind lookupResult, bool hasErrors) { bool hasError = this.CheckInstanceOrStatic(node, receiver, propertySymbol, ref lookupResult, diagnostics); if (!propertySymbol.IsStatic) { WarnOnAccessOfOffDefault(node, receiver, diagnostics); } return new BoundPropertyAccess(node, receiver, propertySymbol, lookupResult, propertySymbol.Type, hasErrors: (hasErrors || hasError)); } private void CheckReceiverAndRuntimeSupportForSymbolAccess(SyntaxNode node, BoundExpression receiverOpt, Symbol symbol, BindingDiagnosticBag diagnostics) { if (symbol.ContainingType?.IsInterface == true) { if (symbol.IsStatic && symbol.IsAbstract) { Debug.Assert(symbol is not TypeSymbol); if (receiverOpt is BoundQueryClause { Value: var value }) { receiverOpt = value; } if (receiverOpt is not BoundTypeExpression { Type: { TypeKind: TypeKind.TypeParameter } }) { Error(diagnostics, ErrorCode.ERR_BadAbstractStaticMemberAccess, node); return; } if (!Compilation.Assembly.RuntimeSupportsStaticAbstractMembersInInterfaces && Compilation.SourceModule != symbol.ContainingModule) { Error(diagnostics, ErrorCode.ERR_RuntimeDoesNotSupportStaticAbstractMembersInInterfaces, node); return; } } if (!Compilation.Assembly.RuntimeSupportsDefaultInterfaceImplementation && Compilation.SourceModule != symbol.ContainingModule) { if (!symbol.IsStatic && !(symbol is TypeSymbol) && !symbol.IsImplementableInterfaceMember()) { Error(diagnostics, ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, node); } else { switch (symbol.DeclaredAccessibility) { case Accessibility.Protected: case Accessibility.ProtectedOrInternal: case Accessibility.ProtectedAndInternal: Error(diagnostics, ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, node); break; } } } } } private BoundExpression BindEventAccess( SyntaxNode node, BoundExpression receiver, EventSymbol eventSymbol, BindingDiagnosticBag diagnostics, LookupResultKind lookupResult, bool hasErrors) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); bool isUsableAsField = eventSymbol.HasAssociatedField && this.IsAccessible(eventSymbol.AssociatedField, ref useSiteInfo, (receiver != null) ? receiver.Type : null); diagnostics.Add(node, useSiteInfo); bool hasError = this.CheckInstanceOrStatic(node, receiver, eventSymbol, ref lookupResult, diagnostics); if (!eventSymbol.IsStatic) { WarnOnAccessOfOffDefault(node, receiver, diagnostics); } return new BoundEventAccess(node, receiver, eventSymbol, isUsableAsField, lookupResult, eventSymbol.Type, hasErrors: (hasErrors || hasError)); } // Say if the receive is an instance or a type, or could be either (returns null). private static bool? IsInstanceReceiver(BoundExpression receiver) { if (receiver == null) { return false; } else { switch (receiver.Kind) { case BoundKind.PreviousSubmissionReference: // Could be either instance or static reference. return null; case BoundKind.TypeExpression: return false; case BoundKind.QueryClause: return IsInstanceReceiver(((BoundQueryClause)receiver).Value); default: return true; } } } private bool CheckInstanceOrStatic( SyntaxNode node, BoundExpression receiver, Symbol symbol, ref LookupResultKind resultKind, BindingDiagnosticBag diagnostics) { bool? instanceReceiver = IsInstanceReceiver(receiver); if (!symbol.RequiresInstanceReceiver()) { if (instanceReceiver == true) { ErrorCode errorCode = this.Flags.Includes(BinderFlags.ObjectInitializerMember) ? ErrorCode.ERR_StaticMemberInObjectInitializer : ErrorCode.ERR_ObjectProhibited; Error(diagnostics, errorCode, node, symbol); resultKind = LookupResultKind.StaticInstanceMismatch; return true; } } else { if (instanceReceiver == false && !IsInsideNameof) { Error(diagnostics, ErrorCode.ERR_ObjectRequired, node, symbol); resultKind = LookupResultKind.StaticInstanceMismatch; return true; } } return false; } /// <summary> /// Given a viable LookupResult, report any ambiguity errors and return either a single /// non-method symbol or a method or property group. If the result set represents a /// collection of methods or a collection of properties where at least one of the properties /// is an indexed property, then 'methodOrPropertyGroup' is populated with the method or /// property group and the method returns null. Otherwise, the method returns a single /// symbol and 'methodOrPropertyGroup' is empty. (Since the result set is viable, there /// must be at least one symbol.) If the result set is ambiguous - either containing multiple /// members of different member types, or multiple properties but no indexed properties - /// then a diagnostic is reported for the ambiguity and a single symbol is returned. /// </summary> private Symbol GetSymbolOrMethodOrPropertyGroup(LookupResult result, SyntaxNode node, string plainName, int arity, ArrayBuilder<Symbol> methodOrPropertyGroup, BindingDiagnosticBag diagnostics, out bool wasError, NamespaceOrTypeSymbol qualifierOpt) { Debug.Assert(!methodOrPropertyGroup.Any()); node = GetNameSyntax(node) ?? node; wasError = false; Debug.Assert(result.Kind != LookupResultKind.Empty); Debug.Assert(!result.Symbols.Any(s => s.IsIndexer())); Symbol other = null; // different member type from 'methodOrPropertyGroup' // Populate 'methodOrPropertyGroup' with a set of methods if any, // or a set of properties if properties but no methods. If there are // other member types, 'other' will be set to one of those members. foreach (var symbol in result.Symbols) { var kind = symbol.Kind; if (methodOrPropertyGroup.Count > 0) { var existingKind = methodOrPropertyGroup[0].Kind; if (existingKind != kind) { // Mix of different member kinds. Prefer methods over // properties and properties over other members. if ((existingKind == SymbolKind.Method) || ((existingKind == SymbolKind.Property) && (kind != SymbolKind.Method))) { other = symbol; continue; } other = methodOrPropertyGroup[0]; methodOrPropertyGroup.Clear(); } } if ((kind == SymbolKind.Method) || (kind == SymbolKind.Property)) { // SPEC VIOLATION: The spec states "Members that include an override modifier are excluded from the set" // SPEC VIOLATION: However, we are not going to do that here; we will keep the overriding member // SPEC VIOLATION: in the method group. The reason is because for features like "go to definition" // SPEC VIOLATION: we wish to go to the overriding member, not to the member of the base class. // SPEC VIOLATION: Or, for code generation of a call to Int32.ToString() we want to generate // SPEC VIOLATION: code that directly calls the Int32.ToString method with an int on the stack, // SPEC VIOLATION: rather than making a virtual call to ToString on a boxed int. methodOrPropertyGroup.Add(symbol); } else { other = symbol; } } Debug.Assert(methodOrPropertyGroup.Any() || ((object)other != null)); if ((methodOrPropertyGroup.Count > 0) && IsMethodOrPropertyGroup(methodOrPropertyGroup)) { // Ambiguities between methods and non-methods are reported here, // but all other ambiguities, including those between properties and // non-methods, are reported in ResultSymbol. if ((methodOrPropertyGroup[0].Kind == SymbolKind.Method) || ((object)other == null)) { // Result will be treated as a method or property group. Any additional // checks, such as use-site errors, must be handled by the caller when // converting to method invocation or property access. if (result.Error != null) { Error(diagnostics, result.Error, node); wasError = (result.Error.Severity == DiagnosticSeverity.Error); } return null; } } methodOrPropertyGroup.Clear(); return ResultSymbol(result, plainName, arity, node, diagnostics, false, out wasError, qualifierOpt); } private static bool IsMethodOrPropertyGroup(ArrayBuilder<Symbol> members) { Debug.Assert(members.Count > 0); var member = members[0]; // Members should be a consistent type. Debug.Assert(members.All(m => m.Kind == member.Kind)); switch (member.Kind) { case SymbolKind.Method: return true; case SymbolKind.Property: Debug.Assert(members.All(m => !m.IsIndexer())); // Do not treat a set of non-indexed properties as a property group, to // avoid the overhead of a BoundPropertyGroup node and overload // resolution for the common property access case. If there are multiple // non-indexed properties (two properties P that differ by custom attributes // for instance), the expectation is that the caller will report an ambiguity // and choose one for error recovery. foreach (PropertySymbol property in members) { if (property.IsIndexedProperty) { return true; } } return false; default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } private BoundExpression BindElementAccess(ElementAccessExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression receiver = BindExpression(node.Expression, diagnostics: diagnostics, invoked: false, indexed: true); return BindElementAccess(node, receiver, node.ArgumentList, diagnostics); } private BoundExpression BindElementAccess(ExpressionSyntax node, BoundExpression receiver, BracketedArgumentListSyntax argumentList, BindingDiagnosticBag diagnostics) { AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance(); try { BindArgumentsAndNames(argumentList, diagnostics, analyzedArguments); if (receiver.Kind == BoundKind.PropertyGroup) { var propertyGroup = (BoundPropertyGroup)receiver; return BindIndexedPropertyAccess(node, propertyGroup.ReceiverOpt, propertyGroup.Properties, analyzedArguments, diagnostics); } receiver = CheckValue(receiver, BindValueKind.RValue, diagnostics); receiver = BindToNaturalType(receiver, diagnostics); return BindElementOrIndexerAccess(node, receiver, analyzedArguments, diagnostics); } finally { analyzedArguments.Free(); } } private BoundExpression BindElementOrIndexerAccess(ExpressionSyntax node, BoundExpression expr, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics) { if ((object)expr.Type == null) { return BadIndexerExpression(node, expr, analyzedArguments, null, diagnostics); } WarnOnAccessOfOffDefault(node, expr, diagnostics); // Did we have any errors? if (analyzedArguments.HasErrors || expr.HasAnyErrors) { // At this point we definitely have reported an error, but we still might be // able to get more semantic analysis of the indexing operation. We do not // want to report cascading errors. BoundExpression result = BindElementAccessCore(node, expr, analyzedArguments, BindingDiagnosticBag.Discarded); return result; } return BindElementAccessCore(node, expr, analyzedArguments, diagnostics); } private BoundExpression BadIndexerExpression(ExpressionSyntax node, BoundExpression expr, AnalyzedArguments analyzedArguments, DiagnosticInfo errorOpt, BindingDiagnosticBag diagnostics) { if (!expr.HasAnyErrors) { diagnostics.Add(errorOpt ?? new CSDiagnosticInfo(ErrorCode.ERR_BadIndexLHS, expr.Display), node.Location); } var childBoundNodes = BuildArgumentsForErrorRecovery(analyzedArguments).Add(expr); return new BoundBadExpression(node, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, childBoundNodes, CreateErrorType(), hasErrors: true); } private BoundExpression BindElementAccessCore( ExpressionSyntax node, BoundExpression expr, AnalyzedArguments arguments, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); Debug.Assert(expr != null); Debug.Assert((object)expr.Type != null); Debug.Assert(arguments != null); var exprType = expr.Type; switch (exprType.TypeKind) { case TypeKind.Array: return BindArrayAccess(node, expr, arguments, diagnostics); case TypeKind.Dynamic: return BindDynamicIndexer(node, expr, arguments, ImmutableArray<PropertySymbol>.Empty, diagnostics); case TypeKind.Pointer: return BindPointerElementAccess(node, expr, arguments, diagnostics); case TypeKind.Class: case TypeKind.Struct: case TypeKind.Interface: case TypeKind.TypeParameter: return BindIndexerAccess(node, expr, arguments, diagnostics); case TypeKind.Submission: // script class is synthesized and should not be used as a type of an indexer expression: default: return BadIndexerExpression(node, expr, arguments, null, diagnostics); } } private BoundExpression BindArrayAccess(ExpressionSyntax node, BoundExpression expr, AnalyzedArguments arguments, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); Debug.Assert(expr != null); Debug.Assert(arguments != null); // For an array access, the primary-no-array-creation-expression of the element-access // must be a value of an array-type. Furthermore, the argument-list of an array access // is not allowed to contain named arguments.The number of expressions in the // argument-list must be the same as the rank of the array-type, and each expression // must be of type int, uint, long, ulong, or must be implicitly convertible to one or // more of these types. if (arguments.Names.Count > 0) { Error(diagnostics, ErrorCode.ERR_NamedArgumentForArray, node); } bool hasErrors = ReportRefOrOutArgument(arguments, diagnostics); var arrayType = (ArrayTypeSymbol)expr.Type; // Note that the spec says to determine which of {int, uint, long, ulong} *each* index // expression is convertible to. That is not what C# 1 through 4 did; the // implementations instead determined which of those four types *all* of the index // expressions converted to. int rank = arrayType.Rank; if (arguments.Arguments.Count != rank) { Error(diagnostics, ErrorCode.ERR_BadIndexCount, node, rank); return new BoundArrayAccess(node, expr, BuildArgumentsForErrorRecovery(arguments), arrayType.ElementType, hasErrors: true); } // Convert all the arguments to the array index type. BoundExpression[] convertedArguments = new BoundExpression[arguments.Arguments.Count]; for (int i = 0; i < arguments.Arguments.Count; ++i) { BoundExpression argument = arguments.Arguments[i]; BoundExpression index = ConvertToArrayIndex(argument, diagnostics, allowIndexAndRange: rank == 1); convertedArguments[i] = index; // NOTE: Dev10 only warns if rank == 1 // Question: Why do we limit this warning to one-dimensional arrays? // Answer: Because multidimensional arrays can have nonzero lower bounds in the CLR. if (rank == 1 && !index.HasAnyErrors) { ConstantValue constant = index.ConstantValue; if (constant != null && constant.IsNegativeNumeric) { Error(diagnostics, ErrorCode.WRN_NegativeArrayIndex, index.Syntax); } } } TypeSymbol resultType = rank == 1 && TypeSymbol.Equals( convertedArguments[0].Type, Compilation.GetWellKnownType(WellKnownType.System_Range), TypeCompareKind.ConsiderEverything) ? arrayType : arrayType.ElementType; return hasErrors ? new BoundArrayAccess(node, BindToTypeForErrorRecovery(expr), convertedArguments.Select(e => BindToTypeForErrorRecovery(e)).AsImmutableOrNull(), resultType, hasErrors: true) : new BoundArrayAccess(node, expr, convertedArguments.AsImmutableOrNull(), resultType, hasErrors: false); } private BoundExpression ConvertToArrayIndex(BoundExpression index, BindingDiagnosticBag diagnostics, bool allowIndexAndRange) { Debug.Assert(index != null); if (index.Kind == BoundKind.OutVariablePendingInference) { return ((OutVariablePendingInference)index).FailInference(this, diagnostics); } else if (index.Kind == BoundKind.DiscardExpression && !index.HasExpressionType()) { return ((BoundDiscardExpression)index).FailInference(this, diagnostics); } var node = index.Syntax; var result = TryImplicitConversionToArrayIndex(index, SpecialType.System_Int32, node, diagnostics) ?? TryImplicitConversionToArrayIndex(index, SpecialType.System_UInt32, node, diagnostics) ?? TryImplicitConversionToArrayIndex(index, SpecialType.System_Int64, node, diagnostics) ?? TryImplicitConversionToArrayIndex(index, SpecialType.System_UInt64, node, diagnostics); if (result is null && allowIndexAndRange) { result = TryImplicitConversionToArrayIndex(index, WellKnownType.System_Index, node, diagnostics); if (result is null) { result = TryImplicitConversionToArrayIndex(index, WellKnownType.System_Range, node, diagnostics); if (result is object) { // This member is needed for lowering and should produce an error if not present _ = GetWellKnownTypeMember( WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__GetSubArray_T, diagnostics, syntax: node); } } else { // This member is needed for lowering and should produce an error if not present _ = GetWellKnownTypeMember( WellKnownMember.System_Index__GetOffset, diagnostics, syntax: node); } } if (result is null) { // Give the error that would be given upon conversion to int32. NamedTypeSymbol int32 = GetSpecialType(SpecialType.System_Int32, diagnostics, node); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion failedConversion = this.Conversions.ClassifyConversionFromExpression(index, int32, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); GenerateImplicitConversionError(diagnostics, node, failedConversion, index, int32); // Suppress any additional diagnostics return CreateConversion(node, index, failedConversion, isCast: false, conversionGroupOpt: null, destination: int32, diagnostics: BindingDiagnosticBag.Discarded); } return result; } private BoundExpression TryImplicitConversionToArrayIndex(BoundExpression expr, WellKnownType wellKnownType, SyntaxNode node, BindingDiagnosticBag diagnostics) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); TypeSymbol type = GetWellKnownType(wellKnownType, ref useSiteInfo); if (type.IsErrorType()) { return null; } var attemptDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); var result = TryImplicitConversionToArrayIndex(expr, type, node, attemptDiagnostics); if (result is object) { diagnostics.Add(node, useSiteInfo); diagnostics.AddRange(attemptDiagnostics); } attemptDiagnostics.Free(); return result; } private BoundExpression TryImplicitConversionToArrayIndex(BoundExpression expr, SpecialType specialType, SyntaxNode node, BindingDiagnosticBag diagnostics) { var attemptDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); TypeSymbol type = GetSpecialType(specialType, attemptDiagnostics, node); var result = TryImplicitConversionToArrayIndex(expr, type, node, attemptDiagnostics); if (result is object) { diagnostics.AddRange(attemptDiagnostics); } attemptDiagnostics.Free(); return result; } private BoundExpression TryImplicitConversionToArrayIndex(BoundExpression expr, TypeSymbol targetType, SyntaxNode node, BindingDiagnosticBag diagnostics) { Debug.Assert(expr != null); Debug.Assert((object)targetType != null); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = this.Conversions.ClassifyImplicitConversionFromExpression(expr, targetType, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!conversion.Exists) { return null; } if (conversion.IsDynamic) { conversion = conversion.SetArrayIndexConversionForDynamic(); } BoundExpression result = CreateConversion(expr.Syntax, expr, conversion, isCast: false, conversionGroupOpt: null, destination: targetType, diagnostics); // UNDONE: was cast? Debug.Assert(result != null); // If this ever fails (it shouldn't), then put a null-check around the diagnostics update. return result; } private BoundExpression BindPointerElementAccess(ExpressionSyntax node, BoundExpression expr, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); Debug.Assert(expr != null); Debug.Assert(analyzedArguments != null); bool hasErrors = false; if (analyzedArguments.Names.Count > 0) { // CONSIDER: the error text for this error code mentions "arrays". It might be nice if we had // a separate error code for pointer element access. Error(diagnostics, ErrorCode.ERR_NamedArgumentForArray, node); hasErrors = true; } hasErrors = hasErrors || ReportRefOrOutArgument(analyzedArguments, diagnostics); Debug.Assert(expr.Type.IsPointerType()); PointerTypeSymbol pointerType = (PointerTypeSymbol)expr.Type; TypeSymbol pointedAtType = pointerType.PointedAtType; ArrayBuilder<BoundExpression> arguments = analyzedArguments.Arguments; if (arguments.Count != 1) { if (!hasErrors) { Error(diagnostics, ErrorCode.ERR_PtrIndexSingle, node); } return new BoundPointerElementAccess(node, expr, BadExpression(node, BuildArgumentsForErrorRecovery(analyzedArguments)).MakeCompilerGenerated(), CheckOverflowAtRuntime, pointedAtType, hasErrors: true); } if (pointedAtType.IsVoidType()) { Error(diagnostics, ErrorCode.ERR_VoidError, expr.Syntax); hasErrors = true; } BoundExpression index = arguments[0]; index = ConvertToArrayIndex(index, diagnostics, allowIndexAndRange: false); return new BoundPointerElementAccess(node, expr, index, CheckOverflowAtRuntime, pointedAtType, hasErrors); } private static bool ReportRefOrOutArgument(AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics) { int numArguments = analyzedArguments.Arguments.Count; for (int i = 0; i < numArguments; i++) { RefKind refKind = analyzedArguments.RefKind(i); if (refKind != RefKind.None) { Error(diagnostics, ErrorCode.ERR_BadArgExtraRef, analyzedArguments.Argument(i).Syntax, i + 1, refKind.ToArgumentDisplayString()); return true; } } return false; } private BoundExpression BindIndexerAccess(ExpressionSyntax node, BoundExpression expr, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); Debug.Assert(expr != null); Debug.Assert((object)expr.Type != null); Debug.Assert(analyzedArguments != null); LookupResult lookupResult = LookupResult.GetInstance(); LookupOptions lookupOptions = expr.Kind == BoundKind.BaseReference ? LookupOptions.UseBaseReferenceAccessibility : LookupOptions.Default; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.LookupMembersWithFallback(lookupResult, expr.Type, WellKnownMemberNames.Indexer, arity: 0, useSiteInfo: ref useSiteInfo, options: lookupOptions); diagnostics.Add(node, useSiteInfo); // Store, rather than return, so that we can release resources. BoundExpression indexerAccessExpression; if (!lookupResult.IsMultiViable) { if (TryBindIndexOrRangeIndexer( node, expr, analyzedArguments, diagnostics, out var patternIndexerAccess)) { indexerAccessExpression = patternIndexerAccess; } else { indexerAccessExpression = BadIndexerExpression(node, expr, analyzedArguments, lookupResult.Error, diagnostics); } } else { ArrayBuilder<PropertySymbol> indexerGroup = ArrayBuilder<PropertySymbol>.GetInstance(); foreach (Symbol symbol in lookupResult.Symbols) { Debug.Assert(symbol.IsIndexer()); indexerGroup.Add((PropertySymbol)symbol); } indexerAccessExpression = BindIndexerOrIndexedPropertyAccess(node, expr, indexerGroup, analyzedArguments, diagnostics); indexerGroup.Free(); } lookupResult.Free(); return indexerAccessExpression; } private static readonly Func<PropertySymbol, bool> s_isIndexedPropertyWithNonOptionalArguments = property => { if (property.IsIndexer || !property.IsIndexedProperty) { return false; } Debug.Assert(property.ParameterCount > 0); var parameter = property.Parameters[0]; return !parameter.IsOptional && !parameter.IsParams; }; private static readonly SymbolDisplayFormat s_propertyGroupFormat = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, memberOptions: SymbolDisplayMemberOptions.IncludeContainingType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); private BoundExpression BindIndexedPropertyAccess(BoundPropertyGroup propertyGroup, bool mustHaveAllOptionalParameters, BindingDiagnosticBag diagnostics) { var syntax = propertyGroup.Syntax; var receiverOpt = propertyGroup.ReceiverOpt; var properties = propertyGroup.Properties; if (properties.All(s_isIndexedPropertyWithNonOptionalArguments)) { Error(diagnostics, mustHaveAllOptionalParameters ? ErrorCode.ERR_IndexedPropertyMustHaveAllOptionalParams : ErrorCode.ERR_IndexedPropertyRequiresParams, syntax, properties[0].ToDisplayString(s_propertyGroupFormat)); return BoundIndexerAccess.ErrorAccess( syntax, receiverOpt, CreateErrorPropertySymbol(properties), ImmutableArray<BoundExpression>.Empty, default(ImmutableArray<string>), default(ImmutableArray<RefKind>), properties); } var arguments = AnalyzedArguments.GetInstance(); var result = BindIndexedPropertyAccess(syntax, receiverOpt, properties, arguments, diagnostics); arguments.Free(); return result; } private BoundExpression BindIndexedPropertyAccess(SyntaxNode syntax, BoundExpression receiverOpt, ImmutableArray<PropertySymbol> propertyGroup, AnalyzedArguments arguments, BindingDiagnosticBag diagnostics) { // TODO: We're creating an extra copy of the properties array in BindIndexerOrIndexedProperty // converting the ArrayBuilder to ImmutableArray. Avoid the extra copy. var properties = ArrayBuilder<PropertySymbol>.GetInstance(); properties.AddRange(propertyGroup); var result = BindIndexerOrIndexedPropertyAccess(syntax, receiverOpt, properties, arguments, diagnostics); properties.Free(); return result; } private BoundExpression BindDynamicIndexer( SyntaxNode syntax, BoundExpression receiver, AnalyzedArguments arguments, ImmutableArray<PropertySymbol> applicableProperties, BindingDiagnosticBag diagnostics) { bool hasErrors = false; BoundKind receiverKind = receiver.Kind; if (receiverKind == BoundKind.BaseReference) { Error(diagnostics, ErrorCode.ERR_NoDynamicPhantomOnBaseIndexer, syntax); hasErrors = true; } else if (receiverKind == BoundKind.TypeOrValueExpression) { var typeOrValue = (BoundTypeOrValueExpression)receiver; // Unfortunately, the runtime binder doesn't have APIs that would allow us to pass both "type or value". // Ideally the runtime binder would choose between type and value based on the result of the overload resolution. // We need to pick one or the other here. Dev11 compiler passes the type only if the value can't be accessed. bool inStaticContext; bool useType = IsInstance(typeOrValue.Data.ValueSymbol) && !HasThis(isExplicit: false, inStaticContext: out inStaticContext); receiver = ReplaceTypeOrValueReceiver(typeOrValue, useType, diagnostics); } var argArray = BuildArgumentsForDynamicInvocation(arguments, diagnostics); var refKindsArray = arguments.RefKinds.ToImmutableOrNull(); hasErrors &= ReportBadDynamicArguments(syntax, argArray, refKindsArray, diagnostics, queryClause: null); return new BoundDynamicIndexerAccess( syntax, receiver, argArray, arguments.GetNames(), refKindsArray, applicableProperties, AssemblySymbol.DynamicType, hasErrors); } private BoundExpression BindIndexerOrIndexedPropertyAccess( SyntaxNode syntax, BoundExpression receiverOpt, ArrayBuilder<PropertySymbol> propertyGroup, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics) { OverloadResolutionResult<PropertySymbol> overloadResolutionResult = OverloadResolutionResult<PropertySymbol>.GetInstance(); bool allowRefOmittedArguments = receiverOpt.IsExpressionOfComImportType(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); this.OverloadResolution.PropertyOverloadResolution(propertyGroup, receiverOpt, analyzedArguments, overloadResolutionResult, allowRefOmittedArguments, ref useSiteInfo); diagnostics.Add(syntax, useSiteInfo); BoundExpression propertyAccess; if (analyzedArguments.HasDynamicArgument && overloadResolutionResult.HasAnyApplicableMember) { // Note that the runtime binder may consider candidates that haven't passed compile-time final validation // and an ambiguity error may be reported. Also additional checks are performed in runtime final validation // that are not performed at compile-time. // Only if the set of final applicable candidates is empty we know for sure the call will fail at runtime. var finalApplicableCandidates = GetCandidatesPassingFinalValidation(syntax, overloadResolutionResult, receiverOpt, default(ImmutableArray<TypeWithAnnotations>), diagnostics); overloadResolutionResult.Free(); return BindDynamicIndexer(syntax, receiverOpt, analyzedArguments, finalApplicableCandidates, diagnostics); } ImmutableArray<string> argumentNames = analyzedArguments.GetNames(); ImmutableArray<RefKind> argumentRefKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); if (!overloadResolutionResult.Succeeded) { // If the arguments had an error reported about them then suppress further error // reporting for overload resolution. ImmutableArray<PropertySymbol> candidates = propertyGroup.ToImmutable(); if (!analyzedArguments.HasErrors) { if (TryBindIndexOrRangeIndexer( syntax, receiverOpt, analyzedArguments, diagnostics, out var patternIndexerAccess)) { return patternIndexerAccess; } else { // Dev10 uses the "this" keyword as the method name for indexers. var candidate = candidates[0]; var name = candidate.IsIndexer ? SyntaxFacts.GetText(SyntaxKind.ThisKeyword) : candidate.Name; overloadResolutionResult.ReportDiagnostics( binder: this, location: syntax.Location, nodeOpt: syntax, diagnostics: diagnostics, name: name, receiver: null, invokedExpression: null, arguments: analyzedArguments, memberGroup: candidates, typeContainingConstructor: null, delegateTypeBeingInvoked: null); } } ImmutableArray<BoundExpression> arguments = BuildArgumentsForErrorRecovery(analyzedArguments, candidates); // A bad BoundIndexerAccess containing an ErrorPropertySymbol will produce better flow analysis results than // a BoundBadExpression containing the candidate indexers. PropertySymbol property = (candidates.Length == 1) ? candidates[0] : CreateErrorPropertySymbol(candidates); propertyAccess = BoundIndexerAccess.ErrorAccess( syntax, receiverOpt, property, arguments, argumentNames, argumentRefKinds, candidates); } else { MemberResolutionResult<PropertySymbol> resolutionResult = overloadResolutionResult.ValidResult; PropertySymbol property = resolutionResult.Member; RefKind? receiverRefKind = receiverOpt?.GetRefKind(); uint receiverEscapeScope = property.RequiresInstanceReceiver && receiverOpt != null ? receiverRefKind?.IsWritableReference() == true ? GetRefEscape(receiverOpt, LocalScopeDepth) : GetValEscape(receiverOpt, LocalScopeDepth) : Binder.ExternalScope; this.CoerceArguments<PropertySymbol>(resolutionResult, analyzedArguments.Arguments, diagnostics, receiverOpt?.Type, receiverRefKind, receiverEscapeScope); var isExpanded = resolutionResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm; var argsToParams = resolutionResult.Result.ArgsToParamsOpt; ReportDiagnosticsIfObsolete(diagnostics, property, syntax, hasBaseReceiver: receiverOpt != null && receiverOpt.Kind == BoundKind.BaseReference); // Make sure that the result of overload resolution is valid. var gotError = MemberGroupFinalValidationAccessibilityChecks(receiverOpt, property, syntax, diagnostics, invokedAsExtensionMethod: false); var receiver = ReplaceTypeOrValueReceiver(receiverOpt, property.IsStatic, diagnostics); if (!gotError && receiver != null && receiver.Kind == BoundKind.ThisReference && receiver.WasCompilerGenerated) { gotError = IsRefOrOutThisParameterCaptured(syntax, diagnostics); } var arguments = analyzedArguments.Arguments.ToImmutable(); if (!gotError) { gotError = !CheckInvocationArgMixing( syntax, property, receiver, property.Parameters, arguments, argsToParams, this.LocalScopeDepth, diagnostics); } // Note that we do not bind default arguments here, because at this point we do not know whether // the indexer is being used in a 'get', or 'set', or 'get+set' (compound assignment) context. propertyAccess = new BoundIndexerAccess( syntax, receiver, property, arguments, argumentNames, argumentRefKinds, isExpanded, argsToParams, defaultArguments: default, property.Type, gotError); } overloadResolutionResult.Free(); return propertyAccess; } private bool TryBindIndexOrRangeIndexer( SyntaxNode syntax, BoundExpression receiverOpt, AnalyzedArguments arguments, BindingDiagnosticBag diagnostics, out BoundIndexOrRangePatternIndexerAccess patternIndexerAccess) { patternIndexerAccess = null; // Verify a few things up-front, namely that we have a single argument // to this indexer that has an Index or Range type and that there is // a real receiver with a known type if (arguments.Arguments.Count != 1) { return false; } var argument = arguments.Arguments[0]; var argType = argument.Type; bool argIsIndex = TypeSymbol.Equals(argType, Compilation.GetWellKnownType(WellKnownType.System_Index), TypeCompareKind.ConsiderEverything); bool argIsRange = !argIsIndex && TypeSymbol.Equals(argType, Compilation.GetWellKnownType(WellKnownType.System_Range), TypeCompareKind.ConsiderEverything); if ((!argIsIndex && !argIsRange) || !(receiverOpt?.Type is TypeSymbol receiverType)) { return false; } // SPEC: // An indexer invocation with a single argument of System.Index or System.Range will // succeed if the receiver type conforms to an appropriate pattern, namely // 1. The receiver type's original definition has an accessible property getter that returns // an int and has the name Length or Count // 2. For Index: Has an accessible indexer with a single int parameter // For Range: Has an accessible Slice method that takes two int parameters PropertySymbol lengthOrCountProperty; var lookupResult = LookupResult.GetInstance(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; // Look for Length first if (!tryLookupLengthOrCount(WellKnownMemberNames.LengthPropertyName, out lengthOrCountProperty) && !tryLookupLengthOrCount(WellKnownMemberNames.CountPropertyName, out lengthOrCountProperty)) { return false; } Debug.Assert(lengthOrCountProperty is { }); if (argIsIndex) { // Look for `T this[int i]` indexer LookupMembersInType( lookupResult, receiverType, WellKnownMemberNames.Indexer, arity: 0, basesBeingResolved: null, LookupOptions.Default, originalBinder: this, diagnose: false, ref discardedUseSiteInfo); if (lookupResult.IsMultiViable) { foreach (var candidate in lookupResult.Symbols) { if (!candidate.IsStatic && candidate is PropertySymbol property && IsAccessible(property, ref discardedUseSiteInfo) && property.OriginalDefinition is { ParameterCount: 1 } original && isIntNotByRef(original.Parameters[0])) { CheckImplicitThisCopyInReadOnlyMember(receiverOpt, lengthOrCountProperty.GetMethod, diagnostics); ReportDiagnosticsIfObsolete(diagnostics, property, syntax, hasBaseReceiver: false); ReportDiagnosticsIfObsolete(diagnostics, lengthOrCountProperty, syntax, hasBaseReceiver: false); // note: implicit copy check on the indexer accessor happens in CheckPropertyValueKind patternIndexerAccess = new BoundIndexOrRangePatternIndexerAccess( syntax, receiverOpt, lengthOrCountProperty, property, BindToNaturalType(argument, diagnostics), property.Type); break; } } } } else if (receiverType.SpecialType == SpecialType.System_String) { Debug.Assert(argIsRange); // Look for Substring var substring = (MethodSymbol)Compilation.GetSpecialTypeMember(SpecialMember.System_String__Substring); if (substring is object) { patternIndexerAccess = new BoundIndexOrRangePatternIndexerAccess( syntax, receiverOpt, lengthOrCountProperty, substring, BindToNaturalType(argument, diagnostics), substring.ReturnType); checkWellKnown(WellKnownMember.System_Range__get_Start); checkWellKnown(WellKnownMember.System_Range__get_End); } } else { Debug.Assert(argIsRange); // Look for `T Slice(int, int)` indexer LookupMembersInType( lookupResult, receiverType, WellKnownMemberNames.SliceMethodName, arity: 0, basesBeingResolved: null, LookupOptions.Default, originalBinder: this, diagnose: false, ref discardedUseSiteInfo); if (lookupResult.IsMultiViable) { foreach (var candidate in lookupResult.Symbols) { if (!candidate.IsStatic && IsAccessible(candidate, ref discardedUseSiteInfo) && candidate is MethodSymbol method && method.OriginalDefinition is var original && original.ParameterCount == 2 && isIntNotByRef(original.Parameters[0]) && isIntNotByRef(original.Parameters[1])) { CheckImplicitThisCopyInReadOnlyMember(receiverOpt, lengthOrCountProperty.GetMethod, diagnostics); CheckImplicitThisCopyInReadOnlyMember(receiverOpt, method, diagnostics); ReportDiagnosticsIfObsolete(diagnostics, method, syntax, hasBaseReceiver: false); ReportDiagnosticsIfObsolete(diagnostics, lengthOrCountProperty, syntax, hasBaseReceiver: false); patternIndexerAccess = new BoundIndexOrRangePatternIndexerAccess( syntax, receiverOpt, lengthOrCountProperty, method, BindToNaturalType(argument, diagnostics), method.ReturnType); checkWellKnown(WellKnownMember.System_Range__get_Start); checkWellKnown(WellKnownMember.System_Range__get_End); break; } } } } cleanup(lookupResult); if (patternIndexerAccess is null) { return false; } _ = MessageID.IDS_FeatureIndexOperator.CheckFeatureAvailability(diagnostics, syntax); checkWellKnown(WellKnownMember.System_Index__GetOffset); if (arguments.Names.Count > 0) { diagnostics.Add( argIsRange ? ErrorCode.ERR_ImplicitRangeIndexerWithName : ErrorCode.ERR_ImplicitIndexIndexerWithName, arguments.Names[0].GetValueOrDefault().Location); } return true; static void cleanup(LookupResult lookupResult) { lookupResult.Free(); } static bool isIntNotByRef(ParameterSymbol param) => param.Type.SpecialType == SpecialType.System_Int32 && param.RefKind == RefKind.None; void checkWellKnown(WellKnownMember member) { // Check required well-known member. They may not be needed // during lowering, but it's simpler to always require them to prevent // the user from getting surprising errors when optimizations fail _ = GetWellKnownTypeMember(member, diagnostics, syntax: syntax); } bool tryLookupLengthOrCount(string propertyName, out PropertySymbol valid) { LookupMembersInType( lookupResult, receiverType, propertyName, arity: 0, basesBeingResolved: null, LookupOptions.Default, originalBinder: this, diagnose: false, useSiteInfo: ref discardedUseSiteInfo); if (lookupResult.IsSingleViable && lookupResult.Symbols[0] is PropertySymbol property && property.GetOwnOrInheritedGetMethod()?.OriginalDefinition is MethodSymbol getMethod && getMethod.ReturnType.SpecialType == SpecialType.System_Int32 && getMethod.RefKind == RefKind.None && !getMethod.IsStatic && IsAccessible(getMethod, ref discardedUseSiteInfo)) { lookupResult.Clear(); valid = property; return true; } lookupResult.Clear(); valid = null; return false; } } private ErrorPropertySymbol CreateErrorPropertySymbol(ImmutableArray<PropertySymbol> propertyGroup) { TypeSymbol propertyType = GetCommonTypeOrReturnType(propertyGroup) ?? CreateErrorType(); var candidate = propertyGroup[0]; return new ErrorPropertySymbol(candidate.ContainingType, propertyType, candidate.Name, candidate.IsIndexer, candidate.IsIndexedProperty); } /// <summary> /// Perform lookup and overload resolution on methods defined directly on the class and any /// extension methods in scope. Lookup will occur for extension methods in all nested scopes /// as necessary until an appropriate method is found. If analyzedArguments is null, the first /// method group is returned, without overload resolution being performed. That method group /// will either be the methods defined on the receiver class directly (no extension methods) /// or the first set of extension methods. /// </summary> /// <param name="node">The node associated with the method group</param> /// <param name="analyzedArguments">The arguments of the invocation (or the delegate type, if a method group conversion)</param> /// <param name="isMethodGroupConversion">True if it is a method group conversion</param> /// <param name="useSiteInfo"></param> /// <param name="inferWithDynamic"></param> /// <param name="returnRefKind">If a method group conversion, the desired ref kind of the delegate</param> /// <param name="returnType">If a method group conversion, the desired return type of the delegate. /// May be null during inference if the return type of the delegate needs to be computed.</param> internal MethodGroupResolution ResolveMethodGroup( BoundMethodGroup node, AnalyzedArguments analyzedArguments, bool isMethodGroupConversion, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool inferWithDynamic = false, RefKind returnRefKind = default, TypeSymbol returnType = null, bool isFunctionPointerResolution = false, in CallingConventionInfo callingConventionInfo = default) { return ResolveMethodGroup( node, node.Syntax, node.Name, analyzedArguments, isMethodGroupConversion, ref useSiteInfo, inferWithDynamic: inferWithDynamic, returnRefKind: returnRefKind, returnType: returnType, isFunctionPointerResolution: isFunctionPointerResolution, callingConventionInfo: callingConventionInfo); } internal MethodGroupResolution ResolveMethodGroup( BoundMethodGroup node, SyntaxNode expression, string methodName, AnalyzedArguments analyzedArguments, bool isMethodGroupConversion, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool inferWithDynamic = false, bool allowUnexpandedForm = true, RefKind returnRefKind = default, TypeSymbol returnType = null, bool isFunctionPointerResolution = false, in CallingConventionInfo callingConventionInfo = default) { var methodResolution = ResolveMethodGroupInternal( node, expression, methodName, analyzedArguments, isMethodGroupConversion, ref useSiteInfo, inferWithDynamic: inferWithDynamic, allowUnexpandedForm: allowUnexpandedForm, returnRefKind: returnRefKind, returnType: returnType, isFunctionPointerResolution: isFunctionPointerResolution, callingConvention: callingConventionInfo); if (methodResolution.IsEmpty && !methodResolution.HasAnyErrors) { Debug.Assert(node.LookupError == null); var diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, useSiteInfo.AccumulatesDependencies); diagnostics.AddRange(methodResolution.Diagnostics); // Could still have use site warnings. BindMemberAccessReportError(node, diagnostics); // Note: no need to free `methodResolution`, we're transferring the pooled objects it owned return new MethodGroupResolution(methodResolution.MethodGroup, methodResolution.OtherSymbol, methodResolution.OverloadResolutionResult, methodResolution.AnalyzedArguments, methodResolution.ResultKind, diagnostics.ToReadOnlyAndFree()); } return methodResolution; } internal MethodGroupResolution ResolveMethodGroupForFunctionPointer( BoundMethodGroup methodGroup, AnalyzedArguments analyzedArguments, TypeSymbol returnType, RefKind returnRefKind, in CallingConventionInfo callingConventionInfo, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ResolveDefaultMethodGroup( methodGroup, analyzedArguments, isMethodGroupConversion: true, ref useSiteInfo, inferWithDynamic: false, allowUnexpandedForm: true, returnRefKind, returnType, isFunctionPointerResolution: true, callingConventionInfo); } private MethodGroupResolution ResolveMethodGroupInternal( BoundMethodGroup methodGroup, SyntaxNode expression, string methodName, AnalyzedArguments analyzedArguments, bool isMethodGroupConversion, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool inferWithDynamic = false, bool allowUnexpandedForm = true, RefKind returnRefKind = default, TypeSymbol returnType = null, bool isFunctionPointerResolution = false, in CallingConventionInfo callingConvention = default) { var methodResolution = ResolveDefaultMethodGroup( methodGroup, analyzedArguments, isMethodGroupConversion, ref useSiteInfo, inferWithDynamic, allowUnexpandedForm, returnRefKind, returnType, isFunctionPointerResolution, callingConvention); // If the method group's receiver is dynamic then there is no point in looking for extension methods; // it's going to be a dynamic invocation. if (!methodGroup.SearchExtensionMethods || methodResolution.HasAnyApplicableMethod || methodGroup.MethodGroupReceiverIsDynamic()) { return methodResolution; } var extensionMethodResolution = BindExtensionMethod( expression, methodName, analyzedArguments, methodGroup.ReceiverOpt, methodGroup.TypeArgumentsOpt, isMethodGroupConversion, returnRefKind: returnRefKind, returnType: returnType, withDependencies: useSiteInfo.AccumulatesDependencies); bool preferExtensionMethodResolution = false; if (extensionMethodResolution.HasAnyApplicableMethod) { preferExtensionMethodResolution = true; } else if (extensionMethodResolution.IsEmpty) { preferExtensionMethodResolution = false; } else if (methodResolution.IsEmpty) { preferExtensionMethodResolution = true; } else { // At this point, both method group resolutions are non-empty but neither contains any applicable method. // Choose the MethodGroupResolution with the better (i.e. less worse) result kind. Debug.Assert(!methodResolution.HasAnyApplicableMethod); Debug.Assert(!extensionMethodResolution.HasAnyApplicableMethod); Debug.Assert(!methodResolution.IsEmpty); Debug.Assert(!extensionMethodResolution.IsEmpty); LookupResultKind methodResultKind = methodResolution.ResultKind; LookupResultKind extensionMethodResultKind = extensionMethodResolution.ResultKind; if (methodResultKind != extensionMethodResultKind && methodResultKind == extensionMethodResultKind.WorseResultKind(methodResultKind)) { preferExtensionMethodResolution = true; } } if (preferExtensionMethodResolution) { methodResolution.Free(); Debug.Assert(!extensionMethodResolution.IsEmpty); return extensionMethodResolution; //NOTE: the first argument of this MethodGroupResolution could be a BoundTypeOrValueExpression } extensionMethodResolution.Free(); return methodResolution; } private MethodGroupResolution ResolveDefaultMethodGroup( BoundMethodGroup node, AnalyzedArguments analyzedArguments, bool isMethodGroupConversion, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool inferWithDynamic = false, bool allowUnexpandedForm = true, RefKind returnRefKind = default, TypeSymbol returnType = null, bool isFunctionPointerResolution = false, in CallingConventionInfo callingConvention = default) { var methods = node.Methods; if (methods.Length == 0) { var method = node.LookupSymbolOpt as MethodSymbol; if ((object)method != null) { methods = ImmutableArray.Create(method); } } var sealedDiagnostics = ImmutableBindingDiagnostic<AssemblySymbol>.Empty; if (node.LookupError != null) { var diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false); Error(diagnostics, node.LookupError, node.NameSyntax); sealedDiagnostics = diagnostics.ToReadOnlyAndFree(); } if (methods.Length == 0) { return new MethodGroupResolution(node.LookupSymbolOpt, node.ResultKind, sealedDiagnostics); } var methodGroup = MethodGroup.GetInstance(); // NOTE: node.ReceiverOpt could be a BoundTypeOrValueExpression - users need to check. methodGroup.PopulateWithNonExtensionMethods(node.ReceiverOpt, methods, node.TypeArgumentsOpt, node.ResultKind, node.LookupError); if (node.LookupError != null) { return new MethodGroupResolution(methodGroup, sealedDiagnostics); } // Arguments will be null if the caller is resolving to the first available // method group, regardless of arguments, when the signature cannot // be inferred. (In the error case of o.M = null; for instance.) if (analyzedArguments == null) { return new MethodGroupResolution(methodGroup, sealedDiagnostics); } else { var result = OverloadResolutionResult<MethodSymbol>.GetInstance(); bool allowRefOmittedArguments = methodGroup.Receiver.IsExpressionOfComImportType(); OverloadResolution.MethodInvocationOverloadResolution( methodGroup.Methods, methodGroup.TypeArguments, methodGroup.Receiver, analyzedArguments, result, ref useSiteInfo, isMethodGroupConversion, allowRefOmittedArguments, inferWithDynamic, allowUnexpandedForm, returnRefKind, returnType, isFunctionPointerResolution, callingConvention); // Note: the MethodGroupResolution instance is responsible for freeing its copy of analyzed arguments return new MethodGroupResolution(methodGroup, null, result, AnalyzedArguments.GetInstance(analyzedArguments), methodGroup.ResultKind, sealedDiagnostics); } } #nullable enable internal NamedTypeSymbol? GetMethodGroupDelegateType(BoundMethodGroup node, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (GetUniqueSignatureFromMethodGroup(node) is { } method && GetMethodGroupOrLambdaDelegateType(method.RefKind, method.ReturnsVoid ? default : method.ReturnTypeWithAnnotations, method.ParameterRefKinds, method.ParameterTypesWithAnnotations, ref useSiteInfo) is { } delegateType) { return delegateType; } return null; } /// <summary> /// Returns one of the methods from the method group if all methods in the method group /// have the same signature, ignoring parameter names and custom modifiers. The particular /// method returned is not important since the caller is interested in the signature only. /// </summary> private MethodSymbol? GetUniqueSignatureFromMethodGroup(BoundMethodGroup node) { MethodSymbol? method = null; foreach (var m in node.Methods) { switch (node.ReceiverOpt) { case BoundTypeExpression: if (!m.IsStatic) continue; break; case BoundThisReference { WasCompilerGenerated: true }: break; default: if (m.IsStatic) continue; break; } if (!isCandidateUnique(ref method, m)) { return null; } } if (node.SearchExtensionMethods) { var receiver = node.ReceiverOpt!; foreach (var scope in new ExtensionMethodScopes(this)) { var methodGroup = MethodGroup.GetInstance(); PopulateExtensionMethodsFromSingleBinder(scope, methodGroup, node.Syntax, receiver, node.Name, node.TypeArgumentsOpt, BindingDiagnosticBag.Discarded); foreach (var m in methodGroup.Methods) { if (m.ReduceExtensionMethod(receiver.Type, Compilation) is { } reduced && !isCandidateUnique(ref method, reduced)) { methodGroup.Free(); return null; } } methodGroup.Free(); } } if (method is null) { return null; } int n = node.TypeArgumentsOpt.IsDefaultOrEmpty ? 0 : node.TypeArgumentsOpt.Length; if (method.Arity != n) { return null; } else if (n > 0) { method = method.ConstructedFrom.Construct(node.TypeArgumentsOpt); } return method; static bool isCandidateUnique(ref MethodSymbol? method, MethodSymbol candidate) { if (method is null) { method = candidate; return true; } if (MemberSignatureComparer.MethodGroupSignatureComparer.Equals(method, candidate)) { return true; } method = null; return false; } } // This method was adapted from LoweredDynamicOperationFactory.GetDelegateType(). // Consider using that method directly since it also synthesizes delegates if necessary. internal NamedTypeSymbol? GetMethodGroupOrLambdaDelegateType( RefKind returnRefKind, TypeWithAnnotations returnTypeOpt, ImmutableArray<RefKind> parameterRefKinds, ImmutableArray<TypeWithAnnotations> parameterTypes, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(returnTypeOpt.Type?.IsVoidType() != true); // expecting !returnTypeOpt.HasType rather than System.Void if (returnRefKind == RefKind.None && (parameterRefKinds.IsDefault || parameterRefKinds.All(refKind => refKind == RefKind.None))) { var wkDelegateType = returnTypeOpt.HasType ? WellKnownTypes.GetWellKnownFunctionDelegate(invokeArgumentCount: parameterTypes.Length) : WellKnownTypes.GetWellKnownActionDelegate(invokeArgumentCount: parameterTypes.Length); if (wkDelegateType != WellKnownType.Unknown) { var delegateType = Compilation.GetWellKnownType(wkDelegateType); delegateType.AddUseSiteInfo(ref useSiteInfo); if (returnTypeOpt.HasType) { parameterTypes = parameterTypes.Add(returnTypeOpt); } if (parameterTypes.Length == 0) { return delegateType; } if (checkConstraints(Compilation, Conversions, delegateType, parameterTypes)) { return delegateType.Construct(parameterTypes); } } } return null; static bool checkConstraints(CSharpCompilation compilation, ConversionsBase conversions, NamedTypeSymbol delegateType, ImmutableArray<TypeWithAnnotations> typeArguments) { var diagnosticsBuilder = ArrayBuilder<TypeParameterDiagnosticInfo>.GetInstance(); var typeParameters = delegateType.TypeParameters; var substitution = new TypeMap(typeParameters, typeArguments); ArrayBuilder<TypeParameterDiagnosticInfo>? useSiteDiagnosticsBuilder = null; var result = delegateType.CheckConstraints( new ConstraintsHelper.CheckConstraintsArgs(compilation, conversions, includeNullability: false, NoLocation.Singleton, diagnostics: null, template: CompoundUseSiteInfo<AssemblySymbol>.Discarded), substitution, typeParameters, typeArguments, diagnosticsBuilder, nullabilityDiagnosticsBuilderOpt: null, ref useSiteDiagnosticsBuilder); diagnosticsBuilder.Free(); return result; } } #nullable disable internal static bool ReportDelegateInvokeUseSiteDiagnostic(BindingDiagnosticBag diagnostics, TypeSymbol possibleDelegateType, Location location = null, SyntaxNode node = null) { Debug.Assert((location == null) ^ (node == null)); if (!possibleDelegateType.IsDelegateType()) { return false; } MethodSymbol invoke = possibleDelegateType.DelegateInvokeMethod(); if ((object)invoke == null) { diagnostics.Add(new CSDiagnosticInfo(ErrorCode.ERR_InvalidDelegateType, possibleDelegateType), location ?? node.Location); return true; } UseSiteInfo<AssemblySymbol> info = invoke.GetUseSiteInfo(); diagnostics.AddDependencies(info); DiagnosticInfo diagnosticInfo = info.DiagnosticInfo; if (diagnosticInfo == null) { return false; } if (location == null) { location = node.Location; } if (diagnosticInfo.Code == (int)ErrorCode.ERR_InvalidDelegateType) { diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_InvalidDelegateType, possibleDelegateType), location)); return true; } return Symbol.ReportUseSiteDiagnostic(diagnosticInfo, diagnostics, location); } private BoundConditionalAccess BindConditionalAccessExpression(ConditionalAccessExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression receiver = BindConditionalAccessReceiver(node, diagnostics); var conditionalAccessBinder = new BinderWithConditionalReceiver(this, receiver); var access = conditionalAccessBinder.BindValue(node.WhenNotNull, diagnostics, BindValueKind.RValue); if (receiver.HasAnyErrors || access.HasAnyErrors) { return new BoundConditionalAccess(node, receiver, access, CreateErrorType(), hasErrors: true); } var receiverType = receiver.Type; Debug.Assert((object)receiverType != null); // access cannot be a method group if (access.Kind == BoundKind.MethodGroup) { return GenerateBadConditionalAccessNodeError(node, receiver, access, diagnostics); } var accessType = access.Type; // access cannot have no type if ((object)accessType == null) { return GenerateBadConditionalAccessNodeError(node, receiver, access, diagnostics); } // The resulting type must be either a reference type T or Nullable<T> // Therefore we must reject cases resulting in types that are not reference types and cannot be lifted into nullable. // - access cannot have unconstrained generic type // - access cannot be a pointer // - access cannot be a restricted type if ((!accessType.IsReferenceType && !accessType.IsValueType) || accessType.IsPointerOrFunctionPointer() || accessType.IsRestrictedType()) { // Result type of the access is void when result value cannot be made nullable. // For improved diagnostics we detect the cases where the value will be used and produce a // more specific (though not technically correct) diagnostic here: // "Error CS0023: Operator '?' cannot be applied to operand of type 'T'" bool resultIsUsed = true; CSharpSyntaxNode parent = node.Parent; if (parent != null) { switch (parent.Kind()) { case SyntaxKind.ExpressionStatement: resultIsUsed = ((ExpressionStatementSyntax)parent).Expression != node; break; case SyntaxKind.SimpleLambdaExpression: resultIsUsed = (((SimpleLambdaExpressionSyntax)parent).Body != node) || MethodOrLambdaRequiresValue(ContainingMemberOrLambda, Compilation); break; case SyntaxKind.ParenthesizedLambdaExpression: resultIsUsed = (((ParenthesizedLambdaExpressionSyntax)parent).Body != node) || MethodOrLambdaRequiresValue(ContainingMemberOrLambda, Compilation); break; case SyntaxKind.ArrowExpressionClause: resultIsUsed = (((ArrowExpressionClauseSyntax)parent).Expression != node) || MethodOrLambdaRequiresValue(ContainingMemberOrLambda, Compilation); break; case SyntaxKind.ForStatement: // Incrementors and Initializers doesn't have to produce a value var loop = (ForStatementSyntax)parent; resultIsUsed = !loop.Incrementors.Contains(node) && !loop.Initializers.Contains(node); break; } } if (resultIsUsed) { return GenerateBadConditionalAccessNodeError(node, receiver, access, diagnostics); } accessType = GetSpecialType(SpecialType.System_Void, diagnostics, node); } // if access has value type, the type of the conditional access is nullable of that // https://github.com/dotnet/roslyn/issues/35075: The test `accessType.IsValueType && !accessType.IsNullableType()` // should probably be `accessType.IsNonNullableValueType()` if (accessType.IsValueType && !accessType.IsNullableType() && !accessType.IsVoidType()) { accessType = GetSpecialType(SpecialType.System_Nullable_T, diagnostics, node).Construct(accessType); } return new BoundConditionalAccess(node, receiver, access, accessType); } internal static bool MethodOrLambdaRequiresValue(Symbol symbol, CSharpCompilation compilation) { return symbol is MethodSymbol method && !method.ReturnsVoid && !method.IsAsyncEffectivelyReturningTask(compilation); } private BoundConditionalAccess GenerateBadConditionalAccessNodeError(ConditionalAccessExpressionSyntax node, BoundExpression receiver, BoundExpression access, BindingDiagnosticBag diagnostics) { var operatorToken = node.OperatorToken; // TODO: need a special ERR for this. // conditional access is not really a binary operator. DiagnosticInfo diagnosticInfo = new CSDiagnosticInfo(ErrorCode.ERR_BadUnaryOp, SyntaxFacts.GetText(operatorToken.Kind()), access.Display); diagnostics.Add(new CSDiagnostic(diagnosticInfo, operatorToken.GetLocation())); receiver = BadExpression(receiver.Syntax, receiver); return new BoundConditionalAccess(node, receiver, access, CreateErrorType(), hasErrors: true); } private BoundExpression BindMemberBindingExpression(MemberBindingExpressionSyntax node, bool invoked, bool indexed, BindingDiagnosticBag diagnostics) { BoundExpression receiver = GetReceiverForConditionalBinding(node, diagnostics); var memberAccess = BindMemberAccessWithBoundLeft(node, receiver, node.Name, node.OperatorToken, invoked, indexed, diagnostics); return memberAccess; } private BoundExpression BindElementBindingExpression(ElementBindingExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression receiver = GetReceiverForConditionalBinding(node, diagnostics); var memberAccess = BindElementAccess(node, receiver, node.ArgumentList, diagnostics); return memberAccess; } private static CSharpSyntaxNode GetConditionalReceiverSyntax(ConditionalAccessExpressionSyntax node) { Debug.Assert(node != null); Debug.Assert(node.Expression != null); var receiver = node.Expression; while (receiver.IsKind(SyntaxKind.ParenthesizedExpression)) { receiver = ((ParenthesizedExpressionSyntax)receiver).Expression; Debug.Assert(receiver != null); } return receiver; } private BoundExpression GetReceiverForConditionalBinding(ExpressionSyntax binding, BindingDiagnosticBag diagnostics) { var conditionalAccessNode = SyntaxFactory.FindConditionalAccessNodeForBinding(binding); Debug.Assert(conditionalAccessNode != null); BoundExpression receiver = this.ConditionalReceiverExpression; if (receiver?.Syntax != GetConditionalReceiverSyntax(conditionalAccessNode)) { // this can happen when semantic model binds parts of a Call or a broken access expression. // We may not have receiver available in such cases. // Not a problem - we only need receiver to get its type and we can bind it here. receiver = BindConditionalAccessReceiver(conditionalAccessNode, diagnostics); } // create surrogate receiver var receiverType = receiver.Type; if (receiverType?.IsNullableType() == true) { receiverType = receiverType.GetNullableUnderlyingType(); } receiver = new BoundConditionalReceiver(receiver.Syntax, 0, receiverType ?? CreateErrorType(), hasErrors: receiver.HasErrors) { WasCompilerGenerated = true }; return receiver; } private BoundExpression BindConditionalAccessReceiver(ConditionalAccessExpressionSyntax node, BindingDiagnosticBag diagnostics) { var receiverSyntax = node.Expression; var receiver = BindRValueWithoutTargetType(receiverSyntax, diagnostics); receiver = MakeMemberAccessValue(receiver, diagnostics); if (receiver.HasAnyErrors) { return receiver; } var operatorToken = node.OperatorToken; if (receiver.Kind == BoundKind.UnboundLambda) { var msgId = ((UnboundLambda)receiver).MessageID; DiagnosticInfo diagnosticInfo = new CSDiagnosticInfo(ErrorCode.ERR_BadUnaryOp, SyntaxFacts.GetText(operatorToken.Kind()), msgId.Localize()); diagnostics.Add(new CSDiagnostic(diagnosticInfo, node.Location)); return BadExpression(receiverSyntax, receiver); } var receiverType = receiver.Type; // Can't dot into the null literal or anything that has no type if ((object)receiverType == null) { Error(diagnostics, ErrorCode.ERR_BadUnaryOp, operatorToken.GetLocation(), operatorToken.Text, receiver.Display); return BadExpression(receiverSyntax, receiver); } // No member accesses on void if (receiverType.IsVoidType()) { Error(diagnostics, ErrorCode.ERR_BadUnaryOp, operatorToken.GetLocation(), operatorToken.Text, receiverType); return BadExpression(receiverSyntax, receiver); } if (receiverType.IsValueType && !receiverType.IsNullableType()) { // must be nullable or reference type Error(diagnostics, ErrorCode.ERR_BadUnaryOp, operatorToken.GetLocation(), operatorToken.Text, receiverType); return BadExpression(receiverSyntax, receiver); } return receiver; } } }
1
dotnet/roslyn
55,125
Don't use DefaultInterpolatedStringHandler in expression trees
Introduces a binder flag to track whether we are currently in an expression tree or not. Fixes https://github.com/dotnet/roslyn/issues/55114.
333fred
2021-07-26T22:08:39Z
2021-07-27T19:33:24Z
5840335153dcca42570a853cdacd06d660fe9596
cfc12ce93ce377c4b9581ccf88403e6740d63977
Don't use DefaultInterpolatedStringHandler in expression trees. Introduces a binder flag to track whether we are currently in an expression tree or not. Fixes https://github.com/dotnet/roslyn/issues/55114.
./src/Compilers/CSharp/Portable/Binder/Binder_InterpolatedString.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; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class Binder { private BoundExpression BindInterpolatedString(InterpolatedStringExpressionSyntax node, BindingDiagnosticBag diagnostics) { var builder = ArrayBuilder<BoundExpression>.GetInstance(); var stringType = GetSpecialType(SpecialType.System_String, diagnostics, node); ConstantValue? resultConstant = null; bool isResultConstant = true; if (node.Contents.Count == 0) { resultConstant = ConstantValue.Create(string.Empty); } else { var intType = GetSpecialType(SpecialType.System_Int32, diagnostics, node); foreach (var content in node.Contents) { switch (content.Kind()) { case SyntaxKind.Interpolation: { var interpolation = (InterpolationSyntax)content; var value = BindValue(interpolation.Expression, diagnostics, BindValueKind.RValue); // We need to ensure the argument is not a lambda, method group, etc. It isn't nice to wait until lowering, // when we perform overload resolution, to report a problem. So we do that check by calling // GenerateConversionForAssignment with objectType. However we want to preserve the original expression's // natural type so that overload resolution may select a specialized implementation of string.Format, // so we discard the result of that call and only preserve its diagnostics. BoundExpression? alignment = null; BoundLiteral? format = null; if (interpolation.AlignmentClause != null) { alignment = GenerateConversionForAssignment(intType, BindValue(interpolation.AlignmentClause.Value, diagnostics, Binder.BindValueKind.RValue), diagnostics); var alignmentConstant = alignment.ConstantValue; if (alignmentConstant != null && !alignmentConstant.IsBad) { const int magnitudeLimit = 32767; // check that the magnitude of the alignment is "in range". int alignmentValue = alignmentConstant.Int32Value; // We do the arithmetic using negative numbers because the largest negative int has no corresponding positive (absolute) value. alignmentValue = (alignmentValue > 0) ? -alignmentValue : alignmentValue; if (alignmentValue < -magnitudeLimit) { diagnostics.Add(ErrorCode.WRN_AlignmentMagnitude, alignment.Syntax.Location, alignmentConstant.Int32Value, magnitudeLimit); } } else if (!alignment.HasErrors) { diagnostics.Add(ErrorCode.ERR_ConstantExpected, interpolation.AlignmentClause.Value.Location); } } if (interpolation.FormatClause != null) { var text = interpolation.FormatClause.FormatStringToken.ValueText; char lastChar; bool hasErrors = false; if (text.Length == 0) { diagnostics.Add(ErrorCode.ERR_EmptyFormatSpecifier, interpolation.FormatClause.Location); hasErrors = true; } else if (SyntaxFacts.IsWhitespace(lastChar = text[text.Length - 1]) || SyntaxFacts.IsNewLine(lastChar)) { diagnostics.Add(ErrorCode.ERR_TrailingWhitespaceInFormatSpecifier, interpolation.FormatClause.Location); hasErrors = true; } format = new BoundLiteral(interpolation.FormatClause, ConstantValue.Create(text), stringType, hasErrors); } builder.Add(new BoundStringInsert(interpolation, value, alignment, format, isInterpolatedStringHandlerAppendCall: false)); if (!isResultConstant || value.ConstantValue == null || !(interpolation is { FormatClause: null, AlignmentClause: null }) || !(value.ConstantValue is { IsString: true, IsBad: false })) { isResultConstant = false; continue; } resultConstant = (resultConstant is null) ? value.ConstantValue : FoldStringConcatenation(BinaryOperatorKind.StringConcatenation, resultConstant, value.ConstantValue); continue; } case SyntaxKind.InterpolatedStringText: { var text = ((InterpolatedStringTextSyntax)content).TextToken.ValueText; builder.Add(new BoundLiteral(content, ConstantValue.Create(text, SpecialType.System_String), stringType)); if (isResultConstant) { var constantVal = ConstantValue.Create(ConstantValueUtils.UnescapeInterpolatedStringLiteral(text), SpecialType.System_String); resultConstant = (resultConstant is null) ? constantVal : FoldStringConcatenation(BinaryOperatorKind.StringConcatenation, resultConstant, constantVal); } continue; } default: throw ExceptionUtilities.UnexpectedValue(content.Kind()); } } if (!isResultConstant) { resultConstant = null; } } Debug.Assert(isResultConstant == (resultConstant != null)); return new BoundUnconvertedInterpolatedString(node, builder.ToImmutableAndFree(), resultConstant, stringType); } private BoundInterpolatedString BindUnconvertedInterpolatedStringToString(BoundUnconvertedInterpolatedString unconvertedInterpolatedString, BindingDiagnosticBag diagnostics) { // We have 4 possible lowering strategies, dependent on the contents of the string, in this order: // 1. The string is a constant value. We can just use the final value. // 2. The string is composed of 4 or fewer components that are all strings, we can lower to a call to string.Concat without a // params array. This is very efficient as the runtime can allocate a buffer for the string with exactly the correct length and // make no intermediate allocations. // 3. The WellKnownType DefaultInterpolatedStringHandler is available, and none of the interpolation holes contain an await expression. // The builder is a ref struct, and we can guarantee the lifetime won't outlive the stack if the string doesn't contain any // awaits, but if it does we cannot use it. This builder is the only way that ref structs can be directly used as interpolation // hole components, which means that ref structs components and await expressions cannot be combined. It is already illegal for // the user to use ref structs in an async method today, but if that were to ever change, this would still need to be respected. // We also cannot use this method if the interpolated string appears within a catch filter, as the builder is disposable and we // cannot put a try/finally inside a filter block. // 4. The string is composed of more than 4 components that are all strings themselves. We can turn this into a single // call to string.Concat. We prefer the builder over this because the builder can use pooling to avoid new allocations, while this // call will need to allocate a param array. // 5. The string has heterogeneous data and either InterpolatedStringHandler is unavailable, or one of the holes contains an await // expression. This is turned into a call to string.Format. // // We need to do the determination of 1, 2, 3, or 4/5 up front, rather than in lowering, as it affects diagnostics (ref structs not being // able to be used, for example). However, between 4 and 5, we don't need to know at this point, so that logic is deferred for lowering. if (unconvertedInterpolatedString.ConstantValue is not null) { // Case 1 Debug.Assert(unconvertedInterpolatedString.Parts.All(static part => part.Type is null or { SpecialType: SpecialType.System_String })); return constructWithData(BindInterpolatedStringParts(unconvertedInterpolatedString, diagnostics), data: null); } // Case 2. Attempt to see if all parts are strings. if (unconvertedInterpolatedString.Parts.Length <= 4 && unconvertedInterpolatedString.Parts.All(p => p is BoundLiteral or BoundStringInsert { Value: { Type: { SpecialType: SpecialType.System_String } }, Alignment: null, Format: null })) { return constructWithData(BindInterpolatedStringParts(unconvertedInterpolatedString, diagnostics), data: null); } if (tryBindAsHandlerType(out var result)) { // Case 3 return result; } // The specifics of 4 vs 5 aren't necessary for this stage of binding. The only thing that matters is that every part needs to be convertible // object. return constructWithData(BindInterpolatedStringParts(unconvertedInterpolatedString, diagnostics), data: null); BoundInterpolatedString constructWithData(ImmutableArray<BoundExpression> parts, InterpolatedStringHandlerData? data) => new BoundInterpolatedString( unconvertedInterpolatedString.Syntax, data, parts, unconvertedInterpolatedString.ConstantValue, unconvertedInterpolatedString.Type, unconvertedInterpolatedString.HasErrors); bool tryBindAsHandlerType([NotNullWhen(true)] out BoundInterpolatedString? result) { result = null; if (unconvertedInterpolatedString.Parts.ContainsAwaitExpression()) { return false; } var interpolatedStringHandlerType = Compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_DefaultInterpolatedStringHandler); if (interpolatedStringHandlerType is MissingMetadataTypeSymbol) { return false; } result = BindUnconvertedInterpolatedStringToHandlerType(unconvertedInterpolatedString, interpolatedStringHandlerType, diagnostics, isHandlerConversion: false); return true; } } private BoundInterpolatedString BindUnconvertedInterpolatedStringToHandlerType( BoundUnconvertedInterpolatedString unconvertedInterpolatedString, NamedTypeSymbol interpolatedStringHandlerType, BindingDiagnosticBag diagnostics, bool isHandlerConversion, ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments = default, ImmutableArray<RefKind> additionalConstructorRefKinds = default) { Debug.Assert(additionalConstructorArguments.IsDefault ? additionalConstructorRefKinds.IsDefault : additionalConstructorArguments.Length == additionalConstructorRefKinds.Length); additionalConstructorArguments = additionalConstructorArguments.NullToEmpty(); additionalConstructorRefKinds = additionalConstructorRefKinds.NullToEmpty(); ReportUseSite(interpolatedStringHandlerType, diagnostics, unconvertedInterpolatedString.Syntax); // We satisfy the conditions for using an interpolated string builder. Bind all the builder calls unconditionally, so that if // there are errors we get better diagnostics than "could not convert to object." var implicitBuilderReceiver = new BoundInterpolatedStringHandlerPlaceholder(unconvertedInterpolatedString.Syntax, interpolatedStringHandlerType) { WasCompilerGenerated = true }; var (appendCalls, usesBoolReturn, positionInfo, baseStringLength, numFormatHoles) = BindInterpolatedStringAppendCalls(unconvertedInterpolatedString, implicitBuilderReceiver, diagnostics); // Prior to C# 10, all types in an interpolated string expression needed to be convertible to `object`. After 10, some types // (such as Span<T>) that are not convertible to `object` are permissible as interpolated string components, provided there // is an applicable AppendFormatted method that accepts them. To preserve langversion, we therefore make sure all components // are convertible to object if the current langversion is lower than the interpolation feature and we're converting this // interpolation into an actual string. bool needToCheckConversionToObject = false; if (isHandlerConversion) { CheckFeatureAvailability(unconvertedInterpolatedString.Syntax, MessageID.IDS_FeatureImprovedInterpolatedStrings, diagnostics); } else if (!Compilation.IsFeatureEnabled(MessageID.IDS_FeatureImprovedInterpolatedStrings) && diagnostics.AccumulatesDiagnostics) { needToCheckConversionToObject = true; } Debug.Assert(appendCalls.Length == unconvertedInterpolatedString.Parts.Length); Debug.Assert(appendCalls.All(a => a is { HasErrors: true } or BoundCall { Arguments: { Length: > 0 } } or BoundDynamicInvocation)); if (needToCheckConversionToObject) { TypeSymbol objectType = GetSpecialType(SpecialType.System_Object, diagnostics, unconvertedInterpolatedString.Syntax); BindingDiagnosticBag conversionDiagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false); foreach (var currentPart in unconvertedInterpolatedString.Parts) { if (currentPart is BoundStringInsert insert) { var value = insert.Value; bool reported = false; if (value.Type is not null) { value = BindToNaturalType(value, conversionDiagnostics); if (conversionDiagnostics.HasAnyErrors()) { CheckFeatureAvailability(value.Syntax, MessageID.IDS_FeatureImprovedInterpolatedStrings, diagnostics); reported = true; } } if (!reported) { _ = GenerateConversionForAssignment(objectType, value, conversionDiagnostics); if (conversionDiagnostics.HasAnyErrors()) { CheckFeatureAvailability(value.Syntax, MessageID.IDS_FeatureImprovedInterpolatedStrings, diagnostics); } } conversionDiagnostics.Clear(); } } conversionDiagnostics.Free(); } var intType = GetSpecialType(SpecialType.System_Int32, diagnostics, unconvertedInterpolatedString.Syntax); int constructorArgumentLength = 3 + additionalConstructorArguments.Length; var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(constructorArgumentLength); var refKindsBuilder = ArrayBuilder<RefKind>.GetInstance(constructorArgumentLength); refKindsBuilder.Add(RefKind.None); refKindsBuilder.Add(RefKind.None); refKindsBuilder.AddRange(additionalConstructorRefKinds); // Add the trailing out validity parameter for the first attempt.Note that we intentionally use `diagnostics` for resolving System.Boolean, // because we want to track that we're using the type no matter what. var boolType = GetSpecialType(SpecialType.System_Boolean, diagnostics, unconvertedInterpolatedString.Syntax); var trailingConstructorValidityPlaceholder = new BoundInterpolatedStringArgumentPlaceholder(unconvertedInterpolatedString.Syntax, BoundInterpolatedStringArgumentPlaceholder.TrailingConstructorValidityParameter, valSafeToEscape: LocalScopeDepth, boolType); var outConstructorAdditionalArguments = additionalConstructorArguments.Add(trailingConstructorValidityPlaceholder); refKindsBuilder.Add(RefKind.Out); populateArguments(unconvertedInterpolatedString.Syntax, outConstructorAdditionalArguments, baseStringLength, numFormatHoles, intType, argumentsBuilder); BoundExpression constructorCall; var outConstructorDiagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: diagnostics.AccumulatesDependencies); var outConstructorCall = MakeConstructorInvocation(interpolatedStringHandlerType, argumentsBuilder, refKindsBuilder, unconvertedInterpolatedString.Syntax, outConstructorDiagnostics); if (outConstructorCall is not BoundObjectCreationExpression { ResultKind: LookupResultKind.Viable }) { // MakeConstructorInvocation can call CoerceArguments on the builder if overload resolution succeeded ignoring accessibility, which // could still end up not succeeding, and that would end up changing the arguments. So we want to clear and repopulate. argumentsBuilder.Clear(); // Try again without an out parameter. populateArguments(unconvertedInterpolatedString.Syntax, additionalConstructorArguments, baseStringLength, numFormatHoles, intType, argumentsBuilder); refKindsBuilder.RemoveLast(); var nonOutConstructorDiagnostics = BindingDiagnosticBag.GetInstance(template: outConstructorDiagnostics); BoundExpression nonOutConstructorCall = MakeConstructorInvocation(interpolatedStringHandlerType, argumentsBuilder, refKindsBuilder, unconvertedInterpolatedString.Syntax, nonOutConstructorDiagnostics); if (nonOutConstructorCall is BoundObjectCreationExpression { ResultKind: LookupResultKind.Viable }) { // We successfully bound the out version, so set all the final data based on that binding constructorCall = nonOutConstructorCall; diagnostics.AddRangeAndFree(nonOutConstructorDiagnostics); outConstructorDiagnostics.Free(); } else { // We'll attempt to figure out which failure was "best" by looking to see if one failed to bind because it couldn't find // a constructor with the correct number of arguments. We presume that, if one failed for this reason and the other failed // for a different reason, that different reason is the one the user will want to know about. If both or neither failed // because of this error, we'll report everything. // https://github.com/dotnet/roslyn/issues/54396 Instead of inspecting errors, we should be capturing the results of overload // resolution and attempting to determine which method considered was the best to report errors for. var nonOutConstructorHasArityError = nonOutConstructorDiagnostics.DiagnosticBag?.AsEnumerableWithoutResolution().Any(d => (ErrorCode)d.Code == ErrorCode.ERR_BadCtorArgCount) ?? false; var outConstructorHasArityError = outConstructorDiagnostics.DiagnosticBag?.AsEnumerableWithoutResolution().Any(d => (ErrorCode)d.Code == ErrorCode.ERR_BadCtorArgCount) ?? false; switch ((nonOutConstructorHasArityError, outConstructorHasArityError)) { case (true, false): constructorCall = outConstructorCall; additionalConstructorArguments = outConstructorAdditionalArguments; diagnostics.AddRangeAndFree(outConstructorDiagnostics); nonOutConstructorDiagnostics.Free(); break; case (false, true): constructorCall = nonOutConstructorCall; diagnostics.AddRangeAndFree(nonOutConstructorDiagnostics); outConstructorDiagnostics.Free(); break; default: // For the final output binding info, we'll go with the shorter constructor in the absence of any tiebreaker, // but we'll report all diagnostics constructorCall = nonOutConstructorCall; diagnostics.AddRangeAndFree(nonOutConstructorDiagnostics); diagnostics.AddRangeAndFree(outConstructorDiagnostics); break; } } } else { diagnostics.AddRangeAndFree(outConstructorDiagnostics); constructorCall = outConstructorCall; additionalConstructorArguments = outConstructorAdditionalArguments; } argumentsBuilder.Free(); refKindsBuilder.Free(); Debug.Assert(constructorCall.HasErrors || constructorCall is BoundObjectCreationExpression or BoundDynamicObjectCreationExpression); if (constructorCall is BoundDynamicObjectCreationExpression) { // An interpolated string handler construction cannot use dynamic. Manually construct an instance of '{0}'. diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, unconvertedInterpolatedString.Syntax.Location, interpolatedStringHandlerType.Name); } return new BoundInterpolatedString( unconvertedInterpolatedString.Syntax, new InterpolatedStringHandlerData( interpolatedStringHandlerType, constructorCall, usesBoolReturn, LocalScopeDepth, additionalConstructorArguments.NullToEmpty(), positionInfo, implicitBuilderReceiver), appendCalls, unconvertedInterpolatedString.ConstantValue, unconvertedInterpolatedString.Type, unconvertedInterpolatedString.HasErrors); static void populateArguments(SyntaxNode syntax, ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments, int baseStringLength, int numFormatHoles, NamedTypeSymbol intType, ArrayBuilder<BoundExpression> argumentsBuilder) { // literalLength argumentsBuilder.Add(new BoundLiteral(syntax, ConstantValue.Create(baseStringLength), intType) { WasCompilerGenerated = true }); // formattedCount argumentsBuilder.Add(new BoundLiteral(syntax, ConstantValue.Create(numFormatHoles), intType) { WasCompilerGenerated = true }); // Any other arguments from the call site argumentsBuilder.AddRange(additionalConstructorArguments); } } private ImmutableArray<BoundExpression> BindInterpolatedStringParts(BoundUnconvertedInterpolatedString unconvertedInterpolatedString, BindingDiagnosticBag diagnostics) { ArrayBuilder<BoundExpression>? partsBuilder = null; var objectType = GetSpecialType(SpecialType.System_Object, diagnostics, unconvertedInterpolatedString.Syntax); for (int i = 0; i < unconvertedInterpolatedString.Parts.Length; i++) { var part = unconvertedInterpolatedString.Parts[i]; if (part is BoundStringInsert insert) { BoundExpression newValue; if (insert.Value.Type is null) { newValue = GenerateConversionForAssignment(objectType, insert.Value, diagnostics); } else { newValue = BindToNaturalType(insert.Value, diagnostics); _ = GenerateConversionForAssignment(objectType, insert.Value, diagnostics); } if (insert.Value != newValue) { if (partsBuilder is null) { partsBuilder = ArrayBuilder<BoundExpression>.GetInstance(unconvertedInterpolatedString.Parts.Length); partsBuilder.AddRange(unconvertedInterpolatedString.Parts, i); } partsBuilder.Add(insert.Update(newValue, insert.Alignment, insert.Format, isInterpolatedStringHandlerAppendCall: false)); } else { partsBuilder?.Add(part); } } else { Debug.Assert(part is BoundLiteral { Type: { SpecialType: SpecialType.System_String } }); partsBuilder?.Add(part); } } return partsBuilder?.ToImmutableAndFree() ?? unconvertedInterpolatedString.Parts; } private (ImmutableArray<BoundExpression> AppendFormatCalls, bool UsesBoolReturn, ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>, int BaseStringLength, int NumFormatHoles) BindInterpolatedStringAppendCalls( BoundUnconvertedInterpolatedString source, BoundInterpolatedStringHandlerPlaceholder implicitBuilderReceiver, BindingDiagnosticBag diagnostics) { if (source.Parts.IsEmpty) { return (ImmutableArray<BoundExpression>.Empty, false, ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>.Empty, 0, 0); } bool? builderPatternExpectsBool = null; var builderAppendCalls = ArrayBuilder<BoundExpression>.GetInstance(source.Parts.Length); var positionInfo = ArrayBuilder<(bool IsLiteral, bool HasAlignment, bool HasFormat)>.GetInstance(source.Parts.Length); var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(3); var parameterNamesAndLocationsBuilder = ArrayBuilder<(string, Location)?>.GetInstance(3); int baseStringLength = 0; int numFormatHoles = 0; foreach (var part in source.Parts) { Debug.Assert(part is BoundLiteral or BoundStringInsert); string methodName; bool isLiteral; bool hasAlignment; bool hasFormat; if (part is BoundStringInsert insert) { methodName = "AppendFormatted"; argumentsBuilder.Add(insert.Value); parameterNamesAndLocationsBuilder.Add(null); isLiteral = false; hasAlignment = false; hasFormat = false; if (insert.Alignment is not null) { hasAlignment = true; argumentsBuilder.Add(insert.Alignment); parameterNamesAndLocationsBuilder.Add(("alignment", insert.Alignment.Syntax.Location)); } if (insert.Format is not null) { hasFormat = true; argumentsBuilder.Add(insert.Format); parameterNamesAndLocationsBuilder.Add(("format", insert.Format.Syntax.Location)); } numFormatHoles++; } else { var boundLiteral = (BoundLiteral)part; Debug.Assert(boundLiteral.ConstantValue != null && boundLiteral.ConstantValue.IsString); var literalText = ConstantValueUtils.UnescapeInterpolatedStringLiteral(boundLiteral.ConstantValue.StringValue); methodName = "AppendLiteral"; argumentsBuilder.Add(boundLiteral.Update(ConstantValue.Create(literalText), boundLiteral.Type)); isLiteral = true; hasAlignment = false; hasFormat = false; baseStringLength += literalText.Length; } var arguments = argumentsBuilder.ToImmutableAndClear(); ImmutableArray<(string, Location)?> parameterNamesAndLocations; if (parameterNamesAndLocationsBuilder.Count > 1) { parameterNamesAndLocations = parameterNamesAndLocationsBuilder.ToImmutableAndClear(); } else { Debug.Assert(parameterNamesAndLocationsBuilder.Count == 0 || parameterNamesAndLocationsBuilder[0] == null); parameterNamesAndLocations = default; parameterNamesAndLocationsBuilder.Clear(); } var call = MakeInvocationExpression(part.Syntax, implicitBuilderReceiver, methodName, arguments, diagnostics, names: parameterNamesAndLocations, searchExtensionMethodsIfNecessary: false); builderAppendCalls.Add(call); positionInfo.Add((isLiteral, hasAlignment, hasFormat)); Debug.Assert(call is BoundCall or BoundDynamicInvocation or { HasErrors: true }); // We just assume that dynamic is going to do the right thing, and runtime will fail if it does not. If there are only dynamic calls, we assume that // void is returned. if (call is BoundCall { Method: { ReturnType: var returnType } method }) { bool methodReturnsBool = returnType.SpecialType == SpecialType.System_Boolean; if (!methodReturnsBool && returnType.SpecialType != SpecialType.System_Void) { // Interpolated string handler method '{0}' is malformed. It does not return 'void' or 'bool'. diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, part.Syntax.Location, method); } else if (builderPatternExpectsBool == null) { builderPatternExpectsBool = methodReturnsBool; } else if (builderPatternExpectsBool != methodReturnsBool) { // Interpolated string handler method '{0}' has inconsistent return types. Expected to return '{1}'. var expected = builderPatternExpectsBool == true ? Compilation.GetSpecialType(SpecialType.System_Boolean) : Compilation.GetSpecialType(SpecialType.System_Void); diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, part.Syntax.Location, method, expected); } } } argumentsBuilder.Free(); parameterNamesAndLocationsBuilder.Free(); return (builderAppendCalls.ToImmutableAndFree(), builderPatternExpectsBool ?? false, positionInfo.ToImmutableAndFree(), baseStringLength, numFormatHoles); } private BoundExpression BindInterpolatedStringHandlerInMemberCall( BoundUnconvertedInterpolatedString unconvertedString, ArrayBuilder<BoundExpression> arguments, ImmutableArray<ParameterSymbol> parameters, ref MemberAnalysisResult memberAnalysisResult, int interpolatedStringArgNum, TypeSymbol? receiverType, RefKind? receiverRefKind, uint receiverEscapeScope, BindingDiagnosticBag diagnostics) { var interpolatedStringConversion = memberAnalysisResult.ConversionForArg(interpolatedStringArgNum); Debug.Assert(interpolatedStringConversion.IsInterpolatedStringHandler); var interpolatedStringParameter = GetCorrespondingParameter(ref memberAnalysisResult, parameters, interpolatedStringArgNum); Debug.Assert(interpolatedStringParameter.Type is NamedTypeSymbol { IsInterpolatedStringHandlerType: true }); if (interpolatedStringParameter.HasInterpolatedStringHandlerArgumentError) { // The InterpolatedStringHandlerArgumentAttribute applied to parameter '{0}' is malformed and cannot be interpreted. Construct an instance of '{1}' manually. diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, unconvertedString.Syntax.Location, interpolatedStringParameter, interpolatedStringParameter.Type); return CreateConversion( unconvertedString.Syntax, unconvertedString, interpolatedStringConversion, isCast: false, conversionGroupOpt: null, wasCompilerGenerated: false, interpolatedStringParameter.Type, diagnostics, hasErrors: true); } var handlerParameterIndexes = interpolatedStringParameter.InterpolatedStringHandlerArgumentIndexes; if (handlerParameterIndexes.IsEmpty) { // No arguments, fall back to the standard conversion steps. return CreateConversion( unconvertedString.Syntax, unconvertedString, interpolatedStringConversion, isCast: false, conversionGroupOpt: null, interpolatedStringParameter.Type, diagnostics); } Debug.Assert(handlerParameterIndexes.All((index, paramLength) => index >= BoundInterpolatedStringArgumentPlaceholder.InstanceParameter && index < paramLength, parameters.Length)); // We need to find the appropriate argument expression for every expected parameter, and error on any that occur after the current parameter ImmutableArray<int> handlerArgumentIndexes; if (memberAnalysisResult.ArgsToParamsOpt.IsDefault && arguments.Count == parameters.Length) { // No parameters are missing and no remapped indexes, we can just use the original indexes handlerArgumentIndexes = handlerParameterIndexes; } else { // Args and parameters were reordered via named parameters, or parameters are missing. Find the correct argument index for each parameter. var handlerArgumentIndexesBuilder = ArrayBuilder<int>.GetInstance(handlerParameterIndexes.Length, fillWithValue: BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter); for (int handlerParameterIndex = 0; handlerParameterIndex < handlerParameterIndexes.Length; handlerParameterIndex++) { int handlerParameter = handlerParameterIndexes[handlerParameterIndex]; Debug.Assert(handlerArgumentIndexesBuilder[handlerParameterIndex] is BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter); if (handlerParameter == BoundInterpolatedStringArgumentPlaceholder.InstanceParameter) { handlerArgumentIndexesBuilder[handlerParameterIndex] = handlerParameter; continue; } for (int argumentIndex = 0; argumentIndex < arguments.Count; argumentIndex++) { // The index in the original parameter list we're looking to match up. int argumentParameterIndex = memberAnalysisResult.ParameterFromArgument(argumentIndex); // Is the original parameter index of the current argument the parameter index that was specified in the attribute? if (argumentParameterIndex == handlerParameter) { // We can't just bail out on the first match: users can duplicate parameters in attributes, causing the same value to be passed twice. handlerArgumentIndexesBuilder[handlerParameterIndex] = argumentIndex; } } } handlerArgumentIndexes = handlerArgumentIndexesBuilder.ToImmutableAndFree(); } var argumentPlaceholdersBuilder = ArrayBuilder<BoundInterpolatedStringArgumentPlaceholder>.GetInstance(handlerArgumentIndexes.Length); var argumentRefKindsBuilder = ArrayBuilder<RefKind>.GetInstance(handlerArgumentIndexes.Length); bool hasErrors = false; // Now, go through all the specified arguments and see if any were specified _after_ the interpolated string, and construct // a set of placeholders for overload resolution. for (int i = 0; i < handlerArgumentIndexes.Length; i++) { int argumentIndex = handlerArgumentIndexes[i]; Debug.Assert(argumentIndex != interpolatedStringArgNum); RefKind refKind; TypeSymbol placeholderType; switch (argumentIndex) { case BoundInterpolatedStringArgumentPlaceholder.InstanceParameter: Debug.Assert(receiverRefKind != null && receiverType is not null); refKind = receiverRefKind.GetValueOrDefault(); placeholderType = receiverType; break; case BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter: { // Don't error if the parameter isn't optional or params: the user will already have an error for missing an optional parameter or overload resolution failed. // If it is optional, then they could otherwise not specify the parameter and that's an error var originalParameterIndex = handlerParameterIndexes[i]; var parameter = parameters[originalParameterIndex]; if (parameter.IsOptional || (originalParameterIndex + 1 == parameters.Length && OverloadResolution.IsValidParamsParameter(parameter))) { // 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}'. diagnostics.Add( ErrorCode.ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified, unconvertedString.Syntax.Location, parameter.Name, interpolatedStringParameter.Name); hasErrors = true; } refKind = parameter.RefKind; placeholderType = parameter.Type; } break; default: { var originalParameterIndex = handlerParameterIndexes[i]; var parameter = parameters[originalParameterIndex]; if (argumentIndex > interpolatedStringArgNum) { // 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}'. diagnostics.Add( ErrorCode.ERR_InterpolatedStringHandlerArgumentLocatedAfterInterpolatedString, arguments[argumentIndex].Syntax.Location, parameter.Name, interpolatedStringParameter.Name); hasErrors = true; } refKind = parameter.RefKind; placeholderType = parameter.Type; } break; } SyntaxNode placeholderSyntax; uint valSafeToEscapeScope; switch (argumentIndex) { case BoundInterpolatedStringArgumentPlaceholder.InstanceParameter: placeholderSyntax = unconvertedString.Syntax; valSafeToEscapeScope = receiverEscapeScope; break; case BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter: placeholderSyntax = unconvertedString.Syntax; valSafeToEscapeScope = Binder.ExternalScope; break; case >= 0: placeholderSyntax = arguments[argumentIndex].Syntax; valSafeToEscapeScope = GetValEscape(arguments[argumentIndex], LocalScopeDepth); break; default: throw ExceptionUtilities.UnexpectedValue(argumentIndex); } argumentPlaceholdersBuilder.Add( new BoundInterpolatedStringArgumentPlaceholder( placeholderSyntax, argumentIndex, valSafeToEscapeScope, placeholderType, hasErrors: argumentIndex == BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter)); // We use the parameter refkind, rather than what the argument was actually passed with, because that will suppress duplicated errors // about arguments being passed with the wrong RefKind. The user will have already gotten an error about mismatched RefKinds or it will // be a place where refkinds are allowed to differ argumentRefKindsBuilder.Add(refKind); } var interpolatedString = BindUnconvertedInterpolatedStringToHandlerType( unconvertedString, (NamedTypeSymbol)interpolatedStringParameter.Type, diagnostics, isHandlerConversion: true, additionalConstructorArguments: argumentPlaceholdersBuilder.ToImmutableAndFree(), additionalConstructorRefKinds: argumentRefKindsBuilder.ToImmutableAndFree()); return new BoundConversion( interpolatedString.Syntax, interpolatedString, interpolatedStringConversion, @checked: CheckOverflowAtRuntime, explicitCastInCode: false, conversionGroupOpt: null, constantValueOpt: null, interpolatedStringParameter.Type, hasErrors || interpolatedString.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.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal partial class Binder { private BoundExpression BindInterpolatedString(InterpolatedStringExpressionSyntax node, BindingDiagnosticBag diagnostics) { var builder = ArrayBuilder<BoundExpression>.GetInstance(); var stringType = GetSpecialType(SpecialType.System_String, diagnostics, node); ConstantValue? resultConstant = null; bool isResultConstant = true; if (node.Contents.Count == 0) { resultConstant = ConstantValue.Create(string.Empty); } else { var intType = GetSpecialType(SpecialType.System_Int32, diagnostics, node); foreach (var content in node.Contents) { switch (content.Kind()) { case SyntaxKind.Interpolation: { var interpolation = (InterpolationSyntax)content; var value = BindValue(interpolation.Expression, diagnostics, BindValueKind.RValue); // We need to ensure the argument is not a lambda, method group, etc. It isn't nice to wait until lowering, // when we perform overload resolution, to report a problem. So we do that check by calling // GenerateConversionForAssignment with objectType. However we want to preserve the original expression's // natural type so that overload resolution may select a specialized implementation of string.Format, // so we discard the result of that call and only preserve its diagnostics. BoundExpression? alignment = null; BoundLiteral? format = null; if (interpolation.AlignmentClause != null) { alignment = GenerateConversionForAssignment(intType, BindValue(interpolation.AlignmentClause.Value, diagnostics, Binder.BindValueKind.RValue), diagnostics); var alignmentConstant = alignment.ConstantValue; if (alignmentConstant != null && !alignmentConstant.IsBad) { const int magnitudeLimit = 32767; // check that the magnitude of the alignment is "in range". int alignmentValue = alignmentConstant.Int32Value; // We do the arithmetic using negative numbers because the largest negative int has no corresponding positive (absolute) value. alignmentValue = (alignmentValue > 0) ? -alignmentValue : alignmentValue; if (alignmentValue < -magnitudeLimit) { diagnostics.Add(ErrorCode.WRN_AlignmentMagnitude, alignment.Syntax.Location, alignmentConstant.Int32Value, magnitudeLimit); } } else if (!alignment.HasErrors) { diagnostics.Add(ErrorCode.ERR_ConstantExpected, interpolation.AlignmentClause.Value.Location); } } if (interpolation.FormatClause != null) { var text = interpolation.FormatClause.FormatStringToken.ValueText; char lastChar; bool hasErrors = false; if (text.Length == 0) { diagnostics.Add(ErrorCode.ERR_EmptyFormatSpecifier, interpolation.FormatClause.Location); hasErrors = true; } else if (SyntaxFacts.IsWhitespace(lastChar = text[text.Length - 1]) || SyntaxFacts.IsNewLine(lastChar)) { diagnostics.Add(ErrorCode.ERR_TrailingWhitespaceInFormatSpecifier, interpolation.FormatClause.Location); hasErrors = true; } format = new BoundLiteral(interpolation.FormatClause, ConstantValue.Create(text), stringType, hasErrors); } builder.Add(new BoundStringInsert(interpolation, value, alignment, format, isInterpolatedStringHandlerAppendCall: false)); if (!isResultConstant || value.ConstantValue == null || !(interpolation is { FormatClause: null, AlignmentClause: null }) || !(value.ConstantValue is { IsString: true, IsBad: false })) { isResultConstant = false; continue; } resultConstant = (resultConstant is null) ? value.ConstantValue : FoldStringConcatenation(BinaryOperatorKind.StringConcatenation, resultConstant, value.ConstantValue); continue; } case SyntaxKind.InterpolatedStringText: { var text = ((InterpolatedStringTextSyntax)content).TextToken.ValueText; builder.Add(new BoundLiteral(content, ConstantValue.Create(text, SpecialType.System_String), stringType)); if (isResultConstant) { var constantVal = ConstantValue.Create(ConstantValueUtils.UnescapeInterpolatedStringLiteral(text), SpecialType.System_String); resultConstant = (resultConstant is null) ? constantVal : FoldStringConcatenation(BinaryOperatorKind.StringConcatenation, resultConstant, constantVal); } continue; } default: throw ExceptionUtilities.UnexpectedValue(content.Kind()); } } if (!isResultConstant) { resultConstant = null; } } Debug.Assert(isResultConstant == (resultConstant != null)); return new BoundUnconvertedInterpolatedString(node, builder.ToImmutableAndFree(), resultConstant, stringType); } private BoundInterpolatedString BindUnconvertedInterpolatedStringToString(BoundUnconvertedInterpolatedString unconvertedInterpolatedString, BindingDiagnosticBag diagnostics) { // We have 4 possible lowering strategies, dependent on the contents of the string, in this order: // 1. The string is a constant value. We can just use the final value. // 2. The string is composed of 4 or fewer components that are all strings, we can lower to a call to string.Concat without a // params array. This is very efficient as the runtime can allocate a buffer for the string with exactly the correct length and // make no intermediate allocations. // 3. The WellKnownType DefaultInterpolatedStringHandler is available, and none of the interpolation holes contain an await expression. // The builder is a ref struct, and we can guarantee the lifetime won't outlive the stack if the string doesn't contain any // awaits, but if it does we cannot use it. This builder is the only way that ref structs can be directly used as interpolation // hole components, which means that ref structs components and await expressions cannot be combined. It is already illegal for // the user to use ref structs in an async method today, but if that were to ever change, this would still need to be respected. // We also cannot use this method if the interpolated string appears within a catch filter, as the builder is disposable and we // cannot put a try/finally inside a filter block. // 4. The string is composed of more than 4 components that are all strings themselves. We can turn this into a single // call to string.Concat. We prefer the builder over this because the builder can use pooling to avoid new allocations, while this // call will need to allocate a param array. // 5. The string has heterogeneous data and either InterpolatedStringHandler is unavailable, or one of the holes contains an await // expression. This is turned into a call to string.Format. // // We need to do the determination of 1, 2, 3, or 4/5 up front, rather than in lowering, as it affects diagnostics (ref structs not being // able to be used, for example). However, between 4 and 5, we don't need to know at this point, so that logic is deferred for lowering. if (unconvertedInterpolatedString.ConstantValue is not null) { // Case 1 Debug.Assert(unconvertedInterpolatedString.Parts.All(static part => part.Type is null or { SpecialType: SpecialType.System_String })); return constructWithData(BindInterpolatedStringParts(unconvertedInterpolatedString, diagnostics), data: null); } // Case 2. Attempt to see if all parts are strings. if (unconvertedInterpolatedString.Parts.Length <= 4 && unconvertedInterpolatedString.Parts.All(p => p is BoundLiteral or BoundStringInsert { Value: { Type: { SpecialType: SpecialType.System_String } }, Alignment: null, Format: null })) { return constructWithData(BindInterpolatedStringParts(unconvertedInterpolatedString, diagnostics), data: null); } if (tryBindAsHandlerType(out var result)) { // Case 3 return result; } // The specifics of 4 vs 5 aren't necessary for this stage of binding. The only thing that matters is that every part needs to be convertible // object. return constructWithData(BindInterpolatedStringParts(unconvertedInterpolatedString, diagnostics), data: null); BoundInterpolatedString constructWithData(ImmutableArray<BoundExpression> parts, InterpolatedStringHandlerData? data) => new BoundInterpolatedString( unconvertedInterpolatedString.Syntax, data, parts, unconvertedInterpolatedString.ConstantValue, unconvertedInterpolatedString.Type, unconvertedInterpolatedString.HasErrors); bool tryBindAsHandlerType([NotNullWhen(true)] out BoundInterpolatedString? result) { result = null; if (InExpressionTree || unconvertedInterpolatedString.Parts.ContainsAwaitExpression()) { return false; } var interpolatedStringHandlerType = Compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_DefaultInterpolatedStringHandler); if (interpolatedStringHandlerType is MissingMetadataTypeSymbol) { return false; } result = BindUnconvertedInterpolatedStringToHandlerType(unconvertedInterpolatedString, interpolatedStringHandlerType, diagnostics, isHandlerConversion: false); return true; } } private BoundInterpolatedString BindUnconvertedInterpolatedStringToHandlerType( BoundUnconvertedInterpolatedString unconvertedInterpolatedString, NamedTypeSymbol interpolatedStringHandlerType, BindingDiagnosticBag diagnostics, bool isHandlerConversion, ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments = default, ImmutableArray<RefKind> additionalConstructorRefKinds = default) { Debug.Assert(additionalConstructorArguments.IsDefault ? additionalConstructorRefKinds.IsDefault : additionalConstructorArguments.Length == additionalConstructorRefKinds.Length); additionalConstructorArguments = additionalConstructorArguments.NullToEmpty(); additionalConstructorRefKinds = additionalConstructorRefKinds.NullToEmpty(); ReportUseSite(interpolatedStringHandlerType, diagnostics, unconvertedInterpolatedString.Syntax); // We satisfy the conditions for using an interpolated string builder. Bind all the builder calls unconditionally, so that if // there are errors we get better diagnostics than "could not convert to object." var implicitBuilderReceiver = new BoundInterpolatedStringHandlerPlaceholder(unconvertedInterpolatedString.Syntax, interpolatedStringHandlerType) { WasCompilerGenerated = true }; var (appendCalls, usesBoolReturn, positionInfo, baseStringLength, numFormatHoles) = BindInterpolatedStringAppendCalls(unconvertedInterpolatedString, implicitBuilderReceiver, diagnostics); // Prior to C# 10, all types in an interpolated string expression needed to be convertible to `object`. After 10, some types // (such as Span<T>) that are not convertible to `object` are permissible as interpolated string components, provided there // is an applicable AppendFormatted method that accepts them. To preserve langversion, we therefore make sure all components // are convertible to object if the current langversion is lower than the interpolation feature and we're converting this // interpolation into an actual string. bool needToCheckConversionToObject = false; if (isHandlerConversion) { CheckFeatureAvailability(unconvertedInterpolatedString.Syntax, MessageID.IDS_FeatureImprovedInterpolatedStrings, diagnostics); } else if (!Compilation.IsFeatureEnabled(MessageID.IDS_FeatureImprovedInterpolatedStrings) && diagnostics.AccumulatesDiagnostics) { needToCheckConversionToObject = true; } Debug.Assert(appendCalls.Length == unconvertedInterpolatedString.Parts.Length); Debug.Assert(appendCalls.All(a => a is { HasErrors: true } or BoundCall { Arguments: { Length: > 0 } } or BoundDynamicInvocation)); if (needToCheckConversionToObject) { TypeSymbol objectType = GetSpecialType(SpecialType.System_Object, diagnostics, unconvertedInterpolatedString.Syntax); BindingDiagnosticBag conversionDiagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false); foreach (var currentPart in unconvertedInterpolatedString.Parts) { if (currentPart is BoundStringInsert insert) { var value = insert.Value; bool reported = false; if (value.Type is not null) { value = BindToNaturalType(value, conversionDiagnostics); if (conversionDiagnostics.HasAnyErrors()) { CheckFeatureAvailability(value.Syntax, MessageID.IDS_FeatureImprovedInterpolatedStrings, diagnostics); reported = true; } } if (!reported) { _ = GenerateConversionForAssignment(objectType, value, conversionDiagnostics); if (conversionDiagnostics.HasAnyErrors()) { CheckFeatureAvailability(value.Syntax, MessageID.IDS_FeatureImprovedInterpolatedStrings, diagnostics); } } conversionDiagnostics.Clear(); } } conversionDiagnostics.Free(); } var intType = GetSpecialType(SpecialType.System_Int32, diagnostics, unconvertedInterpolatedString.Syntax); int constructorArgumentLength = 3 + additionalConstructorArguments.Length; var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(constructorArgumentLength); var refKindsBuilder = ArrayBuilder<RefKind>.GetInstance(constructorArgumentLength); refKindsBuilder.Add(RefKind.None); refKindsBuilder.Add(RefKind.None); refKindsBuilder.AddRange(additionalConstructorRefKinds); // Add the trailing out validity parameter for the first attempt.Note that we intentionally use `diagnostics` for resolving System.Boolean, // because we want to track that we're using the type no matter what. var boolType = GetSpecialType(SpecialType.System_Boolean, diagnostics, unconvertedInterpolatedString.Syntax); var trailingConstructorValidityPlaceholder = new BoundInterpolatedStringArgumentPlaceholder(unconvertedInterpolatedString.Syntax, BoundInterpolatedStringArgumentPlaceholder.TrailingConstructorValidityParameter, valSafeToEscape: LocalScopeDepth, boolType); var outConstructorAdditionalArguments = additionalConstructorArguments.Add(trailingConstructorValidityPlaceholder); refKindsBuilder.Add(RefKind.Out); populateArguments(unconvertedInterpolatedString.Syntax, outConstructorAdditionalArguments, baseStringLength, numFormatHoles, intType, argumentsBuilder); BoundExpression constructorCall; var outConstructorDiagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: diagnostics.AccumulatesDependencies); var outConstructorCall = MakeConstructorInvocation(interpolatedStringHandlerType, argumentsBuilder, refKindsBuilder, unconvertedInterpolatedString.Syntax, outConstructorDiagnostics); if (outConstructorCall is not BoundObjectCreationExpression { ResultKind: LookupResultKind.Viable }) { // MakeConstructorInvocation can call CoerceArguments on the builder if overload resolution succeeded ignoring accessibility, which // could still end up not succeeding, and that would end up changing the arguments. So we want to clear and repopulate. argumentsBuilder.Clear(); // Try again without an out parameter. populateArguments(unconvertedInterpolatedString.Syntax, additionalConstructorArguments, baseStringLength, numFormatHoles, intType, argumentsBuilder); refKindsBuilder.RemoveLast(); var nonOutConstructorDiagnostics = BindingDiagnosticBag.GetInstance(template: outConstructorDiagnostics); BoundExpression nonOutConstructorCall = MakeConstructorInvocation(interpolatedStringHandlerType, argumentsBuilder, refKindsBuilder, unconvertedInterpolatedString.Syntax, nonOutConstructorDiagnostics); if (nonOutConstructorCall is BoundObjectCreationExpression { ResultKind: LookupResultKind.Viable }) { // We successfully bound the out version, so set all the final data based on that binding constructorCall = nonOutConstructorCall; diagnostics.AddRangeAndFree(nonOutConstructorDiagnostics); outConstructorDiagnostics.Free(); } else { // We'll attempt to figure out which failure was "best" by looking to see if one failed to bind because it couldn't find // a constructor with the correct number of arguments. We presume that, if one failed for this reason and the other failed // for a different reason, that different reason is the one the user will want to know about. If both or neither failed // because of this error, we'll report everything. // https://github.com/dotnet/roslyn/issues/54396 Instead of inspecting errors, we should be capturing the results of overload // resolution and attempting to determine which method considered was the best to report errors for. var nonOutConstructorHasArityError = nonOutConstructorDiagnostics.DiagnosticBag?.AsEnumerableWithoutResolution().Any(d => (ErrorCode)d.Code == ErrorCode.ERR_BadCtorArgCount) ?? false; var outConstructorHasArityError = outConstructorDiagnostics.DiagnosticBag?.AsEnumerableWithoutResolution().Any(d => (ErrorCode)d.Code == ErrorCode.ERR_BadCtorArgCount) ?? false; switch ((nonOutConstructorHasArityError, outConstructorHasArityError)) { case (true, false): constructorCall = outConstructorCall; additionalConstructorArguments = outConstructorAdditionalArguments; diagnostics.AddRangeAndFree(outConstructorDiagnostics); nonOutConstructorDiagnostics.Free(); break; case (false, true): constructorCall = nonOutConstructorCall; diagnostics.AddRangeAndFree(nonOutConstructorDiagnostics); outConstructorDiagnostics.Free(); break; default: // For the final output binding info, we'll go with the shorter constructor in the absence of any tiebreaker, // but we'll report all diagnostics constructorCall = nonOutConstructorCall; diagnostics.AddRangeAndFree(nonOutConstructorDiagnostics); diagnostics.AddRangeAndFree(outConstructorDiagnostics); break; } } } else { diagnostics.AddRangeAndFree(outConstructorDiagnostics); constructorCall = outConstructorCall; additionalConstructorArguments = outConstructorAdditionalArguments; } argumentsBuilder.Free(); refKindsBuilder.Free(); Debug.Assert(constructorCall.HasErrors || constructorCall is BoundObjectCreationExpression or BoundDynamicObjectCreationExpression); if (constructorCall is BoundDynamicObjectCreationExpression) { // An interpolated string handler construction cannot use dynamic. Manually construct an instance of '{0}'. diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, unconvertedInterpolatedString.Syntax.Location, interpolatedStringHandlerType.Name); } return new BoundInterpolatedString( unconvertedInterpolatedString.Syntax, new InterpolatedStringHandlerData( interpolatedStringHandlerType, constructorCall, usesBoolReturn, LocalScopeDepth, additionalConstructorArguments.NullToEmpty(), positionInfo, implicitBuilderReceiver), appendCalls, unconvertedInterpolatedString.ConstantValue, unconvertedInterpolatedString.Type, unconvertedInterpolatedString.HasErrors); static void populateArguments(SyntaxNode syntax, ImmutableArray<BoundInterpolatedStringArgumentPlaceholder> additionalConstructorArguments, int baseStringLength, int numFormatHoles, NamedTypeSymbol intType, ArrayBuilder<BoundExpression> argumentsBuilder) { // literalLength argumentsBuilder.Add(new BoundLiteral(syntax, ConstantValue.Create(baseStringLength), intType) { WasCompilerGenerated = true }); // formattedCount argumentsBuilder.Add(new BoundLiteral(syntax, ConstantValue.Create(numFormatHoles), intType) { WasCompilerGenerated = true }); // Any other arguments from the call site argumentsBuilder.AddRange(additionalConstructorArguments); } } private ImmutableArray<BoundExpression> BindInterpolatedStringParts(BoundUnconvertedInterpolatedString unconvertedInterpolatedString, BindingDiagnosticBag diagnostics) { ArrayBuilder<BoundExpression>? partsBuilder = null; var objectType = GetSpecialType(SpecialType.System_Object, diagnostics, unconvertedInterpolatedString.Syntax); for (int i = 0; i < unconvertedInterpolatedString.Parts.Length; i++) { var part = unconvertedInterpolatedString.Parts[i]; if (part is BoundStringInsert insert) { BoundExpression newValue; if (insert.Value.Type is null) { newValue = GenerateConversionForAssignment(objectType, insert.Value, diagnostics); } else { newValue = BindToNaturalType(insert.Value, diagnostics); _ = GenerateConversionForAssignment(objectType, insert.Value, diagnostics); } if (insert.Value != newValue) { if (partsBuilder is null) { partsBuilder = ArrayBuilder<BoundExpression>.GetInstance(unconvertedInterpolatedString.Parts.Length); partsBuilder.AddRange(unconvertedInterpolatedString.Parts, i); } partsBuilder.Add(insert.Update(newValue, insert.Alignment, insert.Format, isInterpolatedStringHandlerAppendCall: false)); } else { partsBuilder?.Add(part); } } else { Debug.Assert(part is BoundLiteral { Type: { SpecialType: SpecialType.System_String } }); partsBuilder?.Add(part); } } return partsBuilder?.ToImmutableAndFree() ?? unconvertedInterpolatedString.Parts; } private (ImmutableArray<BoundExpression> AppendFormatCalls, bool UsesBoolReturn, ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>, int BaseStringLength, int NumFormatHoles) BindInterpolatedStringAppendCalls( BoundUnconvertedInterpolatedString source, BoundInterpolatedStringHandlerPlaceholder implicitBuilderReceiver, BindingDiagnosticBag diagnostics) { if (source.Parts.IsEmpty) { return (ImmutableArray<BoundExpression>.Empty, false, ImmutableArray<(bool IsLiteral, bool HasAlignment, bool HasFormat)>.Empty, 0, 0); } bool? builderPatternExpectsBool = null; var builderAppendCalls = ArrayBuilder<BoundExpression>.GetInstance(source.Parts.Length); var positionInfo = ArrayBuilder<(bool IsLiteral, bool HasAlignment, bool HasFormat)>.GetInstance(source.Parts.Length); var argumentsBuilder = ArrayBuilder<BoundExpression>.GetInstance(3); var parameterNamesAndLocationsBuilder = ArrayBuilder<(string, Location)?>.GetInstance(3); int baseStringLength = 0; int numFormatHoles = 0; foreach (var part in source.Parts) { Debug.Assert(part is BoundLiteral or BoundStringInsert); string methodName; bool isLiteral; bool hasAlignment; bool hasFormat; if (part is BoundStringInsert insert) { methodName = "AppendFormatted"; argumentsBuilder.Add(insert.Value); parameterNamesAndLocationsBuilder.Add(null); isLiteral = false; hasAlignment = false; hasFormat = false; if (insert.Alignment is not null) { hasAlignment = true; argumentsBuilder.Add(insert.Alignment); parameterNamesAndLocationsBuilder.Add(("alignment", insert.Alignment.Syntax.Location)); } if (insert.Format is not null) { hasFormat = true; argumentsBuilder.Add(insert.Format); parameterNamesAndLocationsBuilder.Add(("format", insert.Format.Syntax.Location)); } numFormatHoles++; } else { var boundLiteral = (BoundLiteral)part; Debug.Assert(boundLiteral.ConstantValue != null && boundLiteral.ConstantValue.IsString); var literalText = ConstantValueUtils.UnescapeInterpolatedStringLiteral(boundLiteral.ConstantValue.StringValue); methodName = "AppendLiteral"; argumentsBuilder.Add(boundLiteral.Update(ConstantValue.Create(literalText), boundLiteral.Type)); isLiteral = true; hasAlignment = false; hasFormat = false; baseStringLength += literalText.Length; } var arguments = argumentsBuilder.ToImmutableAndClear(); ImmutableArray<(string, Location)?> parameterNamesAndLocations; if (parameterNamesAndLocationsBuilder.Count > 1) { parameterNamesAndLocations = parameterNamesAndLocationsBuilder.ToImmutableAndClear(); } else { Debug.Assert(parameterNamesAndLocationsBuilder.Count == 0 || parameterNamesAndLocationsBuilder[0] == null); parameterNamesAndLocations = default; parameterNamesAndLocationsBuilder.Clear(); } var call = MakeInvocationExpression(part.Syntax, implicitBuilderReceiver, methodName, arguments, diagnostics, names: parameterNamesAndLocations, searchExtensionMethodsIfNecessary: false); builderAppendCalls.Add(call); positionInfo.Add((isLiteral, hasAlignment, hasFormat)); Debug.Assert(call is BoundCall or BoundDynamicInvocation or { HasErrors: true }); // We just assume that dynamic is going to do the right thing, and runtime will fail if it does not. If there are only dynamic calls, we assume that // void is returned. if (call is BoundCall { Method: { ReturnType: var returnType } method }) { bool methodReturnsBool = returnType.SpecialType == SpecialType.System_Boolean; if (!methodReturnsBool && returnType.SpecialType != SpecialType.System_Void) { // Interpolated string handler method '{0}' is malformed. It does not return 'void' or 'bool'. diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, part.Syntax.Location, method); } else if (builderPatternExpectsBool == null) { builderPatternExpectsBool = methodReturnsBool; } else if (builderPatternExpectsBool != methodReturnsBool) { // Interpolated string handler method '{0}' has inconsistent return types. Expected to return '{1}'. var expected = builderPatternExpectsBool == true ? Compilation.GetSpecialType(SpecialType.System_Boolean) : Compilation.GetSpecialType(SpecialType.System_Void); diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, part.Syntax.Location, method, expected); } } } argumentsBuilder.Free(); parameterNamesAndLocationsBuilder.Free(); return (builderAppendCalls.ToImmutableAndFree(), builderPatternExpectsBool ?? false, positionInfo.ToImmutableAndFree(), baseStringLength, numFormatHoles); } private BoundExpression BindInterpolatedStringHandlerInMemberCall( BoundUnconvertedInterpolatedString unconvertedString, ArrayBuilder<BoundExpression> arguments, ImmutableArray<ParameterSymbol> parameters, ref MemberAnalysisResult memberAnalysisResult, int interpolatedStringArgNum, TypeSymbol? receiverType, RefKind? receiverRefKind, uint receiverEscapeScope, BindingDiagnosticBag diagnostics) { var interpolatedStringConversion = memberAnalysisResult.ConversionForArg(interpolatedStringArgNum); Debug.Assert(interpolatedStringConversion.IsInterpolatedStringHandler); var interpolatedStringParameter = GetCorrespondingParameter(ref memberAnalysisResult, parameters, interpolatedStringArgNum); Debug.Assert(interpolatedStringParameter.Type is NamedTypeSymbol { IsInterpolatedStringHandlerType: true }); if (interpolatedStringParameter.HasInterpolatedStringHandlerArgumentError) { // The InterpolatedStringHandlerArgumentAttribute applied to parameter '{0}' is malformed and cannot be interpreted. Construct an instance of '{1}' manually. diagnostics.Add(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, unconvertedString.Syntax.Location, interpolatedStringParameter, interpolatedStringParameter.Type); return CreateConversion( unconvertedString.Syntax, unconvertedString, interpolatedStringConversion, isCast: false, conversionGroupOpt: null, wasCompilerGenerated: false, interpolatedStringParameter.Type, diagnostics, hasErrors: true); } var handlerParameterIndexes = interpolatedStringParameter.InterpolatedStringHandlerArgumentIndexes; if (handlerParameterIndexes.IsEmpty) { // No arguments, fall back to the standard conversion steps. return CreateConversion( unconvertedString.Syntax, unconvertedString, interpolatedStringConversion, isCast: false, conversionGroupOpt: null, interpolatedStringParameter.Type, diagnostics); } Debug.Assert(handlerParameterIndexes.All((index, paramLength) => index >= BoundInterpolatedStringArgumentPlaceholder.InstanceParameter && index < paramLength, parameters.Length)); // We need to find the appropriate argument expression for every expected parameter, and error on any that occur after the current parameter ImmutableArray<int> handlerArgumentIndexes; if (memberAnalysisResult.ArgsToParamsOpt.IsDefault && arguments.Count == parameters.Length) { // No parameters are missing and no remapped indexes, we can just use the original indexes handlerArgumentIndexes = handlerParameterIndexes; } else { // Args and parameters were reordered via named parameters, or parameters are missing. Find the correct argument index for each parameter. var handlerArgumentIndexesBuilder = ArrayBuilder<int>.GetInstance(handlerParameterIndexes.Length, fillWithValue: BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter); for (int handlerParameterIndex = 0; handlerParameterIndex < handlerParameterIndexes.Length; handlerParameterIndex++) { int handlerParameter = handlerParameterIndexes[handlerParameterIndex]; Debug.Assert(handlerArgumentIndexesBuilder[handlerParameterIndex] is BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter); if (handlerParameter == BoundInterpolatedStringArgumentPlaceholder.InstanceParameter) { handlerArgumentIndexesBuilder[handlerParameterIndex] = handlerParameter; continue; } for (int argumentIndex = 0; argumentIndex < arguments.Count; argumentIndex++) { // The index in the original parameter list we're looking to match up. int argumentParameterIndex = memberAnalysisResult.ParameterFromArgument(argumentIndex); // Is the original parameter index of the current argument the parameter index that was specified in the attribute? if (argumentParameterIndex == handlerParameter) { // We can't just bail out on the first match: users can duplicate parameters in attributes, causing the same value to be passed twice. handlerArgumentIndexesBuilder[handlerParameterIndex] = argumentIndex; } } } handlerArgumentIndexes = handlerArgumentIndexesBuilder.ToImmutableAndFree(); } var argumentPlaceholdersBuilder = ArrayBuilder<BoundInterpolatedStringArgumentPlaceholder>.GetInstance(handlerArgumentIndexes.Length); var argumentRefKindsBuilder = ArrayBuilder<RefKind>.GetInstance(handlerArgumentIndexes.Length); bool hasErrors = false; // Now, go through all the specified arguments and see if any were specified _after_ the interpolated string, and construct // a set of placeholders for overload resolution. for (int i = 0; i < handlerArgumentIndexes.Length; i++) { int argumentIndex = handlerArgumentIndexes[i]; Debug.Assert(argumentIndex != interpolatedStringArgNum); RefKind refKind; TypeSymbol placeholderType; switch (argumentIndex) { case BoundInterpolatedStringArgumentPlaceholder.InstanceParameter: Debug.Assert(receiverRefKind != null && receiverType is not null); refKind = receiverRefKind.GetValueOrDefault(); placeholderType = receiverType; break; case BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter: { // Don't error if the parameter isn't optional or params: the user will already have an error for missing an optional parameter or overload resolution failed. // If it is optional, then they could otherwise not specify the parameter and that's an error var originalParameterIndex = handlerParameterIndexes[i]; var parameter = parameters[originalParameterIndex]; if (parameter.IsOptional || (originalParameterIndex + 1 == parameters.Length && OverloadResolution.IsValidParamsParameter(parameter))) { // 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}'. diagnostics.Add( ErrorCode.ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified, unconvertedString.Syntax.Location, parameter.Name, interpolatedStringParameter.Name); hasErrors = true; } refKind = parameter.RefKind; placeholderType = parameter.Type; } break; default: { var originalParameterIndex = handlerParameterIndexes[i]; var parameter = parameters[originalParameterIndex]; if (argumentIndex > interpolatedStringArgNum) { // 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}'. diagnostics.Add( ErrorCode.ERR_InterpolatedStringHandlerArgumentLocatedAfterInterpolatedString, arguments[argumentIndex].Syntax.Location, parameter.Name, interpolatedStringParameter.Name); hasErrors = true; } refKind = parameter.RefKind; placeholderType = parameter.Type; } break; } SyntaxNode placeholderSyntax; uint valSafeToEscapeScope; switch (argumentIndex) { case BoundInterpolatedStringArgumentPlaceholder.InstanceParameter: placeholderSyntax = unconvertedString.Syntax; valSafeToEscapeScope = receiverEscapeScope; break; case BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter: placeholderSyntax = unconvertedString.Syntax; valSafeToEscapeScope = Binder.ExternalScope; break; case >= 0: placeholderSyntax = arguments[argumentIndex].Syntax; valSafeToEscapeScope = GetValEscape(arguments[argumentIndex], LocalScopeDepth); break; default: throw ExceptionUtilities.UnexpectedValue(argumentIndex); } argumentPlaceholdersBuilder.Add( new BoundInterpolatedStringArgumentPlaceholder( placeholderSyntax, argumentIndex, valSafeToEscapeScope, placeholderType, hasErrors: argumentIndex == BoundInterpolatedStringArgumentPlaceholder.UnspecifiedParameter)); // We use the parameter refkind, rather than what the argument was actually passed with, because that will suppress duplicated errors // about arguments being passed with the wrong RefKind. The user will have already gotten an error about mismatched RefKinds or it will // be a place where refkinds are allowed to differ argumentRefKindsBuilder.Add(refKind); } var interpolatedString = BindUnconvertedInterpolatedStringToHandlerType( unconvertedString, (NamedTypeSymbol)interpolatedStringParameter.Type, diagnostics, isHandlerConversion: true, additionalConstructorArguments: argumentPlaceholdersBuilder.ToImmutableAndFree(), additionalConstructorRefKinds: argumentRefKindsBuilder.ToImmutableAndFree()); return new BoundConversion( interpolatedString.Syntax, interpolatedString, interpolatedStringConversion, @checked: CheckOverflowAtRuntime, explicitCastInCode: false, conversionGroupOpt: null, constantValueOpt: null, interpolatedStringParameter.Type, hasErrors || interpolatedString.HasErrors); } } }
1
dotnet/roslyn
55,125
Don't use DefaultInterpolatedStringHandler in expression trees
Introduces a binder flag to track whether we are currently in an expression tree or not. Fixes https://github.com/dotnet/roslyn/issues/55114.
333fred
2021-07-26T22:08:39Z
2021-07-27T19:33:24Z
5840335153dcca42570a853cdacd06d660fe9596
cfc12ce93ce377c4b9581ccf88403e6740d63977
Don't use DefaultInterpolatedStringHandler in expression trees. Introduces a binder flag to track whether we are currently in an expression tree or not. Fixes https://github.com/dotnet/roslyn/issues/55114.
./src/Compilers/CSharp/Portable/Binder/Binder_Invocation.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This portion of the binder converts an <see cref="ExpressionSyntax"/> into a <see cref="BoundExpression"/>. /// </summary> internal partial class Binder { private BoundExpression BindMethodGroup(ExpressionSyntax node, bool invoked, bool indexed, BindingDiagnosticBag diagnostics) { switch (node.Kind()) { case SyntaxKind.IdentifierName: case SyntaxKind.GenericName: return BindIdentifier((SimpleNameSyntax)node, invoked, indexed, diagnostics); case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: return BindMemberAccess((MemberAccessExpressionSyntax)node, invoked, indexed, diagnostics); case SyntaxKind.ParenthesizedExpression: return BindMethodGroup(((ParenthesizedExpressionSyntax)node).Expression, invoked: false, indexed: false, diagnostics: diagnostics); default: return BindExpression(node, diagnostics, invoked, indexed); } } private static ImmutableArray<MethodSymbol> GetOriginalMethods(OverloadResolutionResult<MethodSymbol> overloadResolutionResult) { // If overload resolution has failed then we want to stash away the original methods that we // considered so that the IDE can display tooltips or other information about them. // However, if a method group contained a generic method that was type inferred then // the IDE wants information about the *inferred* method, not the original unconstructed // generic method. if (overloadResolutionResult == null) { return ImmutableArray<MethodSymbol>.Empty; } var builder = ArrayBuilder<MethodSymbol>.GetInstance(); foreach (var result in overloadResolutionResult.Results) { builder.Add(result.Member); } return builder.ToImmutableAndFree(); } #nullable enable /// <summary> /// Helper method to create a synthesized method invocation expression. /// </summary> /// <param name="node">Syntax Node.</param> /// <param name="receiver">Receiver for the method call.</param> /// <param name="methodName">Method to be invoked on the receiver.</param> /// <param name="args">Arguments to the method call.</param> /// <param name="diagnostics">Diagnostics.</param> /// <param name="typeArgsSyntax">Optional type arguments syntax.</param> /// <param name="typeArgs">Optional type arguments.</param> /// <param name="queryClause">The syntax for the query clause generating this invocation expression, if any.</param> /// <param name="allowFieldsAndProperties">True to allow invocation of fields and properties of delegate type. Only methods are allowed otherwise.</param> /// <param name="allowUnexpandedForm">False to prevent selecting a params method in unexpanded form.</param> /// <returns>Synthesized method invocation expression.</returns> internal BoundExpression MakeInvocationExpression( SyntaxNode node, BoundExpression receiver, string methodName, ImmutableArray<BoundExpression> args, BindingDiagnosticBag diagnostics, SeparatedSyntaxList<TypeSyntax> typeArgsSyntax = default(SeparatedSyntaxList<TypeSyntax>), ImmutableArray<TypeWithAnnotations> typeArgs = default(ImmutableArray<TypeWithAnnotations>), ImmutableArray<(string Name, Location Location)?> names = default, CSharpSyntaxNode? queryClause = null, bool allowFieldsAndProperties = false, bool allowUnexpandedForm = true, bool searchExtensionMethodsIfNecessary = true) { Debug.Assert(receiver != null); Debug.Assert(names.IsDefault || names.Length == args.Length); receiver = BindToNaturalType(receiver, diagnostics); var boundExpression = BindInstanceMemberAccess(node, node, receiver, methodName, typeArgs.NullToEmpty().Length, typeArgsSyntax, typeArgs, invoked: true, indexed: false, diagnostics, searchExtensionMethodsIfNecessary); // The other consumers of this helper (await and collection initializers) require the target member to be a method. if (!allowFieldsAndProperties && (boundExpression.Kind == BoundKind.FieldAccess || boundExpression.Kind == BoundKind.PropertyAccess)) { Symbol symbol; MessageID msgId; if (boundExpression.Kind == BoundKind.FieldAccess) { msgId = MessageID.IDS_SK_FIELD; symbol = ((BoundFieldAccess)boundExpression).FieldSymbol; } else { msgId = MessageID.IDS_SK_PROPERTY; symbol = ((BoundPropertyAccess)boundExpression).PropertySymbol; } diagnostics.Add( ErrorCode.ERR_BadSKknown, node.Location, methodName, msgId.Localize(), MessageID.IDS_SK_METHOD.Localize()); return BadExpression(node, LookupResultKind.Empty, ImmutableArray.Create(symbol), args.Add(receiver), wasCompilerGenerated: true); } boundExpression = CheckValue(boundExpression, BindValueKind.RValueOrMethodGroup, diagnostics); boundExpression.WasCompilerGenerated = true; var analyzedArguments = AnalyzedArguments.GetInstance(); Debug.Assert(!args.Any(e => e.Kind == BoundKind.OutVariablePendingInference || e.Kind == BoundKind.OutDeconstructVarPendingInference || e.Kind == BoundKind.DiscardExpression && !e.HasExpressionType())); analyzedArguments.Arguments.AddRange(args); if (!names.IsDefault) { analyzedArguments.Names.AddRange(names); } BoundExpression result = BindInvocationExpression( node, node, methodName, boundExpression, analyzedArguments, diagnostics, queryClause, allowUnexpandedForm: allowUnexpandedForm); // Query operator can't be called dynamically. if (queryClause != null && result.Kind == BoundKind.DynamicInvocation) { // the error has already been reported by BindInvocationExpression Debug.Assert(diagnostics.DiagnosticBag is null || diagnostics.HasAnyErrors()); result = CreateBadCall(node, boundExpression, LookupResultKind.Viable, analyzedArguments); } result.WasCompilerGenerated = true; analyzedArguments.Free(); return result; } #nullable disable /// <summary> /// Bind an expression as a method invocation. /// </summary> private BoundExpression BindInvocationExpression( InvocationExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression result; if (TryBindNameofOperator(node, diagnostics, out result)) { return result; // all of the binding is done by BindNameofOperator } // M(__arglist()) is legal, but M(__arglist(__arglist()) is not! bool isArglist = node.Expression.Kind() == SyntaxKind.ArgListExpression; AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance(); if (isArglist) { BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments, allowArglist: false); result = BindArgListOperator(node, diagnostics, analyzedArguments); } else { BoundExpression boundExpression = BindMethodGroup(node.Expression, invoked: true, indexed: false, diagnostics: diagnostics); boundExpression = CheckValue(boundExpression, BindValueKind.RValueOrMethodGroup, diagnostics); string name = boundExpression.Kind == BoundKind.MethodGroup ? GetName(node.Expression) : null; BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments, allowArglist: true); result = BindInvocationExpression(node, node.Expression, name, boundExpression, analyzedArguments, diagnostics); } analyzedArguments.Free(); return result; } private BoundExpression BindArgListOperator(InvocationExpressionSyntax node, BindingDiagnosticBag diagnostics, AnalyzedArguments analyzedArguments) { bool hasErrors = analyzedArguments.HasErrors; // We allow names, oddly enough; M(__arglist(x : 123)) is legal. We just ignore them. TypeSymbol objType = GetSpecialType(SpecialType.System_Object, diagnostics, node); for (int i = 0; i < analyzedArguments.Arguments.Count; ++i) { BoundExpression argument = analyzedArguments.Arguments[i]; if (argument.Kind == BoundKind.OutVariablePendingInference) { analyzedArguments.Arguments[i] = ((OutVariablePendingInference)argument).FailInference(this, diagnostics); } else if ((object)argument.Type == null && !argument.HasAnyErrors) { // We are going to need every argument in here to have a type. If we don't have one, // try converting it to object. We'll either succeed (if it is a null literal) // or fail with a good error message. // // Note that the native compiler converts null literals to object, and for everything // else it either crashes, or produces nonsense code. Roslyn improves upon this considerably. analyzedArguments.Arguments[i] = GenerateConversionForAssignment(objType, argument, diagnostics); } else if (argument.Type.IsVoidType()) { Error(diagnostics, ErrorCode.ERR_CantUseVoidInArglist, argument.Syntax); hasErrors = true; } else if (analyzedArguments.RefKind(i) == RefKind.None) { analyzedArguments.Arguments[i] = BindToNaturalType(analyzedArguments.Arguments[i], diagnostics); } switch (analyzedArguments.RefKind(i)) { case RefKind.None: case RefKind.Ref: break; default: // Disallow "in" or "out" arguments Error(diagnostics, ErrorCode.ERR_CantUseInOrOutInArglist, argument.Syntax); hasErrors = true; break; } } ImmutableArray<BoundExpression> arguments = analyzedArguments.Arguments.ToImmutable(); ImmutableArray<RefKind> refKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); return new BoundArgListOperator(node, arguments, refKinds, null, hasErrors); } /// <summary> /// Bind an expression as a method invocation. /// </summary> private BoundExpression BindInvocationExpression( SyntaxNode node, SyntaxNode expression, string methodName, BoundExpression boundExpression, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause = null, bool allowUnexpandedForm = true) { BoundExpression result; NamedTypeSymbol delegateType; if ((object)boundExpression.Type != null && boundExpression.Type.IsDynamic()) { // Either we have a dynamic method group invocation "dyn.M(...)" or // a dynamic delegate invocation "dyn(...)" -- either way, bind it as a dynamic // invocation and let the lowering pass sort it out. ReportSuppressionIfNeeded(boundExpression, diagnostics); result = BindDynamicInvocation(node, boundExpression, analyzedArguments, ImmutableArray<MethodSymbol>.Empty, diagnostics, queryClause); } else if (boundExpression.Kind == BoundKind.MethodGroup) { ReportSuppressionIfNeeded(boundExpression, diagnostics); result = BindMethodGroupInvocation( node, expression, methodName, (BoundMethodGroup)boundExpression, analyzedArguments, diagnostics, queryClause, allowUnexpandedForm: allowUnexpandedForm, anyApplicableCandidates: out _); } else if ((object)(delegateType = GetDelegateType(boundExpression)) != null) { if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, delegateType, node: node)) { return CreateBadCall(node, boundExpression, LookupResultKind.Viable, analyzedArguments); } result = BindDelegateInvocation(node, expression, methodName, boundExpression, analyzedArguments, diagnostics, queryClause, delegateType); } else if (boundExpression.Type?.Kind == SymbolKind.FunctionPointerType) { ReportSuppressionIfNeeded(boundExpression, diagnostics); result = BindFunctionPointerInvocation(node, boundExpression, analyzedArguments, diagnostics); } else { if (!boundExpression.HasAnyErrors) { diagnostics.Add(new CSDiagnosticInfo(ErrorCode.ERR_MethodNameExpected), expression.Location); } result = CreateBadCall(node, boundExpression, LookupResultKind.NotInvocable, analyzedArguments); } CheckRestrictedTypeReceiver(result, this.Compilation, diagnostics); return result; } private BoundExpression BindDynamicInvocation( SyntaxNode node, BoundExpression expression, AnalyzedArguments arguments, ImmutableArray<MethodSymbol> applicableMethods, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause) { CheckNamedArgumentsForDynamicInvocation(arguments, diagnostics); bool hasErrors = false; if (expression.Kind == BoundKind.MethodGroup) { BoundMethodGroup methodGroup = (BoundMethodGroup)expression; BoundExpression receiver = methodGroup.ReceiverOpt; // receiver is null if we are calling a static method declared on an outer class via its simple name: if (receiver != null) { switch (receiver.Kind) { case BoundKind.BaseReference: Error(diagnostics, ErrorCode.ERR_NoDynamicPhantomOnBase, node, methodGroup.Name); hasErrors = true; break; case BoundKind.ThisReference: // Can't call the HasThis method due to EE doing odd things with containing member and its containing type. if ((InConstructorInitializer || InFieldInitializer) && receiver.WasCompilerGenerated) { // Only a static method can be called in a constructor initializer. If we were not in a ctor initializer // the runtime binder would ignore the receiver, but in a ctor initializer we can't read "this" before // the base constructor is called. We need to handle this as a type qualified static method call. // Also applicable to things like field initializers, which run before the ctor initializer. expression = methodGroup.Update( methodGroup.TypeArgumentsOpt, methodGroup.Name, methodGroup.Methods, methodGroup.LookupSymbolOpt, methodGroup.LookupError, methodGroup.Flags & ~BoundMethodGroupFlags.HasImplicitReceiver, receiverOpt: new BoundTypeExpression(node, null, this.ContainingType).MakeCompilerGenerated(), resultKind: methodGroup.ResultKind); } break; case BoundKind.TypeOrValueExpression: var typeOrValue = (BoundTypeOrValueExpression)receiver; // Unfortunately, the runtime binder doesn't have APIs that would allow us to pass both "type or value". // Ideally the runtime binder would choose between type and value based on the result of the overload resolution. // We need to pick one or the other here. Dev11 compiler passes the type only if the value can't be accessed. bool inStaticContext; bool useType = IsInstance(typeOrValue.Data.ValueSymbol) && !HasThis(isExplicit: false, inStaticContext: out inStaticContext); BoundExpression finalReceiver = ReplaceTypeOrValueReceiver(typeOrValue, useType, diagnostics); expression = methodGroup.Update( methodGroup.TypeArgumentsOpt, methodGroup.Name, methodGroup.Methods, methodGroup.LookupSymbolOpt, methodGroup.LookupError, methodGroup.Flags, finalReceiver, methodGroup.ResultKind); break; } } } else { expression = BindToNaturalType(expression, diagnostics); } ImmutableArray<BoundExpression> argArray = BuildArgumentsForDynamicInvocation(arguments, diagnostics); var refKindsArray = arguments.RefKinds.ToImmutableOrNull(); hasErrors &= ReportBadDynamicArguments(node, argArray, refKindsArray, diagnostics, queryClause); return new BoundDynamicInvocation( node, arguments.GetNames(), refKindsArray, applicableMethods, expression, argArray, type: Compilation.DynamicType, hasErrors: hasErrors); } private void CheckNamedArgumentsForDynamicInvocation(AnalyzedArguments arguments, BindingDiagnosticBag diagnostics) { if (arguments.Names.Count == 0) { return; } if (!Compilation.LanguageVersion.AllowNonTrailingNamedArguments()) { return; } bool seenName = false; for (int i = 0; i < arguments.Names.Count; i++) { if (arguments.Names[i] != null) { seenName = true; } else if (seenName) { Error(diagnostics, ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgumentInDynamicInvocation, arguments.Arguments[i].Syntax); return; } } } private ImmutableArray<BoundExpression> BuildArgumentsForDynamicInvocation(AnalyzedArguments arguments, BindingDiagnosticBag diagnostics) { var builder = ArrayBuilder<BoundExpression>.GetInstance(arguments.Arguments.Count); builder.AddRange(arguments.Arguments); for (int i = 0, n = builder.Count; i < n; i++) { builder[i] = builder[i] switch { OutVariablePendingInference outvar => outvar.FailInference(this, diagnostics), BoundDiscardExpression discard when !discard.HasExpressionType() => discard.FailInference(this, diagnostics), var arg => BindToNaturalType(arg, diagnostics) }; } return builder.ToImmutableAndFree(); } // Returns true if there were errors. private static bool ReportBadDynamicArguments( SyntaxNode node, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKinds, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause) { bool hasErrors = false; bool reportedBadQuery = false; if (!refKinds.IsDefault) { for (int argIndex = 0; argIndex < refKinds.Length; argIndex++) { if (refKinds[argIndex] == RefKind.In) { Error(diagnostics, ErrorCode.ERR_InDynamicMethodArg, arguments[argIndex].Syntax); hasErrors = true; } } } foreach (var arg in arguments) { if (!IsLegalDynamicOperand(arg)) { if (queryClause != null && !reportedBadQuery) { reportedBadQuery = true; Error(diagnostics, ErrorCode.ERR_BadDynamicQuery, node); hasErrors = true; continue; } if (arg.Kind == BoundKind.Lambda || arg.Kind == BoundKind.UnboundLambda) { // Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArgLambda, arg.Syntax); hasErrors = true; } else if (arg.Kind == BoundKind.MethodGroup) { // Cannot use a method group as an argument to a dynamically dispatched operation. Did you intend to invoke the method? Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArgMemgrp, arg.Syntax); hasErrors = true; } else if (arg.Kind == BoundKind.ArgListOperator) { // Not a great error message, since __arglist is not a type, but it'll do. // error CS1978: Cannot use an expression of type '__arglist' as an argument to a dynamically dispatched operation Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArg, arg.Syntax, "__arglist"); } else { // Lambdas,anonymous methods and method groups are the typeless expressions that // are not usable as dynamic arguments; if we get here then the expression must have a type. Debug.Assert((object)arg.Type != null); // error CS1978: Cannot use an expression of type 'int*' as an argument to a dynamically dispatched operation Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArg, arg.Syntax, arg.Type); hasErrors = true; } } } return hasErrors; } private BoundExpression BindDelegateInvocation( SyntaxNode node, SyntaxNode expression, string methodName, BoundExpression boundExpression, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause, NamedTypeSymbol delegateType) { BoundExpression result; var methodGroup = MethodGroup.GetInstance(); methodGroup.PopulateWithSingleMethod(boundExpression, delegateType.DelegateInvokeMethod); var overloadResolutionResult = OverloadResolutionResult<MethodSymbol>.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); OverloadResolution.MethodInvocationOverloadResolution( methods: methodGroup.Methods, typeArguments: methodGroup.TypeArguments, receiver: methodGroup.Receiver, arguments: analyzedArguments, result: overloadResolutionResult, useSiteInfo: ref useSiteInfo); diagnostics.Add(node, useSiteInfo); // If overload resolution on the "Invoke" method found an applicable candidate, and one of the arguments // was dynamic then treat this as a dynamic call. if (analyzedArguments.HasDynamicArgument && overloadResolutionResult.HasAnyApplicableMember) { result = BindDynamicInvocation(node, boundExpression, analyzedArguments, overloadResolutionResult.GetAllApplicableMembers(), diagnostics, queryClause); } else { result = BindInvocationExpressionContinued(node, expression, methodName, overloadResolutionResult, analyzedArguments, methodGroup, delegateType, diagnostics, queryClause); } overloadResolutionResult.Free(); methodGroup.Free(); return result; } private static bool HasApplicableConditionalMethod(OverloadResolutionResult<MethodSymbol> results) { var r = results.Results; for (int i = 0; i < r.Length; ++i) { if (r[i].IsApplicable && r[i].Member.IsConditional) { return true; } } return false; } private BoundExpression BindMethodGroupInvocation( SyntaxNode syntax, SyntaxNode expression, string methodName, BoundMethodGroup methodGroup, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause, bool allowUnexpandedForm, out bool anyApplicableCandidates) { BoundExpression result; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var resolution = this.ResolveMethodGroup( methodGroup, expression, methodName, analyzedArguments, isMethodGroupConversion: false, useSiteInfo: ref useSiteInfo, allowUnexpandedForm: allowUnexpandedForm); diagnostics.Add(expression, useSiteInfo); anyApplicableCandidates = resolution.ResultKind == LookupResultKind.Viable && resolution.OverloadResolutionResult.HasAnyApplicableMember; if (!methodGroup.HasAnyErrors) diagnostics.AddRange(resolution.Diagnostics); // Suppress cascading. if (resolution.HasAnyErrors) { ImmutableArray<MethodSymbol> originalMethods; LookupResultKind resultKind; ImmutableArray<TypeWithAnnotations> typeArguments; if (resolution.OverloadResolutionResult != null) { originalMethods = GetOriginalMethods(resolution.OverloadResolutionResult); resultKind = resolution.MethodGroup.ResultKind; typeArguments = resolution.MethodGroup.TypeArguments.ToImmutable(); } else { originalMethods = methodGroup.Methods; resultKind = methodGroup.ResultKind; typeArguments = methodGroup.TypeArgumentsOpt; } result = CreateBadCall( syntax, methodName, methodGroup.ReceiverOpt, originalMethods, resultKind, typeArguments, analyzedArguments, invokedAsExtensionMethod: resolution.IsExtensionMethodGroup, isDelegate: false); } else if (!resolution.IsEmpty) { // We're checking resolution.ResultKind, rather than methodGroup.HasErrors // to better handle the case where there's a problem with the receiver // (e.g. inaccessible), but the method group resolved correctly (e.g. because // it's actually an accessible static method on a base type). // CONSIDER: could check for error types amongst method group type arguments. if (resolution.ResultKind != LookupResultKind.Viable) { if (resolution.MethodGroup != null) { // we want to force any unbound lambda arguments to cache an appropriate conversion if possible; see 9448. result = BindInvocationExpressionContinued( syntax, expression, methodName, resolution.OverloadResolutionResult, resolution.AnalyzedArguments, resolution.MethodGroup, delegateTypeOpt: null, diagnostics: BindingDiagnosticBag.Discarded, queryClause: queryClause); } // Since the resolution is non-empty and has no diagnostics, the LookupResultKind in its MethodGroup is uninteresting. result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments); } else { // If overload resolution found one or more applicable methods and at least one argument // was dynamic then treat this as a dynamic call. if (resolution.AnalyzedArguments.HasDynamicArgument && resolution.OverloadResolutionResult.HasAnyApplicableMember) { if (resolution.IsLocalFunctionInvocation) { result = BindLocalFunctionInvocationWithDynamicArgument( syntax, expression, methodName, methodGroup, diagnostics, queryClause, resolution); } else if (resolution.IsExtensionMethodGroup) { // error CS1973: 'T' has no applicable method named 'M' 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. // We found an extension method, so the instance associated with the method group must have // existed and had a type. Debug.Assert(methodGroup.InstanceOpt != null && (object)methodGroup.InstanceOpt.Type != null); Error(diagnostics, ErrorCode.ERR_BadArgTypeDynamicExtension, syntax, methodGroup.InstanceOpt.Type, methodGroup.Name); result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments); } else { if (HasApplicableConditionalMethod(resolution.OverloadResolutionResult)) { // warning CS1974: The dynamically dispatched call to method 'Goo' may fail at runtime // because one or more applicable overloads are conditional methods Error(diagnostics, ErrorCode.WRN_DynamicDispatchToConditionalMethod, syntax, methodGroup.Name); } // Note that the runtime binder may consider candidates that haven't passed compile-time final validation // and an ambiguity error may be reported. Also additional checks are performed in runtime final validation // that are not performed at compile-time. // Only if the set of final applicable candidates is empty we know for sure the call will fail at runtime. var finalApplicableCandidates = GetCandidatesPassingFinalValidation(syntax, resolution.OverloadResolutionResult, methodGroup.ReceiverOpt, methodGroup.TypeArgumentsOpt, diagnostics); if (finalApplicableCandidates.Length > 0) { result = BindDynamicInvocation(syntax, methodGroup, resolution.AnalyzedArguments, finalApplicableCandidates, diagnostics, queryClause); } else { result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments); } } } else { result = BindInvocationExpressionContinued( syntax, expression, methodName, resolution.OverloadResolutionResult, resolution.AnalyzedArguments, resolution.MethodGroup, delegateTypeOpt: null, diagnostics: diagnostics, queryClause: queryClause); } } } else { result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments); } resolution.Free(); return result; } private BoundExpression BindLocalFunctionInvocationWithDynamicArgument( SyntaxNode syntax, SyntaxNode expression, string methodName, BoundMethodGroup boundMethodGroup, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause, MethodGroupResolution resolution) { // Invocations of local functions with dynamic arguments don't need // to be dispatched as dynamic invocations since they cannot be // overloaded. Instead, we'll just emit a standard call with // dynamic implicit conversions for any dynamic arguments. There // are two exceptions: "params", and unconstructed generics. While // implementing those cases with dynamic invocations is possible, // we have decided the implementation complexity is not worth it. // Refer to the comments below for the exact semantics. Debug.Assert(resolution.IsLocalFunctionInvocation); Debug.Assert(resolution.OverloadResolutionResult.Succeeded); Debug.Assert(queryClause == null); var validResult = resolution.OverloadResolutionResult.ValidResult; var args = resolution.AnalyzedArguments.Arguments.ToImmutable(); var refKindsArray = resolution.AnalyzedArguments.RefKinds.ToImmutableOrNull(); ReportBadDynamicArguments(syntax, args, refKindsArray, diagnostics, queryClause); var localFunction = validResult.Member; var methodResult = validResult.Result; // We're only in trouble if a dynamic argument is passed to the // params parameter and is ambiguous at compile time between normal // and expanded form i.e., there is exactly one dynamic argument to // a params parameter // See https://github.com/dotnet/roslyn/issues/10708 if (OverloadResolution.IsValidParams(localFunction) && methodResult.Kind == MemberResolutionKind.ApplicableInNormalForm) { var parameters = localFunction.Parameters; Debug.Assert(parameters.Last().IsParams); var lastParamIndex = parameters.Length - 1; for (int i = 0; i < args.Length; ++i) { var arg = args[i]; if (arg.HasDynamicType() && methodResult.ParameterFromArgument(i) == lastParamIndex) { Error(diagnostics, ErrorCode.ERR_DynamicLocalFunctionParamsParameter, syntax, parameters.Last().Name, localFunction.Name); return BindDynamicInvocation( syntax, boundMethodGroup, resolution.AnalyzedArguments, resolution.OverloadResolutionResult.GetAllApplicableMembers(), diagnostics, queryClause); } } } // If we call an unconstructed generic local function with a // dynamic argument in a place where it influences the type // parameters, we need to dynamically dispatch the call (as the // function must be constructed at runtime). We cannot do that, so // disallow that. However, doing a specific analysis of each // argument and its corresponding parameter to check if it's // generic (and allow dynamic in non-generic parameters) may break // overload resolution in the future, if we ever allow overloaded // local functions. So, just disallow any mixing of dynamic and // inferred generics. (Explicit generic arguments are fine) // See https://github.com/dotnet/roslyn/issues/21317 if (boundMethodGroup.TypeArgumentsOpt.IsDefaultOrEmpty && localFunction.IsGenericMethod) { Error(diagnostics, ErrorCode.ERR_DynamicLocalFunctionTypeParameter, syntax, localFunction.Name); return BindDynamicInvocation( syntax, boundMethodGroup, resolution.AnalyzedArguments, resolution.OverloadResolutionResult.GetAllApplicableMembers(), diagnostics, queryClause); } return BindInvocationExpressionContinued( node: syntax, expression: expression, methodName: methodName, result: resolution.OverloadResolutionResult, analyzedArguments: resolution.AnalyzedArguments, methodGroup: resolution.MethodGroup, delegateTypeOpt: null, diagnostics: diagnostics, queryClause: queryClause); } private ImmutableArray<TMethodOrPropertySymbol> GetCandidatesPassingFinalValidation<TMethodOrPropertySymbol>( SyntaxNode syntax, OverloadResolutionResult<TMethodOrPropertySymbol> overloadResolutionResult, BoundExpression receiverOpt, ImmutableArray<TypeWithAnnotations> typeArgumentsOpt, BindingDiagnosticBag diagnostics) where TMethodOrPropertySymbol : Symbol { Debug.Assert(overloadResolutionResult.HasAnyApplicableMember); var finalCandidates = ArrayBuilder<TMethodOrPropertySymbol>.GetInstance(); BindingDiagnosticBag firstFailed = null; var candidateDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); for (int i = 0, n = overloadResolutionResult.ResultsBuilder.Count; i < n; i++) { var result = overloadResolutionResult.ResultsBuilder[i]; if (result.Result.IsApplicable) { // For F to pass the check, all of the following must hold: // ... // * If the type parameters of F were substituted in the step above, their constraints are satisfied. // * If F is a static method, the method group must have resulted from a simple-name, a member-access through a type, // or a member-access whose receiver can't be classified as a type or value until after overload resolution (see §7.6.4.1). // * If F is an instance method, the method group must have resulted from a simple-name, a member-access through a variable or value, // or a member-access whose receiver can't be classified as a type or value until after overload resolution (see §7.6.4.1). if (!MemberGroupFinalValidationAccessibilityChecks(receiverOpt, result.Member, syntax, candidateDiagnostics, invokedAsExtensionMethod: false) && (typeArgumentsOpt.IsDefault || ((MethodSymbol)(object)result.Member).CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(this.Compilation, this.Conversions, includeNullability: false, syntax.Location, candidateDiagnostics)))) { finalCandidates.Add(result.Member); continue; } if (firstFailed == null) { firstFailed = candidateDiagnostics; candidateDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); } else { candidateDiagnostics.Clear(); } } } if (firstFailed != null) { // Report diagnostics of the first candidate that failed the validation // unless we have at least one candidate that passes. if (finalCandidates.Count == 0) { diagnostics.AddRange(firstFailed); } firstFailed.Free(); } candidateDiagnostics.Free(); return finalCandidates.ToImmutableAndFree(); } private void CheckRestrictedTypeReceiver(BoundExpression expression, CSharpCompilation compilation, BindingDiagnosticBag diagnostics) { Debug.Assert(diagnostics != null); // It is never legal to box a restricted type, even if we are boxing it as the receiver // of a method call. When must be box? We skip boxing when the method in question is defined // on the restricted type or overridden by the restricted type. switch (expression.Kind) { case BoundKind.Call: { var call = (BoundCall)expression; if (!call.HasAnyErrors && call.ReceiverOpt != null && (object)call.ReceiverOpt.Type != null) { // error CS0029: Cannot implicitly convert type 'A' to 'B' // Case 1: receiver is a restricted type, and method called is defined on a parent type if (call.ReceiverOpt.Type.IsRestrictedType() && !TypeSymbol.Equals(call.Method.ContainingType, call.ReceiverOpt.Type, TypeCompareKind.ConsiderEverything2)) { SymbolDistinguisher distinguisher = new SymbolDistinguisher(compilation, call.ReceiverOpt.Type, call.Method.ContainingType); Error(diagnostics, ErrorCode.ERR_NoImplicitConv, call.ReceiverOpt.Syntax, distinguisher.First, distinguisher.Second); } // Case 2: receiver is a base reference, and the child type is restricted else if (call.ReceiverOpt.Kind == BoundKind.BaseReference && this.ContainingType.IsRestrictedType()) { SymbolDistinguisher distinguisher = new SymbolDistinguisher(compilation, this.ContainingType, call.Method.ContainingType); Error(diagnostics, ErrorCode.ERR_NoImplicitConv, call.ReceiverOpt.Syntax, distinguisher.First, distinguisher.Second); } } } break; case BoundKind.DynamicInvocation: { var dynInvoke = (BoundDynamicInvocation)expression; if (!dynInvoke.HasAnyErrors && (object)dynInvoke.Expression.Type != null && dynInvoke.Expression.Type.IsRestrictedType()) { // eg: b = typedReference.Equals(dyn); // error CS1978: Cannot use an expression of type 'TypedReference' as an argument to a dynamically dispatched operation Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArg, dynInvoke.Expression.Syntax, dynInvoke.Expression.Type); } } break; case BoundKind.FunctionPointerInvocation: break; default: throw ExceptionUtilities.UnexpectedValue(expression.Kind); } } /// <summary> /// Perform overload resolution on the method group or expression (BoundMethodGroup) /// and arguments and return a BoundExpression representing the invocation. /// </summary> /// <param name="node">Invocation syntax node.</param> /// <param name="expression">The syntax for the invoked method, including receiver.</param> /// <param name="methodName">Name of the invoked method.</param> /// <param name="result">Overload resolution result for method group executed by caller.</param> /// <param name="analyzedArguments">Arguments bound by the caller.</param> /// <param name="methodGroup">Method group if the invocation represents a potentially overloaded member.</param> /// <param name="delegateTypeOpt">Delegate type if method group represents a delegate.</param> /// <param name="diagnostics">Diagnostics.</param> /// <param name="queryClause">The syntax for the query clause generating this invocation expression, if any.</param> /// <returns>BoundCall or error expression representing the invocation.</returns> private BoundCall BindInvocationExpressionContinued( SyntaxNode node, SyntaxNode expression, string methodName, OverloadResolutionResult<MethodSymbol> result, AnalyzedArguments analyzedArguments, MethodGroup methodGroup, NamedTypeSymbol delegateTypeOpt, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause = null) { Debug.Assert(node != null); Debug.Assert(methodGroup != null); Debug.Assert(methodGroup.Error == null); Debug.Assert(methodGroup.Methods.Count > 0); Debug.Assert(((object)delegateTypeOpt == null) || (methodGroup.Methods.Count == 1)); var invokedAsExtensionMethod = methodGroup.IsExtensionMethodGroup; // Delegate invocations should never be considered extension method // invocations (even though the delegate may refer to an extension method). Debug.Assert(!invokedAsExtensionMethod || ((object)delegateTypeOpt == null)); // We have already determined that we are not in a situation where we can successfully do // a dynamic binding. We might be in one of the following situations: // // * There were dynamic arguments but overload resolution still found zero applicable candidates. // * There were no dynamic arguments and overload resolution found zero applicable candidates. // * There were no dynamic arguments and overload resolution found multiple applicable candidates // without being able to find the best one. // // In those three situations we might give an additional error. if (!result.Succeeded) { if (analyzedArguments.HasErrors) { // Errors for arguments have already been reported, except for unbound lambdas and switch expressions. // We report those now. foreach (var argument in analyzedArguments.Arguments) { switch (argument) { case UnboundLambda unboundLambda: var boundWithErrors = unboundLambda.BindForErrorRecovery(); diagnostics.AddRange(boundWithErrors.Diagnostics); break; case BoundUnconvertedObjectCreationExpression _: case BoundTupleLiteral _: // Tuple literals can contain unbound lambdas or switch expressions. _ = BindToNaturalType(argument, diagnostics); break; case BoundUnconvertedSwitchExpression { Type: { } naturalType } switchExpr: _ = ConvertSwitchExpression(switchExpr, naturalType, conversionIfTargetTyped: null, diagnostics); break; case BoundUnconvertedConditionalOperator { Type: { } naturalType } conditionalExpr: _ = ConvertConditionalExpression(conditionalExpr, naturalType, conversionIfTargetTyped: null, diagnostics); break; } } } else { // Since there were no argument errors to report, we report an error on the invocation itself. string name = (object)delegateTypeOpt == null ? methodName : null; result.ReportDiagnostics( binder: this, location: GetLocationForOverloadResolutionDiagnostic(node, expression), nodeOpt: node, diagnostics: diagnostics, name: name, receiver: methodGroup.Receiver, invokedExpression: expression, arguments: analyzedArguments, memberGroup: methodGroup.Methods.ToImmutable(), typeContainingConstructor: null, delegateTypeBeingInvoked: delegateTypeOpt, queryClause: queryClause); } return CreateBadCall(node, methodGroup.Name, invokedAsExtensionMethod && analyzedArguments.Arguments.Count > 0 && (object)methodGroup.Receiver == (object)analyzedArguments.Arguments[0] ? null : methodGroup.Receiver, GetOriginalMethods(result), methodGroup.ResultKind, methodGroup.TypeArguments.ToImmutable(), analyzedArguments, invokedAsExtensionMethod: invokedAsExtensionMethod, isDelegate: ((object)delegateTypeOpt != null)); } // Otherwise, there were no dynamic arguments and overload resolution found a unique best candidate. // We still have to determine if it passes final validation. var methodResult = result.ValidResult; var returnType = methodResult.Member.ReturnType; var method = methodResult.Member; // It is possible that overload resolution succeeded, but we have chosen an // instance method and we're in a static method. A careful reading of the // overload resolution spec shows that the "final validation" stage allows an // "implicit this" on any method call, not just method calls from inside // instance methods. Therefore we must detect this scenario here, rather than in // overload resolution. var receiver = ReplaceTypeOrValueReceiver(methodGroup.Receiver, !method.RequiresInstanceReceiver && !invokedAsExtensionMethod, diagnostics); var receiverRefKind = receiver?.GetRefKind(); uint receiverValEscapeScope = method.RequiresInstanceReceiver && receiver != null ? receiverRefKind?.IsWritableReference() == true ? GetRefEscape(receiver, LocalScopeDepth) : GetValEscape(receiver, LocalScopeDepth) : Binder.ExternalScope; this.CoerceArguments(methodResult, analyzedArguments.Arguments, diagnostics, receiver?.Type, receiverRefKind, receiverValEscapeScope); var expanded = methodResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm; var argsToParams = methodResult.Result.ArgsToParamsOpt; BindDefaultArguments(node, method.Parameters, analyzedArguments.Arguments, analyzedArguments.RefKinds, ref argsToParams, out var defaultArguments, expanded, enableCallerInfo: true, diagnostics); // Note: we specifically want to do final validation (7.6.5.1) without checking delegate compatibility (15.2), // so we're calling MethodGroupFinalValidation directly, rather than via MethodGroupConversionHasErrors. // Note: final validation wants the receiver that corresponds to the source representation // (i.e. the first argument, if invokedAsExtensionMethod). var gotError = MemberGroupFinalValidation(receiver, method, expression, diagnostics, invokedAsExtensionMethod); CheckImplicitThisCopyInReadOnlyMember(receiver, method, diagnostics); if (invokedAsExtensionMethod) { BoundExpression receiverArgument = analyzedArguments.Argument(0); ParameterSymbol receiverParameter = method.Parameters.First(); // we will have a different receiver if ReplaceTypeOrValueReceiver has unwrapped TypeOrValue if ((object)receiver != receiverArgument) { // Because the receiver didn't pass through CoerceArguments, we need to apply an appropriate conversion here. Debug.Assert(argsToParams.IsDefault || argsToParams[0] == 0); receiverArgument = CreateConversion(receiver, methodResult.Result.ConversionForArg(0), receiverParameter.Type, diagnostics); } if (receiverParameter.RefKind == RefKind.Ref) { // If this was a ref extension method, receiverArgument must be checked for L-value constraints. // This helper method will also replace it with a BoundBadExpression if it was invalid. receiverArgument = CheckValue(receiverArgument, BindValueKind.RefOrOut, diagnostics); if (analyzedArguments.RefKinds.Count == 0) { analyzedArguments.RefKinds.Count = analyzedArguments.Arguments.Count; } // receiver of a `ref` extension method is a `ref` argument. (and we have checked above that it can be passed as a Ref) // we need to adjust the argument refkind as if we had a `ref` modifier in a call. analyzedArguments.RefKinds[0] = RefKind.Ref; CheckFeatureAvailability(receiverArgument.Syntax, MessageID.IDS_FeatureRefExtensionMethods, diagnostics); } else if (receiverParameter.RefKind == RefKind.In) { // NB: receiver of an `in` extension method is treated as a `byval` argument, so no changes from the default refkind is needed in that case. Debug.Assert(analyzedArguments.RefKind(0) == RefKind.None); CheckFeatureAvailability(receiverArgument.Syntax, MessageID.IDS_FeatureRefExtensionMethods, diagnostics); } analyzedArguments.Arguments[0] = receiverArgument; } // This will be the receiver of the BoundCall node that we create. // For extension methods, there is no receiver because the receiver in source was actually the first argument. // For instance methods, we may have synthesized an implicit this node. We'll keep it for the emitter. // For static methods, we may have synthesized a type expression. It serves no purpose, so we'll drop it. if (invokedAsExtensionMethod || (!method.RequiresInstanceReceiver && receiver != null && receiver.WasCompilerGenerated)) { receiver = null; } var argNames = analyzedArguments.GetNames(); var argRefKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); var args = analyzedArguments.Arguments.ToImmutable(); if (!gotError && method.RequiresInstanceReceiver && receiver != null && receiver.Kind == BoundKind.ThisReference && receiver.WasCompilerGenerated) { gotError = IsRefOrOutThisParameterCaptured(node, diagnostics); } // What if some of the arguments are implicit? Dev10 reports unsafe errors // if the implied argument would have an unsafe type. We need to check // the parameters explicitly, since there won't be bound nodes for the implied // arguments until lowering. if (method.HasUnsafeParameter()) { // Don't worry about double reporting (i.e. for both the argument and the parameter) // because only one unsafe diagnostic is allowed per scope - the others are suppressed. gotError = ReportUnsafeIfNotAllowed(node, diagnostics) || gotError; } bool hasBaseReceiver = receiver != null && receiver.Kind == BoundKind.BaseReference; ReportDiagnosticsIfObsolete(diagnostics, method, node, hasBaseReceiver); ReportDiagnosticsIfUnmanagedCallersOnly(diagnostics, method, node.Location, isDelegateConversion: false); // No use site errors, but there could be use site warnings. // If there are any use site warnings, they have already been reported by overload resolution. Debug.Assert(!method.HasUseSiteError, "Shouldn't have reached this point if there were use site errors."); if (method.IsRuntimeFinalizer()) { ErrorCode code = hasBaseReceiver ? ErrorCode.ERR_CallingBaseFinalizeDeprecated : ErrorCode.ERR_CallingFinalizeDeprecated; Error(diagnostics, code, node); gotError = true; } Debug.Assert(args.IsDefaultOrEmpty || (object)receiver != (object)args[0]); if (!gotError) { gotError = !CheckInvocationArgMixing( node, method, receiver, method.Parameters, args, argsToParams, this.LocalScopeDepth, diagnostics); } bool isDelegateCall = (object)delegateTypeOpt != null; if (!isDelegateCall) { if (method.RequiresInstanceReceiver) { WarnOnAccessOfOffDefault(node.Kind() == SyntaxKind.InvocationExpression ? ((InvocationExpressionSyntax)node).Expression : node, receiver, diagnostics); } } return new BoundCall(node, receiver, method, args, argNames, argRefKinds, isDelegateCall: isDelegateCall, expanded: expanded, invokedAsExtensionMethod: invokedAsExtensionMethod, argsToParamsOpt: argsToParams, defaultArguments, resultKind: LookupResultKind.Viable, type: returnType, hasErrors: gotError); } #nullable enable private static SourceLocation GetCallerLocation(SyntaxNode syntax) { var token = syntax switch { InvocationExpressionSyntax invocation => invocation.ArgumentList.OpenParenToken, BaseObjectCreationExpressionSyntax objectCreation => objectCreation.NewKeyword, ConstructorInitializerSyntax constructorInitializer => constructorInitializer.ArgumentList.OpenParenToken, PrimaryConstructorBaseTypeSyntax primaryConstructorBaseType => primaryConstructorBaseType.ArgumentList.OpenParenToken, ElementAccessExpressionSyntax elementAccess => elementAccess.ArgumentList.OpenBracketToken, _ => syntax.GetFirstToken() }; return new SourceLocation(token); } private BoundExpression GetDefaultParameterSpecialNoConversion(SyntaxNode syntax, ParameterSymbol parameter, BindingDiagnosticBag diagnostics) { var parameterType = parameter.Type; Debug.Assert(parameterType.IsDynamic() || parameterType.SpecialType == SpecialType.System_Object); // We have a call to a method M([Optional] object x) which omits the argument. The value we generate // for the argument depends on the presence or absence of other attributes. The rules are: // // * If the parameter is marked as [MarshalAs(Interface)], [MarshalAs(IUnknown)] or [MarshalAs(IDispatch)] // then the argument is null. // * Otherwise, if the parameter is marked as [IUnknownConstant] then the argument is // new UnknownWrapper(null) // * Otherwise, if the parameter is marked as [IDispatchConstant] then the argument is // new DispatchWrapper(null) // * Otherwise, the argument is Type.Missing. BoundExpression? defaultValue = null; if (parameter.IsMarshalAsObject) { // default(object) defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; } else if (parameter.IsIUnknownConstant) { if (GetWellKnownTypeMember(Compilation, WellKnownMember.System_Runtime_InteropServices_UnknownWrapper__ctor, diagnostics, syntax: syntax) is MethodSymbol methodSymbol) { // new UnknownWrapper(default(object)) var unknownArgument = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; defaultValue = new BoundObjectCreationExpression(syntax, methodSymbol, unknownArgument) { WasCompilerGenerated = true }; } } else if (parameter.IsIDispatchConstant) { if (GetWellKnownTypeMember(Compilation, WellKnownMember.System_Runtime_InteropServices_DispatchWrapper__ctor, diagnostics, syntax: syntax) is MethodSymbol methodSymbol) { // new DispatchWrapper(default(object)) var dispatchArgument = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; defaultValue = new BoundObjectCreationExpression(syntax, methodSymbol, dispatchArgument) { WasCompilerGenerated = true }; } } else { if (GetWellKnownTypeMember(Compilation, WellKnownMember.System_Type__Missing, diagnostics, syntax: syntax) is FieldSymbol fieldSymbol) { // Type.Missing defaultValue = new BoundFieldAccess(syntax, null, fieldSymbol, ConstantValue.NotAvailable) { WasCompilerGenerated = true }; } } return defaultValue ?? BadExpression(syntax).MakeCompilerGenerated(); } internal static ParameterSymbol? GetCorrespondingParameter( int argumentOrdinal, ImmutableArray<ParameterSymbol> parameters, ImmutableArray<int> argsToParamsOpt, bool expanded) { int n = parameters.Length; ParameterSymbol? parameter; if (argsToParamsOpt.IsDefault) { if (argumentOrdinal < n) { parameter = parameters[argumentOrdinal]; } else if (expanded) { parameter = parameters[n - 1]; } else { parameter = null; } } else { Debug.Assert(argumentOrdinal < argsToParamsOpt.Length); int parameterOrdinal = argsToParamsOpt[argumentOrdinal]; if (parameterOrdinal < n) { parameter = parameters[parameterOrdinal]; } else { parameter = null; } } return parameter; } internal void BindDefaultArguments( SyntaxNode node, ImmutableArray<ParameterSymbol> parameters, ArrayBuilder<BoundExpression> argumentsBuilder, ArrayBuilder<RefKind>? argumentRefKindsBuilder, ref ImmutableArray<int> argsToParamsOpt, out BitVector defaultArguments, bool expanded, bool enableCallerInfo, BindingDiagnosticBag diagnostics, bool assertMissingParametersAreOptional = true) { var visitedParameters = BitVector.Create(parameters.Length); for (var i = 0; i < argumentsBuilder.Count; i++) { var parameter = GetCorrespondingParameter(i, parameters, argsToParamsOpt, expanded); if (parameter is not null) { visitedParameters[parameter.Ordinal] = true; } } // only proceed with binding default arguments if we know there is some parameter that has not been matched by an explicit argument if (parameters.All(static (param, visitedParameters) => visitedParameters[param.Ordinal], visitedParameters)) { defaultArguments = default; return; } // In a scenario like `string Prop { get; } = M();`, the containing symbol could be the synthesized field. // We want to use the associated user-declared symbol instead where possible. var containingMember = ContainingMember() switch { FieldSymbol { AssociatedSymbol: { } symbol } => symbol, var c => c }; defaultArguments = BitVector.Create(parameters.Length); ArrayBuilder<int>? argsToParamsBuilder = null; if (!argsToParamsOpt.IsDefault) { argsToParamsBuilder = ArrayBuilder<int>.GetInstance(argsToParamsOpt.Length); argsToParamsBuilder.AddRange(argsToParamsOpt); } // Params methods can be invoked in normal form, so the strongest assertion we can make is that, if // we're in an expanded context, the last param must be params. The inverse is not necessarily true. Debug.Assert(!expanded || parameters[^1].IsParams); // Params array is filled in the local rewriter var lastIndex = expanded ? ^1 : ^0; var argumentsCount = argumentsBuilder.Count; // Go over missing parameters, inserting default values for optional parameters foreach (var parameter in parameters.AsSpan()[..lastIndex]) { if (!visitedParameters[parameter.Ordinal]) { Debug.Assert(parameter.IsOptional || !assertMissingParametersAreOptional); defaultArguments[argumentsBuilder.Count] = true; argumentsBuilder.Add(bindDefaultArgument(node, parameter, containingMember, enableCallerInfo, diagnostics, argumentsBuilder, argumentsCount, argsToParamsOpt)); if (argumentRefKindsBuilder is { Count: > 0 }) { argumentRefKindsBuilder.Add(RefKind.None); } argsToParamsBuilder?.Add(parameter.Ordinal); } } Debug.Assert(argumentRefKindsBuilder is null || argumentRefKindsBuilder.Count == 0 || argumentRefKindsBuilder.Count == argumentsBuilder.Count); Debug.Assert(argsToParamsBuilder is null || argsToParamsBuilder.Count == argumentsBuilder.Count); if (argsToParamsBuilder is object) { argsToParamsOpt = argsToParamsBuilder.ToImmutableOrNull(); argsToParamsBuilder.Free(); } BoundExpression bindDefaultArgument(SyntaxNode syntax, ParameterSymbol parameter, Symbol containingMember, bool enableCallerInfo, BindingDiagnosticBag diagnostics, ArrayBuilder<BoundExpression> argumentsBuilder, int argumentsCount, ImmutableArray<int> argsToParamsOpt) { TypeSymbol parameterType = parameter.Type; if (Flags.Includes(BinderFlags.ParameterDefaultValue)) { // This is only expected to occur in recursive error scenarios, for example: `object F(object param = F()) { }` // We return a non-error expression here to ensure ERR_DefaultValueMustBeConstant (or another appropriate diagnostics) is produced by the caller. return new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; } var defaultConstantValue = parameter.ExplicitDefaultConstantValue switch { // Bad default values are implicitly replaced with default(T) at call sites. { IsBad: true } => ConstantValue.Null, var constantValue => constantValue }; Debug.Assert((object?)defaultConstantValue != ConstantValue.Unset); var callerSourceLocation = enableCallerInfo ? GetCallerLocation(syntax) : null; BoundExpression defaultValue; if (callerSourceLocation is object && parameter.IsCallerLineNumber) { int line = callerSourceLocation.SourceTree.GetDisplayLineNumber(callerSourceLocation.SourceSpan); defaultValue = new BoundLiteral(syntax, ConstantValue.Create(line), Compilation.GetSpecialType(SpecialType.System_Int32)) { WasCompilerGenerated = true }; } else if (callerSourceLocation is object && parameter.IsCallerFilePath) { string path = callerSourceLocation.SourceTree.GetDisplayPath(callerSourceLocation.SourceSpan, Compilation.Options.SourceReferenceResolver); defaultValue = new BoundLiteral(syntax, ConstantValue.Create(path), Compilation.GetSpecialType(SpecialType.System_String)) { WasCompilerGenerated = true }; } else if (callerSourceLocation is object && parameter.IsCallerMemberName) { var memberName = containingMember.GetMemberCallerName(); defaultValue = new BoundLiteral(syntax, ConstantValue.Create(memberName), Compilation.GetSpecialType(SpecialType.System_String)) { WasCompilerGenerated = true }; } else if (callerSourceLocation is object && getArgumentIndex(parameter.CallerArgumentExpressionParameterIndex, argsToParamsOpt) is int argumentIndex && argumentIndex > -1 && argumentIndex < argumentsCount) { var argument = argumentsBuilder[argumentIndex]; defaultValue = new BoundLiteral(syntax, ConstantValue.Create(argument.Syntax.ToString()), Compilation.GetSpecialType(SpecialType.System_String)) { WasCompilerGenerated = true }; } else if (defaultConstantValue == ConstantValue.NotAvailable) { // There is no constant value given for the parameter in source/metadata. if (parameterType.IsDynamic() || parameterType.SpecialType == SpecialType.System_Object) { // We have something like M([Optional] object x). We have special handling for such situations. defaultValue = GetDefaultParameterSpecialNoConversion(syntax, parameter, diagnostics); } else { // The argument to M([Optional] int x) becomes default(int) defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; } } else if (defaultConstantValue.IsNull) { defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; } else { TypeSymbol constantType = Compilation.GetSpecialType(defaultConstantValue.SpecialType); defaultValue = new BoundLiteral(syntax, defaultConstantValue, constantType) { WasCompilerGenerated = true }; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = Conversions.ClassifyConversionFromExpression(defaultValue, parameterType, ref useSiteInfo); diagnostics.Add(syntax, useSiteInfo); if (!conversion.IsValid && defaultConstantValue is { SpecialType: SpecialType.System_Decimal or SpecialType.System_DateTime }) { // Usually, if a default constant value fails to convert to the parameter type, we want an error at the call site. // For legacy reasons, decimal and DateTime constants are special. If such a constant fails to convert to the parameter type // then we want to silently replace it with default(ParameterType). defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; } else { if (!conversion.IsValid) { GenerateImplicitConversionError(diagnostics, syntax, conversion, defaultValue, parameterType); } var isCast = conversion.IsExplicit; defaultValue = CreateConversion( defaultValue.Syntax, defaultValue, conversion, isCast, isCast ? new ConversionGroup(conversion, parameter.TypeWithAnnotations) : null, parameterType, diagnostics); } return defaultValue; static int getArgumentIndex(int parameterIndex, ImmutableArray<int> argsToParamsOpt) => argsToParamsOpt.IsDefault ? parameterIndex : argsToParamsOpt.IndexOf(parameterIndex); } } #nullable disable /// <summary> /// Returns false if an implicit 'this' copy will occur due to an instance member invocation in a readonly member. /// </summary> internal bool CheckImplicitThisCopyInReadOnlyMember(BoundExpression receiver, MethodSymbol method, BindingDiagnosticBag diagnostics) { // For now we are warning only in implicit copy scenarios that are only possible with readonly members. // Eventually we will warn on implicit value copies in more scenarios. See https://github.com/dotnet/roslyn/issues/33968. if (receiver is BoundThisReference && receiver.Type.IsValueType && ContainingMemberOrLambda is MethodSymbol containingMethod && containingMethod.IsEffectivelyReadOnly && // Ignore calls to base members. TypeSymbol.Equals(containingMethod.ContainingType, method.ContainingType, TypeCompareKind.ConsiderEverything) && !method.IsEffectivelyReadOnly && method.RequiresInstanceReceiver) { Error(diagnostics, ErrorCode.WRN_ImplicitCopyInReadOnlyMember, receiver.Syntax, method, ThisParameterSymbol.SymbolName); return false; } return true; } /// <param name="node">Invocation syntax node.</param> /// <param name="expression">The syntax for the invoked method, including receiver.</param> private static Location GetLocationForOverloadResolutionDiagnostic(SyntaxNode node, SyntaxNode expression) { if (node != expression) { switch (expression.Kind()) { case SyntaxKind.QualifiedName: return ((QualifiedNameSyntax)expression).Right.GetLocation(); case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: return ((MemberAccessExpressionSyntax)expression).Name.GetLocation(); } } return expression.GetLocation(); } /// <summary> /// Replace a BoundTypeOrValueExpression with a BoundExpression for either a type (if useType is true) /// or a value (if useType is false). Any other node is bound to its natural type. /// </summary> /// <remarks> /// Call this once overload resolution has succeeded on the method group of which the BoundTypeOrValueExpression /// is the receiver. Generally, useType will be true if the chosen method is static and false otherwise. /// </remarks> private BoundExpression ReplaceTypeOrValueReceiver(BoundExpression receiver, bool useType, BindingDiagnosticBag diagnostics) { if ((object)receiver == null) { return null; } switch (receiver.Kind) { case BoundKind.TypeOrValueExpression: var typeOrValue = (BoundTypeOrValueExpression)receiver; if (useType) { diagnostics.AddRange(typeOrValue.Data.TypeDiagnostics); return typeOrValue.Data.TypeExpression; } else { diagnostics.AddRange(typeOrValue.Data.ValueDiagnostics); return CheckValue(typeOrValue.Data.ValueExpression, BindValueKind.RValue, diagnostics); } case BoundKind.QueryClause: // a query clause may wrap a TypeOrValueExpression. var q = (BoundQueryClause)receiver; var value = q.Value; var replaced = ReplaceTypeOrValueReceiver(value, useType, diagnostics); return (value == replaced) ? q : q.Update(replaced, q.DefinedSymbol, q.Operation, q.Cast, q.Binder, q.UnoptimizedForm, q.Type); default: return BindToNaturalType(receiver, diagnostics); } } /// <summary> /// Return the delegate type if this expression represents a delegate. /// </summary> private static NamedTypeSymbol GetDelegateType(BoundExpression expr) { if ((object)expr != null && expr.Kind != BoundKind.TypeExpression) { var type = expr.Type as NamedTypeSymbol; if (((object)type != null) && type.IsDelegateType()) { return type; } } return null; } private BoundCall CreateBadCall( SyntaxNode node, string name, BoundExpression receiver, ImmutableArray<MethodSymbol> methods, LookupResultKind resultKind, ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations, AnalyzedArguments analyzedArguments, bool invokedAsExtensionMethod, bool isDelegate) { MethodSymbol method; ImmutableArray<BoundExpression> args; if (!typeArgumentsWithAnnotations.IsDefaultOrEmpty) { var constructedMethods = ArrayBuilder<MethodSymbol>.GetInstance(); foreach (var m in methods) { constructedMethods.Add(m.ConstructedFrom == m && m.Arity == typeArgumentsWithAnnotations.Length ? m.Construct(typeArgumentsWithAnnotations) : m); } methods = constructedMethods.ToImmutableAndFree(); } if (methods.Length == 1 && !IsUnboundGeneric(methods[0])) { method = methods[0]; } else { var returnType = GetCommonTypeOrReturnType(methods) ?? new ExtendedErrorTypeSymbol(this.Compilation, string.Empty, arity: 0, errorInfo: null); var methodContainer = (object)receiver != null && (object)receiver.Type != null ? receiver.Type : this.ContainingType; method = new ErrorMethodSymbol(methodContainer, returnType, name); } args = BuildArgumentsForErrorRecovery(analyzedArguments, methods); var argNames = analyzedArguments.GetNames(); var argRefKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); receiver = BindToTypeForErrorRecovery(receiver); return BoundCall.ErrorCall(node, receiver, method, args, argNames, argRefKinds, isDelegate, invokedAsExtensionMethod: invokedAsExtensionMethod, originalMethods: methods, resultKind: resultKind, binder: this); } private static bool IsUnboundGeneric(MethodSymbol method) { return method.IsGenericMethod && method.ConstructedFrom() == method; } // Arbitrary limit on the number of parameter lists from overload // resolution candidates considered when binding argument types. // Any additional parameter lists are ignored. internal const int MaxParameterListsForErrorRecovery = 10; private ImmutableArray<BoundExpression> BuildArgumentsForErrorRecovery(AnalyzedArguments analyzedArguments, ImmutableArray<MethodSymbol> methods) { var parameterListList = ArrayBuilder<ImmutableArray<ParameterSymbol>>.GetInstance(); foreach (var m in methods) { if (!IsUnboundGeneric(m) && m.ParameterCount > 0) { parameterListList.Add(m.Parameters); if (parameterListList.Count == MaxParameterListsForErrorRecovery) { break; } } } var result = BuildArgumentsForErrorRecovery(analyzedArguments, parameterListList); parameterListList.Free(); return result; } private ImmutableArray<BoundExpression> BuildArgumentsForErrorRecovery(AnalyzedArguments analyzedArguments, ImmutableArray<PropertySymbol> properties) { var parameterListList = ArrayBuilder<ImmutableArray<ParameterSymbol>>.GetInstance(); foreach (var p in properties) { if (p.ParameterCount > 0) { parameterListList.Add(p.Parameters); if (parameterListList.Count == MaxParameterListsForErrorRecovery) { break; } } } var result = BuildArgumentsForErrorRecovery(analyzedArguments, parameterListList); parameterListList.Free(); return result; } private ImmutableArray<BoundExpression> BuildArgumentsForErrorRecovery(AnalyzedArguments analyzedArguments, IEnumerable<ImmutableArray<ParameterSymbol>> parameterListList) { var discardedDiagnostics = DiagnosticBag.GetInstance(); int argumentCount = analyzedArguments.Arguments.Count; ArrayBuilder<BoundExpression> newArguments = ArrayBuilder<BoundExpression>.GetInstance(argumentCount); newArguments.AddRange(analyzedArguments.Arguments); for (int i = 0; i < argumentCount; i++) { var argument = newArguments[i]; switch (argument.Kind) { case BoundKind.UnboundLambda: { // bind the argument against each applicable parameter var unboundArgument = (UnboundLambda)argument; foreach (var parameterList in parameterListList) { var parameterType = GetCorrespondingParameterType(analyzedArguments, i, parameterList); if (parameterType?.Kind == SymbolKind.NamedType && (object)parameterType.GetDelegateType() != null) { var discarded = unboundArgument.Bind((NamedTypeSymbol)parameterType); } } // replace the unbound lambda with its best inferred bound version newArguments[i] = unboundArgument.BindForErrorRecovery(); break; } case BoundKind.OutVariablePendingInference: case BoundKind.DiscardExpression: { if (argument.HasExpressionType()) { break; } var candidateType = getCorrespondingParameterType(i); if (argument.Kind == BoundKind.OutVariablePendingInference) { if ((object)candidateType == null) { newArguments[i] = ((OutVariablePendingInference)argument).FailInference(this, null); } else { newArguments[i] = ((OutVariablePendingInference)argument).SetInferredTypeWithAnnotations(TypeWithAnnotations.Create(candidateType), null); } } else if (argument.Kind == BoundKind.DiscardExpression) { if ((object)candidateType == null) { newArguments[i] = ((BoundDiscardExpression)argument).FailInference(this, null); } else { newArguments[i] = ((BoundDiscardExpression)argument).SetInferredTypeWithAnnotations(TypeWithAnnotations.Create(candidateType)); } } break; } case BoundKind.OutDeconstructVarPendingInference: { newArguments[i] = ((OutDeconstructVarPendingInference)argument).FailInference(this); break; } case BoundKind.Parameter: case BoundKind.Local: { newArguments[i] = BindToTypeForErrorRecovery(argument); break; } default: { newArguments[i] = BindToTypeForErrorRecovery(argument, getCorrespondingParameterType(i)); break; } } } discardedDiagnostics.Free(); return newArguments.ToImmutableAndFree(); TypeSymbol getCorrespondingParameterType(int i) { // See if all applicable parameters have the same type TypeSymbol candidateType = null; foreach (var parameterList in parameterListList) { var parameterType = GetCorrespondingParameterType(analyzedArguments, i, parameterList); if ((object)parameterType != null) { if ((object)candidateType == null) { candidateType = parameterType; } else if (!candidateType.Equals(parameterType, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { // type mismatch candidateType = null; break; } } } return candidateType; } } /// <summary> /// Compute the type of the corresponding parameter, if any. This is used to improve error recovery, /// for bad invocations, not for semantic analysis of correct invocations, so it is a heuristic. /// If no parameter appears to correspond to the given argument, we return null. /// </summary> /// <param name="analyzedArguments">The analyzed argument list</param> /// <param name="i">The index of the argument</param> /// <param name="parameterList">The parameter list to match against</param> /// <returns>The type of the corresponding parameter.</returns> private static TypeSymbol GetCorrespondingParameterType(AnalyzedArguments analyzedArguments, int i, ImmutableArray<ParameterSymbol> parameterList) { string name = analyzedArguments.Name(i); if (name != null) { // look for a parameter by that name foreach (var parameter in parameterList) { if (parameter.Name == name) return parameter.Type; } return null; } return (i < parameterList.Length) ? parameterList[i].Type : null; // CONSIDER: should we handle variable argument lists? } /// <summary> /// Absent parameter types to bind the arguments, we simply use the arguments provided for error recovery. /// </summary> private ImmutableArray<BoundExpression> BuildArgumentsForErrorRecovery(AnalyzedArguments analyzedArguments) { return BuildArgumentsForErrorRecovery(analyzedArguments, Enumerable.Empty<ImmutableArray<ParameterSymbol>>()); } private BoundCall CreateBadCall( SyntaxNode node, BoundExpression expr, LookupResultKind resultKind, AnalyzedArguments analyzedArguments) { TypeSymbol returnType = new ExtendedErrorTypeSymbol(this.Compilation, string.Empty, arity: 0, errorInfo: null); var methodContainer = expr.Type ?? this.ContainingType; MethodSymbol method = new ErrorMethodSymbol(methodContainer, returnType, string.Empty); var args = BuildArgumentsForErrorRecovery(analyzedArguments); var argNames = analyzedArguments.GetNames(); var argRefKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); var originalMethods = (expr.Kind == BoundKind.MethodGroup) ? ((BoundMethodGroup)expr).Methods : ImmutableArray<MethodSymbol>.Empty; return BoundCall.ErrorCall(node, expr, method, args, argNames, argRefKinds, isDelegateCall: false, invokedAsExtensionMethod: false, originalMethods: originalMethods, resultKind: resultKind, binder: this); } private static TypeSymbol GetCommonTypeOrReturnType<TMember>(ImmutableArray<TMember> members) where TMember : Symbol { TypeSymbol type = null; for (int i = 0, n = members.Length; i < n; i++) { TypeSymbol returnType = members[i].GetTypeOrReturnType().Type; if ((object)type == null) { type = returnType; } else if (!TypeSymbol.Equals(type, returnType, TypeCompareKind.ConsiderEverything2)) { return null; } } return type; } private bool TryBindNameofOperator(InvocationExpressionSyntax node, BindingDiagnosticBag diagnostics, out BoundExpression result) { result = null; if (node.Expression.Kind() != SyntaxKind.IdentifierName || ((IdentifierNameSyntax)node.Expression).Identifier.ContextualKind() != SyntaxKind.NameOfKeyword || node.ArgumentList.Arguments.Count != 1) { return false; } ArgumentSyntax argument = node.ArgumentList.Arguments[0]; if (argument.NameColon != null || argument.RefOrOutKeyword != default(SyntaxToken) || InvocableNameofInScope()) { return false; } result = BindNameofOperatorInternal(node, diagnostics); return true; } private BoundExpression BindNameofOperatorInternal(InvocationExpressionSyntax node, BindingDiagnosticBag diagnostics) { CheckFeatureAvailability(node, MessageID.IDS_FeatureNameof, diagnostics); var argument = node.ArgumentList.Arguments[0].Expression; // We relax the instance-vs-static requirement for top-level member access expressions by creating a NameofBinder binder. var nameofBinder = new NameofBinder(argument, this); var boundArgument = nameofBinder.BindExpression(argument, diagnostics); bool syntaxIsOk = CheckSyntaxForNameofArgument(argument, out string name, boundArgument.HasAnyErrors ? BindingDiagnosticBag.Discarded : diagnostics); if (!boundArgument.HasAnyErrors && syntaxIsOk && boundArgument.Kind == BoundKind.MethodGroup) { var methodGroup = (BoundMethodGroup)boundArgument; if (!methodGroup.TypeArgumentsOpt.IsDefaultOrEmpty) { // method group with type parameters not allowed diagnostics.Add(ErrorCode.ERR_NameofMethodGroupWithTypeParameters, argument.Location); } else { nameofBinder.EnsureNameofExpressionSymbols(methodGroup, diagnostics); } } if (boundArgument is BoundNamespaceExpression nsExpr) { diagnostics.AddAssembliesUsedByNamespaceReference(nsExpr.NamespaceSymbol); } boundArgument = BindToNaturalType(boundArgument, diagnostics, reportNoTargetType: false); return new BoundNameOfOperator(node, boundArgument, ConstantValue.Create(name), Compilation.GetSpecialType(SpecialType.System_String)); } private void EnsureNameofExpressionSymbols(BoundMethodGroup methodGroup, BindingDiagnosticBag diagnostics) { // Check that the method group contains something applicable. Otherwise error. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var resolution = ResolveMethodGroup(methodGroup, analyzedArguments: null, isMethodGroupConversion: false, useSiteInfo: ref useSiteInfo); diagnostics.Add(methodGroup.Syntax, useSiteInfo); diagnostics.AddRange(resolution.Diagnostics); if (resolution.IsExtensionMethodGroup) { diagnostics.Add(ErrorCode.ERR_NameofExtensionMethod, methodGroup.Syntax.Location); } } /// <summary> /// Returns true if syntax form is OK (so no errors were reported) /// </summary> private bool CheckSyntaxForNameofArgument(ExpressionSyntax argument, out string name, BindingDiagnosticBag diagnostics, bool top = true) { switch (argument.Kind()) { case SyntaxKind.IdentifierName: { var syntax = (IdentifierNameSyntax)argument; name = syntax.Identifier.ValueText; return true; } case SyntaxKind.GenericName: { var syntax = (GenericNameSyntax)argument; name = syntax.Identifier.ValueText; return true; } case SyntaxKind.SimpleMemberAccessExpression: { var syntax = (MemberAccessExpressionSyntax)argument; bool ok = true; switch (syntax.Expression.Kind()) { case SyntaxKind.BaseExpression: case SyntaxKind.ThisExpression: break; default: ok = CheckSyntaxForNameofArgument(syntax.Expression, out name, diagnostics, false); break; } name = syntax.Name.Identifier.ValueText; return ok; } case SyntaxKind.AliasQualifiedName: { var syntax = (AliasQualifiedNameSyntax)argument; bool ok = true; if (top) { diagnostics.Add(ErrorCode.ERR_AliasQualifiedNameNotAnExpression, argument.Location); ok = false; } name = syntax.Name.Identifier.ValueText; return ok; } case SyntaxKind.ThisExpression: case SyntaxKind.BaseExpression: case SyntaxKind.PredefinedType: name = ""; if (top) goto default; return true; default: { var code = top ? ErrorCode.ERR_ExpressionHasNoName : ErrorCode.ERR_SubexpressionNotInNameof; diagnostics.Add(code, argument.Location); name = ""; return false; } } } /// <summary> /// Helper method that checks whether there is an invocable 'nameof' in scope. /// </summary> private bool InvocableNameofInScope() { var lookupResult = LookupResult.GetInstance(); const LookupOptions options = LookupOptions.AllMethodsOnArityZero | LookupOptions.MustBeInvocableIfMember; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; this.LookupSymbolsWithFallback(lookupResult, SyntaxFacts.GetText(SyntaxKind.NameOfKeyword), useSiteInfo: ref discardedUseSiteInfo, arity: 0, options: options); var result = lookupResult.IsMultiViable; lookupResult.Free(); return result; } #nullable enable private BoundFunctionPointerInvocation BindFunctionPointerInvocation(SyntaxNode node, BoundExpression boundExpression, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics) { RoslynDebug.Assert(boundExpression.Type is FunctionPointerTypeSymbol); var funcPtr = (FunctionPointerTypeSymbol)boundExpression.Type; var overloadResolutionResult = OverloadResolutionResult<FunctionPointerMethodSymbol>.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var methodsBuilder = ArrayBuilder<FunctionPointerMethodSymbol>.GetInstance(1); methodsBuilder.Add(funcPtr.Signature); OverloadResolution.FunctionPointerOverloadResolution( methodsBuilder, analyzedArguments, overloadResolutionResult, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!overloadResolutionResult.Succeeded) { ImmutableArray<FunctionPointerMethodSymbol> methods = methodsBuilder.ToImmutableAndFree(); overloadResolutionResult.ReportDiagnostics( binder: this, node.Location, nodeOpt: null, diagnostics, name: null, boundExpression, boundExpression.Syntax, analyzedArguments, methods, typeContainingConstructor: null, delegateTypeBeingInvoked: null, returnRefKind: funcPtr.Signature.RefKind); return new BoundFunctionPointerInvocation( node, boundExpression, BuildArgumentsForErrorRecovery(analyzedArguments, StaticCast<MethodSymbol>.From(methods)), analyzedArguments.RefKinds.ToImmutableOrNull(), LookupResultKind.OverloadResolutionFailure, funcPtr.Signature.ReturnType, hasErrors: true); } methodsBuilder.Free(); MemberResolutionResult<FunctionPointerMethodSymbol> methodResult = overloadResolutionResult.ValidResult; CoerceArguments( methodResult, analyzedArguments.Arguments, diagnostics, receiverType: null, receiverRefKind: null, receiverEscapeScope: Binder.ExternalScope); var args = analyzedArguments.Arguments.ToImmutable(); var refKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); bool hasErrors = ReportUnsafeIfNotAllowed(node, diagnostics); if (!hasErrors) { hasErrors = !CheckInvocationArgMixing( node, funcPtr.Signature, receiverOpt: null, funcPtr.Signature.Parameters, args, methodResult.Result.ArgsToParamsOpt, LocalScopeDepth, diagnostics); } return new BoundFunctionPointerInvocation( node, boundExpression, args, refKinds, LookupResultKind.Viable, funcPtr.Signature.ReturnType, 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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This portion of the binder converts an <see cref="ExpressionSyntax"/> into a <see cref="BoundExpression"/>. /// </summary> internal partial class Binder { private BoundExpression BindMethodGroup(ExpressionSyntax node, bool invoked, bool indexed, BindingDiagnosticBag diagnostics) { switch (node.Kind()) { case SyntaxKind.IdentifierName: case SyntaxKind.GenericName: return BindIdentifier((SimpleNameSyntax)node, invoked, indexed, diagnostics); case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: return BindMemberAccess((MemberAccessExpressionSyntax)node, invoked, indexed, diagnostics); case SyntaxKind.ParenthesizedExpression: return BindMethodGroup(((ParenthesizedExpressionSyntax)node).Expression, invoked: false, indexed: false, diagnostics: diagnostics); default: return BindExpression(node, diagnostics, invoked, indexed); } } private static ImmutableArray<MethodSymbol> GetOriginalMethods(OverloadResolutionResult<MethodSymbol> overloadResolutionResult) { // If overload resolution has failed then we want to stash away the original methods that we // considered so that the IDE can display tooltips or other information about them. // However, if a method group contained a generic method that was type inferred then // the IDE wants information about the *inferred* method, not the original unconstructed // generic method. if (overloadResolutionResult == null) { return ImmutableArray<MethodSymbol>.Empty; } var builder = ArrayBuilder<MethodSymbol>.GetInstance(); foreach (var result in overloadResolutionResult.Results) { builder.Add(result.Member); } return builder.ToImmutableAndFree(); } #nullable enable /// <summary> /// Helper method to create a synthesized method invocation expression. /// </summary> /// <param name="node">Syntax Node.</param> /// <param name="receiver">Receiver for the method call.</param> /// <param name="methodName">Method to be invoked on the receiver.</param> /// <param name="args">Arguments to the method call.</param> /// <param name="diagnostics">Diagnostics.</param> /// <param name="typeArgsSyntax">Optional type arguments syntax.</param> /// <param name="typeArgs">Optional type arguments.</param> /// <param name="queryClause">The syntax for the query clause generating this invocation expression, if any.</param> /// <param name="allowFieldsAndProperties">True to allow invocation of fields and properties of delegate type. Only methods are allowed otherwise.</param> /// <param name="allowUnexpandedForm">False to prevent selecting a params method in unexpanded form.</param> /// <returns>Synthesized method invocation expression.</returns> internal BoundExpression MakeInvocationExpression( SyntaxNode node, BoundExpression receiver, string methodName, ImmutableArray<BoundExpression> args, BindingDiagnosticBag diagnostics, SeparatedSyntaxList<TypeSyntax> typeArgsSyntax = default(SeparatedSyntaxList<TypeSyntax>), ImmutableArray<TypeWithAnnotations> typeArgs = default(ImmutableArray<TypeWithAnnotations>), ImmutableArray<(string Name, Location Location)?> names = default, CSharpSyntaxNode? queryClause = null, bool allowFieldsAndProperties = false, bool allowUnexpandedForm = true, bool searchExtensionMethodsIfNecessary = true) { Debug.Assert(receiver != null); Debug.Assert(names.IsDefault || names.Length == args.Length); receiver = BindToNaturalType(receiver, diagnostics); var boundExpression = BindInstanceMemberAccess(node, node, receiver, methodName, typeArgs.NullToEmpty().Length, typeArgsSyntax, typeArgs, invoked: true, indexed: false, diagnostics, searchExtensionMethodsIfNecessary); // The other consumers of this helper (await and collection initializers) require the target member to be a method. if (!allowFieldsAndProperties && (boundExpression.Kind == BoundKind.FieldAccess || boundExpression.Kind == BoundKind.PropertyAccess)) { Symbol symbol; MessageID msgId; if (boundExpression.Kind == BoundKind.FieldAccess) { msgId = MessageID.IDS_SK_FIELD; symbol = ((BoundFieldAccess)boundExpression).FieldSymbol; } else { msgId = MessageID.IDS_SK_PROPERTY; symbol = ((BoundPropertyAccess)boundExpression).PropertySymbol; } diagnostics.Add( ErrorCode.ERR_BadSKknown, node.Location, methodName, msgId.Localize(), MessageID.IDS_SK_METHOD.Localize()); return BadExpression(node, LookupResultKind.Empty, ImmutableArray.Create(symbol), args.Add(receiver), wasCompilerGenerated: true); } boundExpression = CheckValue(boundExpression, BindValueKind.RValueOrMethodGroup, diagnostics); boundExpression.WasCompilerGenerated = true; var analyzedArguments = AnalyzedArguments.GetInstance(); Debug.Assert(!args.Any(e => e.Kind == BoundKind.OutVariablePendingInference || e.Kind == BoundKind.OutDeconstructVarPendingInference || e.Kind == BoundKind.DiscardExpression && !e.HasExpressionType())); analyzedArguments.Arguments.AddRange(args); if (!names.IsDefault) { analyzedArguments.Names.AddRange(names); } BoundExpression result = BindInvocationExpression( node, node, methodName, boundExpression, analyzedArguments, diagnostics, queryClause, allowUnexpandedForm: allowUnexpandedForm); // Query operator can't be called dynamically. if (queryClause != null && result.Kind == BoundKind.DynamicInvocation) { // the error has already been reported by BindInvocationExpression Debug.Assert(diagnostics.DiagnosticBag is null || diagnostics.HasAnyErrors()); result = CreateBadCall(node, boundExpression, LookupResultKind.Viable, analyzedArguments); } result.WasCompilerGenerated = true; analyzedArguments.Free(); return result; } #nullable disable /// <summary> /// Bind an expression as a method invocation. /// </summary> private BoundExpression BindInvocationExpression( InvocationExpressionSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression result; if (TryBindNameofOperator(node, diagnostics, out result)) { return result; // all of the binding is done by BindNameofOperator } // M(__arglist()) is legal, but M(__arglist(__arglist()) is not! bool isArglist = node.Expression.Kind() == SyntaxKind.ArgListExpression; AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance(); if (isArglist) { BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments, allowArglist: false); result = BindArgListOperator(node, diagnostics, analyzedArguments); } else { BoundExpression boundExpression = BindMethodGroup(node.Expression, invoked: true, indexed: false, diagnostics: diagnostics); boundExpression = CheckValue(boundExpression, BindValueKind.RValueOrMethodGroup, diagnostics); string name = boundExpression.Kind == BoundKind.MethodGroup ? GetName(node.Expression) : null; BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments, allowArglist: true); result = BindInvocationExpression(node, node.Expression, name, boundExpression, analyzedArguments, diagnostics); } analyzedArguments.Free(); return result; } private BoundExpression BindArgListOperator(InvocationExpressionSyntax node, BindingDiagnosticBag diagnostics, AnalyzedArguments analyzedArguments) { bool hasErrors = analyzedArguments.HasErrors; // We allow names, oddly enough; M(__arglist(x : 123)) is legal. We just ignore them. TypeSymbol objType = GetSpecialType(SpecialType.System_Object, diagnostics, node); for (int i = 0; i < analyzedArguments.Arguments.Count; ++i) { BoundExpression argument = analyzedArguments.Arguments[i]; if (argument.Kind == BoundKind.OutVariablePendingInference) { analyzedArguments.Arguments[i] = ((OutVariablePendingInference)argument).FailInference(this, diagnostics); } else if ((object)argument.Type == null && !argument.HasAnyErrors) { // We are going to need every argument in here to have a type. If we don't have one, // try converting it to object. We'll either succeed (if it is a null literal) // or fail with a good error message. // // Note that the native compiler converts null literals to object, and for everything // else it either crashes, or produces nonsense code. Roslyn improves upon this considerably. analyzedArguments.Arguments[i] = GenerateConversionForAssignment(objType, argument, diagnostics); } else if (argument.Type.IsVoidType()) { Error(diagnostics, ErrorCode.ERR_CantUseVoidInArglist, argument.Syntax); hasErrors = true; } else if (analyzedArguments.RefKind(i) == RefKind.None) { analyzedArguments.Arguments[i] = BindToNaturalType(analyzedArguments.Arguments[i], diagnostics); } switch (analyzedArguments.RefKind(i)) { case RefKind.None: case RefKind.Ref: break; default: // Disallow "in" or "out" arguments Error(diagnostics, ErrorCode.ERR_CantUseInOrOutInArglist, argument.Syntax); hasErrors = true; break; } } ImmutableArray<BoundExpression> arguments = analyzedArguments.Arguments.ToImmutable(); ImmutableArray<RefKind> refKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); return new BoundArgListOperator(node, arguments, refKinds, null, hasErrors); } /// <summary> /// Bind an expression as a method invocation. /// </summary> private BoundExpression BindInvocationExpression( SyntaxNode node, SyntaxNode expression, string methodName, BoundExpression boundExpression, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause = null, bool allowUnexpandedForm = true) { BoundExpression result; NamedTypeSymbol delegateType; if ((object)boundExpression.Type != null && boundExpression.Type.IsDynamic()) { // Either we have a dynamic method group invocation "dyn.M(...)" or // a dynamic delegate invocation "dyn(...)" -- either way, bind it as a dynamic // invocation and let the lowering pass sort it out. ReportSuppressionIfNeeded(boundExpression, diagnostics); result = BindDynamicInvocation(node, boundExpression, analyzedArguments, ImmutableArray<MethodSymbol>.Empty, diagnostics, queryClause); } else if (boundExpression.Kind == BoundKind.MethodGroup) { ReportSuppressionIfNeeded(boundExpression, diagnostics); result = BindMethodGroupInvocation( node, expression, methodName, (BoundMethodGroup)boundExpression, analyzedArguments, diagnostics, queryClause, allowUnexpandedForm: allowUnexpandedForm, anyApplicableCandidates: out _); } else if ((object)(delegateType = GetDelegateType(boundExpression)) != null) { if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, delegateType, node: node)) { return CreateBadCall(node, boundExpression, LookupResultKind.Viable, analyzedArguments); } result = BindDelegateInvocation(node, expression, methodName, boundExpression, analyzedArguments, diagnostics, queryClause, delegateType); } else if (boundExpression.Type?.Kind == SymbolKind.FunctionPointerType) { ReportSuppressionIfNeeded(boundExpression, diagnostics); result = BindFunctionPointerInvocation(node, boundExpression, analyzedArguments, diagnostics); } else { if (!boundExpression.HasAnyErrors) { diagnostics.Add(new CSDiagnosticInfo(ErrorCode.ERR_MethodNameExpected), expression.Location); } result = CreateBadCall(node, boundExpression, LookupResultKind.NotInvocable, analyzedArguments); } CheckRestrictedTypeReceiver(result, this.Compilation, diagnostics); return result; } private BoundExpression BindDynamicInvocation( SyntaxNode node, BoundExpression expression, AnalyzedArguments arguments, ImmutableArray<MethodSymbol> applicableMethods, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause) { CheckNamedArgumentsForDynamicInvocation(arguments, diagnostics); bool hasErrors = false; if (expression.Kind == BoundKind.MethodGroup) { BoundMethodGroup methodGroup = (BoundMethodGroup)expression; BoundExpression receiver = methodGroup.ReceiverOpt; // receiver is null if we are calling a static method declared on an outer class via its simple name: if (receiver != null) { switch (receiver.Kind) { case BoundKind.BaseReference: Error(diagnostics, ErrorCode.ERR_NoDynamicPhantomOnBase, node, methodGroup.Name); hasErrors = true; break; case BoundKind.ThisReference: // Can't call the HasThis method due to EE doing odd things with containing member and its containing type. if ((InConstructorInitializer || InFieldInitializer) && receiver.WasCompilerGenerated) { // Only a static method can be called in a constructor initializer. If we were not in a ctor initializer // the runtime binder would ignore the receiver, but in a ctor initializer we can't read "this" before // the base constructor is called. We need to handle this as a type qualified static method call. // Also applicable to things like field initializers, which run before the ctor initializer. expression = methodGroup.Update( methodGroup.TypeArgumentsOpt, methodGroup.Name, methodGroup.Methods, methodGroup.LookupSymbolOpt, methodGroup.LookupError, methodGroup.Flags & ~BoundMethodGroupFlags.HasImplicitReceiver, receiverOpt: new BoundTypeExpression(node, null, this.ContainingType).MakeCompilerGenerated(), resultKind: methodGroup.ResultKind); } break; case BoundKind.TypeOrValueExpression: var typeOrValue = (BoundTypeOrValueExpression)receiver; // Unfortunately, the runtime binder doesn't have APIs that would allow us to pass both "type or value". // Ideally the runtime binder would choose between type and value based on the result of the overload resolution. // We need to pick one or the other here. Dev11 compiler passes the type only if the value can't be accessed. bool inStaticContext; bool useType = IsInstance(typeOrValue.Data.ValueSymbol) && !HasThis(isExplicit: false, inStaticContext: out inStaticContext); BoundExpression finalReceiver = ReplaceTypeOrValueReceiver(typeOrValue, useType, diagnostics); expression = methodGroup.Update( methodGroup.TypeArgumentsOpt, methodGroup.Name, methodGroup.Methods, methodGroup.LookupSymbolOpt, methodGroup.LookupError, methodGroup.Flags, finalReceiver, methodGroup.ResultKind); break; } } } else { expression = BindToNaturalType(expression, diagnostics); } ImmutableArray<BoundExpression> argArray = BuildArgumentsForDynamicInvocation(arguments, diagnostics); var refKindsArray = arguments.RefKinds.ToImmutableOrNull(); hasErrors &= ReportBadDynamicArguments(node, argArray, refKindsArray, diagnostics, queryClause); return new BoundDynamicInvocation( node, arguments.GetNames(), refKindsArray, applicableMethods, expression, argArray, type: Compilation.DynamicType, hasErrors: hasErrors); } private void CheckNamedArgumentsForDynamicInvocation(AnalyzedArguments arguments, BindingDiagnosticBag diagnostics) { if (arguments.Names.Count == 0) { return; } if (!Compilation.LanguageVersion.AllowNonTrailingNamedArguments()) { return; } bool seenName = false; for (int i = 0; i < arguments.Names.Count; i++) { if (arguments.Names[i] != null) { seenName = true; } else if (seenName) { Error(diagnostics, ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgumentInDynamicInvocation, arguments.Arguments[i].Syntax); return; } } } private ImmutableArray<BoundExpression> BuildArgumentsForDynamicInvocation(AnalyzedArguments arguments, BindingDiagnosticBag diagnostics) { var builder = ArrayBuilder<BoundExpression>.GetInstance(arguments.Arguments.Count); builder.AddRange(arguments.Arguments); for (int i = 0, n = builder.Count; i < n; i++) { builder[i] = builder[i] switch { OutVariablePendingInference outvar => outvar.FailInference(this, diagnostics), BoundDiscardExpression discard when !discard.HasExpressionType() => discard.FailInference(this, diagnostics), var arg => BindToNaturalType(arg, diagnostics) }; } return builder.ToImmutableAndFree(); } // Returns true if there were errors. private static bool ReportBadDynamicArguments( SyntaxNode node, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKinds, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause) { bool hasErrors = false; bool reportedBadQuery = false; if (!refKinds.IsDefault) { for (int argIndex = 0; argIndex < refKinds.Length; argIndex++) { if (refKinds[argIndex] == RefKind.In) { Error(diagnostics, ErrorCode.ERR_InDynamicMethodArg, arguments[argIndex].Syntax); hasErrors = true; } } } foreach (var arg in arguments) { if (!IsLegalDynamicOperand(arg)) { if (queryClause != null && !reportedBadQuery) { reportedBadQuery = true; Error(diagnostics, ErrorCode.ERR_BadDynamicQuery, node); hasErrors = true; continue; } if (arg.Kind == BoundKind.Lambda || arg.Kind == BoundKind.UnboundLambda) { // Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArgLambda, arg.Syntax); hasErrors = true; } else if (arg.Kind == BoundKind.MethodGroup) { // Cannot use a method group as an argument to a dynamically dispatched operation. Did you intend to invoke the method? Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArgMemgrp, arg.Syntax); hasErrors = true; } else if (arg.Kind == BoundKind.ArgListOperator) { // Not a great error message, since __arglist is not a type, but it'll do. // error CS1978: Cannot use an expression of type '__arglist' as an argument to a dynamically dispatched operation Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArg, arg.Syntax, "__arglist"); } else { // Lambdas,anonymous methods and method groups are the typeless expressions that // are not usable as dynamic arguments; if we get here then the expression must have a type. Debug.Assert((object)arg.Type != null); // error CS1978: Cannot use an expression of type 'int*' as an argument to a dynamically dispatched operation Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArg, arg.Syntax, arg.Type); hasErrors = true; } } } return hasErrors; } private BoundExpression BindDelegateInvocation( SyntaxNode node, SyntaxNode expression, string methodName, BoundExpression boundExpression, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause, NamedTypeSymbol delegateType) { BoundExpression result; var methodGroup = MethodGroup.GetInstance(); methodGroup.PopulateWithSingleMethod(boundExpression, delegateType.DelegateInvokeMethod); var overloadResolutionResult = OverloadResolutionResult<MethodSymbol>.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); OverloadResolution.MethodInvocationOverloadResolution( methods: methodGroup.Methods, typeArguments: methodGroup.TypeArguments, receiver: methodGroup.Receiver, arguments: analyzedArguments, result: overloadResolutionResult, useSiteInfo: ref useSiteInfo); diagnostics.Add(node, useSiteInfo); // If overload resolution on the "Invoke" method found an applicable candidate, and one of the arguments // was dynamic then treat this as a dynamic call. if (analyzedArguments.HasDynamicArgument && overloadResolutionResult.HasAnyApplicableMember) { result = BindDynamicInvocation(node, boundExpression, analyzedArguments, overloadResolutionResult.GetAllApplicableMembers(), diagnostics, queryClause); } else { result = BindInvocationExpressionContinued(node, expression, methodName, overloadResolutionResult, analyzedArguments, methodGroup, delegateType, diagnostics, queryClause); } overloadResolutionResult.Free(); methodGroup.Free(); return result; } private static bool HasApplicableConditionalMethod(OverloadResolutionResult<MethodSymbol> results) { var r = results.Results; for (int i = 0; i < r.Length; ++i) { if (r[i].IsApplicable && r[i].Member.IsConditional) { return true; } } return false; } private BoundExpression BindMethodGroupInvocation( SyntaxNode syntax, SyntaxNode expression, string methodName, BoundMethodGroup methodGroup, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause, bool allowUnexpandedForm, out bool anyApplicableCandidates) { BoundExpression result; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var resolution = this.ResolveMethodGroup( methodGroup, expression, methodName, analyzedArguments, isMethodGroupConversion: false, useSiteInfo: ref useSiteInfo, allowUnexpandedForm: allowUnexpandedForm); diagnostics.Add(expression, useSiteInfo); anyApplicableCandidates = resolution.ResultKind == LookupResultKind.Viable && resolution.OverloadResolutionResult.HasAnyApplicableMember; if (!methodGroup.HasAnyErrors) diagnostics.AddRange(resolution.Diagnostics); // Suppress cascading. if (resolution.HasAnyErrors) { ImmutableArray<MethodSymbol> originalMethods; LookupResultKind resultKind; ImmutableArray<TypeWithAnnotations> typeArguments; if (resolution.OverloadResolutionResult != null) { originalMethods = GetOriginalMethods(resolution.OverloadResolutionResult); resultKind = resolution.MethodGroup.ResultKind; typeArguments = resolution.MethodGroup.TypeArguments.ToImmutable(); } else { originalMethods = methodGroup.Methods; resultKind = methodGroup.ResultKind; typeArguments = methodGroup.TypeArgumentsOpt; } result = CreateBadCall( syntax, methodName, methodGroup.ReceiverOpt, originalMethods, resultKind, typeArguments, analyzedArguments, invokedAsExtensionMethod: resolution.IsExtensionMethodGroup, isDelegate: false); } else if (!resolution.IsEmpty) { // We're checking resolution.ResultKind, rather than methodGroup.HasErrors // to better handle the case where there's a problem with the receiver // (e.g. inaccessible), but the method group resolved correctly (e.g. because // it's actually an accessible static method on a base type). // CONSIDER: could check for error types amongst method group type arguments. if (resolution.ResultKind != LookupResultKind.Viable) { if (resolution.MethodGroup != null) { // we want to force any unbound lambda arguments to cache an appropriate conversion if possible; see 9448. result = BindInvocationExpressionContinued( syntax, expression, methodName, resolution.OverloadResolutionResult, resolution.AnalyzedArguments, resolution.MethodGroup, delegateTypeOpt: null, diagnostics: BindingDiagnosticBag.Discarded, queryClause: queryClause); } // Since the resolution is non-empty and has no diagnostics, the LookupResultKind in its MethodGroup is uninteresting. result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments); } else { // If overload resolution found one or more applicable methods and at least one argument // was dynamic then treat this as a dynamic call. if (resolution.AnalyzedArguments.HasDynamicArgument && resolution.OverloadResolutionResult.HasAnyApplicableMember) { if (resolution.IsLocalFunctionInvocation) { result = BindLocalFunctionInvocationWithDynamicArgument( syntax, expression, methodName, methodGroup, diagnostics, queryClause, resolution); } else if (resolution.IsExtensionMethodGroup) { // error CS1973: 'T' has no applicable method named 'M' 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. // We found an extension method, so the instance associated with the method group must have // existed and had a type. Debug.Assert(methodGroup.InstanceOpt != null && (object)methodGroup.InstanceOpt.Type != null); Error(diagnostics, ErrorCode.ERR_BadArgTypeDynamicExtension, syntax, methodGroup.InstanceOpt.Type, methodGroup.Name); result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments); } else { if (HasApplicableConditionalMethod(resolution.OverloadResolutionResult)) { // warning CS1974: The dynamically dispatched call to method 'Goo' may fail at runtime // because one or more applicable overloads are conditional methods Error(diagnostics, ErrorCode.WRN_DynamicDispatchToConditionalMethod, syntax, methodGroup.Name); } // Note that the runtime binder may consider candidates that haven't passed compile-time final validation // and an ambiguity error may be reported. Also additional checks are performed in runtime final validation // that are not performed at compile-time. // Only if the set of final applicable candidates is empty we know for sure the call will fail at runtime. var finalApplicableCandidates = GetCandidatesPassingFinalValidation(syntax, resolution.OverloadResolutionResult, methodGroup.ReceiverOpt, methodGroup.TypeArgumentsOpt, diagnostics); if (finalApplicableCandidates.Length > 0) { result = BindDynamicInvocation(syntax, methodGroup, resolution.AnalyzedArguments, finalApplicableCandidates, diagnostics, queryClause); } else { result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments); } } } else { result = BindInvocationExpressionContinued( syntax, expression, methodName, resolution.OverloadResolutionResult, resolution.AnalyzedArguments, resolution.MethodGroup, delegateTypeOpt: null, diagnostics: diagnostics, queryClause: queryClause); } } } else { result = CreateBadCall(syntax, methodGroup, methodGroup.ResultKind, analyzedArguments); } resolution.Free(); return result; } private BoundExpression BindLocalFunctionInvocationWithDynamicArgument( SyntaxNode syntax, SyntaxNode expression, string methodName, BoundMethodGroup boundMethodGroup, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause, MethodGroupResolution resolution) { // Invocations of local functions with dynamic arguments don't need // to be dispatched as dynamic invocations since they cannot be // overloaded. Instead, we'll just emit a standard call with // dynamic implicit conversions for any dynamic arguments. There // are two exceptions: "params", and unconstructed generics. While // implementing those cases with dynamic invocations is possible, // we have decided the implementation complexity is not worth it. // Refer to the comments below for the exact semantics. Debug.Assert(resolution.IsLocalFunctionInvocation); Debug.Assert(resolution.OverloadResolutionResult.Succeeded); Debug.Assert(queryClause == null); var validResult = resolution.OverloadResolutionResult.ValidResult; var args = resolution.AnalyzedArguments.Arguments.ToImmutable(); var refKindsArray = resolution.AnalyzedArguments.RefKinds.ToImmutableOrNull(); ReportBadDynamicArguments(syntax, args, refKindsArray, diagnostics, queryClause); var localFunction = validResult.Member; var methodResult = validResult.Result; // We're only in trouble if a dynamic argument is passed to the // params parameter and is ambiguous at compile time between normal // and expanded form i.e., there is exactly one dynamic argument to // a params parameter // See https://github.com/dotnet/roslyn/issues/10708 if (OverloadResolution.IsValidParams(localFunction) && methodResult.Kind == MemberResolutionKind.ApplicableInNormalForm) { var parameters = localFunction.Parameters; Debug.Assert(parameters.Last().IsParams); var lastParamIndex = parameters.Length - 1; for (int i = 0; i < args.Length; ++i) { var arg = args[i]; if (arg.HasDynamicType() && methodResult.ParameterFromArgument(i) == lastParamIndex) { Error(diagnostics, ErrorCode.ERR_DynamicLocalFunctionParamsParameter, syntax, parameters.Last().Name, localFunction.Name); return BindDynamicInvocation( syntax, boundMethodGroup, resolution.AnalyzedArguments, resolution.OverloadResolutionResult.GetAllApplicableMembers(), diagnostics, queryClause); } } } // If we call an unconstructed generic local function with a // dynamic argument in a place where it influences the type // parameters, we need to dynamically dispatch the call (as the // function must be constructed at runtime). We cannot do that, so // disallow that. However, doing a specific analysis of each // argument and its corresponding parameter to check if it's // generic (and allow dynamic in non-generic parameters) may break // overload resolution in the future, if we ever allow overloaded // local functions. So, just disallow any mixing of dynamic and // inferred generics. (Explicit generic arguments are fine) // See https://github.com/dotnet/roslyn/issues/21317 if (boundMethodGroup.TypeArgumentsOpt.IsDefaultOrEmpty && localFunction.IsGenericMethod) { Error(diagnostics, ErrorCode.ERR_DynamicLocalFunctionTypeParameter, syntax, localFunction.Name); return BindDynamicInvocation( syntax, boundMethodGroup, resolution.AnalyzedArguments, resolution.OverloadResolutionResult.GetAllApplicableMembers(), diagnostics, queryClause); } return BindInvocationExpressionContinued( node: syntax, expression: expression, methodName: methodName, result: resolution.OverloadResolutionResult, analyzedArguments: resolution.AnalyzedArguments, methodGroup: resolution.MethodGroup, delegateTypeOpt: null, diagnostics: diagnostics, queryClause: queryClause); } private ImmutableArray<TMethodOrPropertySymbol> GetCandidatesPassingFinalValidation<TMethodOrPropertySymbol>( SyntaxNode syntax, OverloadResolutionResult<TMethodOrPropertySymbol> overloadResolutionResult, BoundExpression receiverOpt, ImmutableArray<TypeWithAnnotations> typeArgumentsOpt, BindingDiagnosticBag diagnostics) where TMethodOrPropertySymbol : Symbol { Debug.Assert(overloadResolutionResult.HasAnyApplicableMember); var finalCandidates = ArrayBuilder<TMethodOrPropertySymbol>.GetInstance(); BindingDiagnosticBag firstFailed = null; var candidateDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); for (int i = 0, n = overloadResolutionResult.ResultsBuilder.Count; i < n; i++) { var result = overloadResolutionResult.ResultsBuilder[i]; if (result.Result.IsApplicable) { // For F to pass the check, all of the following must hold: // ... // * If the type parameters of F were substituted in the step above, their constraints are satisfied. // * If F is a static method, the method group must have resulted from a simple-name, a member-access through a type, // or a member-access whose receiver can't be classified as a type or value until after overload resolution (see §7.6.4.1). // * If F is an instance method, the method group must have resulted from a simple-name, a member-access through a variable or value, // or a member-access whose receiver can't be classified as a type or value until after overload resolution (see §7.6.4.1). if (!MemberGroupFinalValidationAccessibilityChecks(receiverOpt, result.Member, syntax, candidateDiagnostics, invokedAsExtensionMethod: false) && (typeArgumentsOpt.IsDefault || ((MethodSymbol)(object)result.Member).CheckConstraints(new ConstraintsHelper.CheckConstraintsArgs(this.Compilation, this.Conversions, includeNullability: false, syntax.Location, candidateDiagnostics)))) { finalCandidates.Add(result.Member); continue; } if (firstFailed == null) { firstFailed = candidateDiagnostics; candidateDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); } else { candidateDiagnostics.Clear(); } } } if (firstFailed != null) { // Report diagnostics of the first candidate that failed the validation // unless we have at least one candidate that passes. if (finalCandidates.Count == 0) { diagnostics.AddRange(firstFailed); } firstFailed.Free(); } candidateDiagnostics.Free(); return finalCandidates.ToImmutableAndFree(); } private void CheckRestrictedTypeReceiver(BoundExpression expression, CSharpCompilation compilation, BindingDiagnosticBag diagnostics) { Debug.Assert(diagnostics != null); // It is never legal to box a restricted type, even if we are boxing it as the receiver // of a method call. When must be box? We skip boxing when the method in question is defined // on the restricted type or overridden by the restricted type. switch (expression.Kind) { case BoundKind.Call: { var call = (BoundCall)expression; if (!call.HasAnyErrors && call.ReceiverOpt != null && (object)call.ReceiverOpt.Type != null) { // error CS0029: Cannot implicitly convert type 'A' to 'B' // Case 1: receiver is a restricted type, and method called is defined on a parent type if (call.ReceiverOpt.Type.IsRestrictedType() && !TypeSymbol.Equals(call.Method.ContainingType, call.ReceiverOpt.Type, TypeCompareKind.ConsiderEverything2)) { SymbolDistinguisher distinguisher = new SymbolDistinguisher(compilation, call.ReceiverOpt.Type, call.Method.ContainingType); Error(diagnostics, ErrorCode.ERR_NoImplicitConv, call.ReceiverOpt.Syntax, distinguisher.First, distinguisher.Second); } // Case 2: receiver is a base reference, and the child type is restricted else if (call.ReceiverOpt.Kind == BoundKind.BaseReference && this.ContainingType.IsRestrictedType()) { SymbolDistinguisher distinguisher = new SymbolDistinguisher(compilation, this.ContainingType, call.Method.ContainingType); Error(diagnostics, ErrorCode.ERR_NoImplicitConv, call.ReceiverOpt.Syntax, distinguisher.First, distinguisher.Second); } } } break; case BoundKind.DynamicInvocation: { var dynInvoke = (BoundDynamicInvocation)expression; if (!dynInvoke.HasAnyErrors && (object)dynInvoke.Expression.Type != null && dynInvoke.Expression.Type.IsRestrictedType()) { // eg: b = typedReference.Equals(dyn); // error CS1978: Cannot use an expression of type 'TypedReference' as an argument to a dynamically dispatched operation Error(diagnostics, ErrorCode.ERR_BadDynamicMethodArg, dynInvoke.Expression.Syntax, dynInvoke.Expression.Type); } } break; case BoundKind.FunctionPointerInvocation: break; default: throw ExceptionUtilities.UnexpectedValue(expression.Kind); } } /// <summary> /// Perform overload resolution on the method group or expression (BoundMethodGroup) /// and arguments and return a BoundExpression representing the invocation. /// </summary> /// <param name="node">Invocation syntax node.</param> /// <param name="expression">The syntax for the invoked method, including receiver.</param> /// <param name="methodName">Name of the invoked method.</param> /// <param name="result">Overload resolution result for method group executed by caller.</param> /// <param name="analyzedArguments">Arguments bound by the caller.</param> /// <param name="methodGroup">Method group if the invocation represents a potentially overloaded member.</param> /// <param name="delegateTypeOpt">Delegate type if method group represents a delegate.</param> /// <param name="diagnostics">Diagnostics.</param> /// <param name="queryClause">The syntax for the query clause generating this invocation expression, if any.</param> /// <returns>BoundCall or error expression representing the invocation.</returns> private BoundCall BindInvocationExpressionContinued( SyntaxNode node, SyntaxNode expression, string methodName, OverloadResolutionResult<MethodSymbol> result, AnalyzedArguments analyzedArguments, MethodGroup methodGroup, NamedTypeSymbol delegateTypeOpt, BindingDiagnosticBag diagnostics, CSharpSyntaxNode queryClause = null) { Debug.Assert(node != null); Debug.Assert(methodGroup != null); Debug.Assert(methodGroup.Error == null); Debug.Assert(methodGroup.Methods.Count > 0); Debug.Assert(((object)delegateTypeOpt == null) || (methodGroup.Methods.Count == 1)); var invokedAsExtensionMethod = methodGroup.IsExtensionMethodGroup; // Delegate invocations should never be considered extension method // invocations (even though the delegate may refer to an extension method). Debug.Assert(!invokedAsExtensionMethod || ((object)delegateTypeOpt == null)); // We have already determined that we are not in a situation where we can successfully do // a dynamic binding. We might be in one of the following situations: // // * There were dynamic arguments but overload resolution still found zero applicable candidates. // * There were no dynamic arguments and overload resolution found zero applicable candidates. // * There were no dynamic arguments and overload resolution found multiple applicable candidates // without being able to find the best one. // // In those three situations we might give an additional error. if (!result.Succeeded) { if (analyzedArguments.HasErrors) { // Errors for arguments have already been reported, except for unbound lambdas and switch expressions. // We report those now. foreach (var argument in analyzedArguments.Arguments) { switch (argument) { case UnboundLambda unboundLambda: var boundWithErrors = unboundLambda.BindForErrorRecovery(); diagnostics.AddRange(boundWithErrors.Diagnostics); break; case BoundUnconvertedObjectCreationExpression _: case BoundTupleLiteral _: // Tuple literals can contain unbound lambdas or switch expressions. _ = BindToNaturalType(argument, diagnostics); break; case BoundUnconvertedSwitchExpression { Type: { } naturalType } switchExpr: _ = ConvertSwitchExpression(switchExpr, naturalType, conversionIfTargetTyped: null, diagnostics); break; case BoundUnconvertedConditionalOperator { Type: { } naturalType } conditionalExpr: _ = ConvertConditionalExpression(conditionalExpr, naturalType, conversionIfTargetTyped: null, diagnostics); break; } } } else { // Since there were no argument errors to report, we report an error on the invocation itself. string name = (object)delegateTypeOpt == null ? methodName : null; result.ReportDiagnostics( binder: this, location: GetLocationForOverloadResolutionDiagnostic(node, expression), nodeOpt: node, diagnostics: diagnostics, name: name, receiver: methodGroup.Receiver, invokedExpression: expression, arguments: analyzedArguments, memberGroup: methodGroup.Methods.ToImmutable(), typeContainingConstructor: null, delegateTypeBeingInvoked: delegateTypeOpt, queryClause: queryClause); } return CreateBadCall(node, methodGroup.Name, invokedAsExtensionMethod && analyzedArguments.Arguments.Count > 0 && (object)methodGroup.Receiver == (object)analyzedArguments.Arguments[0] ? null : methodGroup.Receiver, GetOriginalMethods(result), methodGroup.ResultKind, methodGroup.TypeArguments.ToImmutable(), analyzedArguments, invokedAsExtensionMethod: invokedAsExtensionMethod, isDelegate: ((object)delegateTypeOpt != null)); } // Otherwise, there were no dynamic arguments and overload resolution found a unique best candidate. // We still have to determine if it passes final validation. var methodResult = result.ValidResult; var returnType = methodResult.Member.ReturnType; var method = methodResult.Member; // It is possible that overload resolution succeeded, but we have chosen an // instance method and we're in a static method. A careful reading of the // overload resolution spec shows that the "final validation" stage allows an // "implicit this" on any method call, not just method calls from inside // instance methods. Therefore we must detect this scenario here, rather than in // overload resolution. var receiver = ReplaceTypeOrValueReceiver(methodGroup.Receiver, !method.RequiresInstanceReceiver && !invokedAsExtensionMethod, diagnostics); var receiverRefKind = receiver?.GetRefKind(); uint receiverValEscapeScope = method.RequiresInstanceReceiver && receiver != null ? receiverRefKind?.IsWritableReference() == true ? GetRefEscape(receiver, LocalScopeDepth) : GetValEscape(receiver, LocalScopeDepth) : Binder.ExternalScope; this.CoerceArguments(methodResult, analyzedArguments.Arguments, diagnostics, receiver?.Type, receiverRefKind, receiverValEscapeScope); var expanded = methodResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm; var argsToParams = methodResult.Result.ArgsToParamsOpt; BindDefaultArguments(node, method.Parameters, analyzedArguments.Arguments, analyzedArguments.RefKinds, ref argsToParams, out var defaultArguments, expanded, enableCallerInfo: true, diagnostics); // Note: we specifically want to do final validation (7.6.5.1) without checking delegate compatibility (15.2), // so we're calling MethodGroupFinalValidation directly, rather than via MethodGroupConversionHasErrors. // Note: final validation wants the receiver that corresponds to the source representation // (i.e. the first argument, if invokedAsExtensionMethod). var gotError = MemberGroupFinalValidation(receiver, method, expression, diagnostics, invokedAsExtensionMethod); CheckImplicitThisCopyInReadOnlyMember(receiver, method, diagnostics); if (invokedAsExtensionMethod) { BoundExpression receiverArgument = analyzedArguments.Argument(0); ParameterSymbol receiverParameter = method.Parameters.First(); // we will have a different receiver if ReplaceTypeOrValueReceiver has unwrapped TypeOrValue if ((object)receiver != receiverArgument) { // Because the receiver didn't pass through CoerceArguments, we need to apply an appropriate conversion here. Debug.Assert(argsToParams.IsDefault || argsToParams[0] == 0); receiverArgument = CreateConversion(receiver, methodResult.Result.ConversionForArg(0), receiverParameter.Type, diagnostics); } if (receiverParameter.RefKind == RefKind.Ref) { // If this was a ref extension method, receiverArgument must be checked for L-value constraints. // This helper method will also replace it with a BoundBadExpression if it was invalid. receiverArgument = CheckValue(receiverArgument, BindValueKind.RefOrOut, diagnostics); if (analyzedArguments.RefKinds.Count == 0) { analyzedArguments.RefKinds.Count = analyzedArguments.Arguments.Count; } // receiver of a `ref` extension method is a `ref` argument. (and we have checked above that it can be passed as a Ref) // we need to adjust the argument refkind as if we had a `ref` modifier in a call. analyzedArguments.RefKinds[0] = RefKind.Ref; CheckFeatureAvailability(receiverArgument.Syntax, MessageID.IDS_FeatureRefExtensionMethods, diagnostics); } else if (receiverParameter.RefKind == RefKind.In) { // NB: receiver of an `in` extension method is treated as a `byval` argument, so no changes from the default refkind is needed in that case. Debug.Assert(analyzedArguments.RefKind(0) == RefKind.None); CheckFeatureAvailability(receiverArgument.Syntax, MessageID.IDS_FeatureRefExtensionMethods, diagnostics); } analyzedArguments.Arguments[0] = receiverArgument; } // This will be the receiver of the BoundCall node that we create. // For extension methods, there is no receiver because the receiver in source was actually the first argument. // For instance methods, we may have synthesized an implicit this node. We'll keep it for the emitter. // For static methods, we may have synthesized a type expression. It serves no purpose, so we'll drop it. if (invokedAsExtensionMethod || (!method.RequiresInstanceReceiver && receiver != null && receiver.WasCompilerGenerated)) { receiver = null; } var argNames = analyzedArguments.GetNames(); var argRefKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); var args = analyzedArguments.Arguments.ToImmutable(); if (!gotError && method.RequiresInstanceReceiver && receiver != null && receiver.Kind == BoundKind.ThisReference && receiver.WasCompilerGenerated) { gotError = IsRefOrOutThisParameterCaptured(node, diagnostics); } // What if some of the arguments are implicit? Dev10 reports unsafe errors // if the implied argument would have an unsafe type. We need to check // the parameters explicitly, since there won't be bound nodes for the implied // arguments until lowering. if (method.HasUnsafeParameter()) { // Don't worry about double reporting (i.e. for both the argument and the parameter) // because only one unsafe diagnostic is allowed per scope - the others are suppressed. gotError = ReportUnsafeIfNotAllowed(node, diagnostics) || gotError; } bool hasBaseReceiver = receiver != null && receiver.Kind == BoundKind.BaseReference; ReportDiagnosticsIfObsolete(diagnostics, method, node, hasBaseReceiver); ReportDiagnosticsIfUnmanagedCallersOnly(diagnostics, method, node.Location, isDelegateConversion: false); // No use site errors, but there could be use site warnings. // If there are any use site warnings, they have already been reported by overload resolution. Debug.Assert(!method.HasUseSiteError, "Shouldn't have reached this point if there were use site errors."); if (method.IsRuntimeFinalizer()) { ErrorCode code = hasBaseReceiver ? ErrorCode.ERR_CallingBaseFinalizeDeprecated : ErrorCode.ERR_CallingFinalizeDeprecated; Error(diagnostics, code, node); gotError = true; } Debug.Assert(args.IsDefaultOrEmpty || (object)receiver != (object)args[0]); if (!gotError) { gotError = !CheckInvocationArgMixing( node, method, receiver, method.Parameters, args, argsToParams, this.LocalScopeDepth, diagnostics); } bool isDelegateCall = (object)delegateTypeOpt != null; if (!isDelegateCall) { if (method.RequiresInstanceReceiver) { WarnOnAccessOfOffDefault(node.Kind() == SyntaxKind.InvocationExpression ? ((InvocationExpressionSyntax)node).Expression : node, receiver, diagnostics); } } return new BoundCall(node, receiver, method, args, argNames, argRefKinds, isDelegateCall: isDelegateCall, expanded: expanded, invokedAsExtensionMethod: invokedAsExtensionMethod, argsToParamsOpt: argsToParams, defaultArguments, resultKind: LookupResultKind.Viable, type: returnType, hasErrors: gotError); } #nullable enable private static SourceLocation GetCallerLocation(SyntaxNode syntax) { var token = syntax switch { InvocationExpressionSyntax invocation => invocation.ArgumentList.OpenParenToken, BaseObjectCreationExpressionSyntax objectCreation => objectCreation.NewKeyword, ConstructorInitializerSyntax constructorInitializer => constructorInitializer.ArgumentList.OpenParenToken, PrimaryConstructorBaseTypeSyntax primaryConstructorBaseType => primaryConstructorBaseType.ArgumentList.OpenParenToken, ElementAccessExpressionSyntax elementAccess => elementAccess.ArgumentList.OpenBracketToken, _ => syntax.GetFirstToken() }; return new SourceLocation(token); } private BoundExpression GetDefaultParameterSpecialNoConversion(SyntaxNode syntax, ParameterSymbol parameter, BindingDiagnosticBag diagnostics) { var parameterType = parameter.Type; Debug.Assert(parameterType.IsDynamic() || parameterType.SpecialType == SpecialType.System_Object); // We have a call to a method M([Optional] object x) which omits the argument. The value we generate // for the argument depends on the presence or absence of other attributes. The rules are: // // * If the parameter is marked as [MarshalAs(Interface)], [MarshalAs(IUnknown)] or [MarshalAs(IDispatch)] // then the argument is null. // * Otherwise, if the parameter is marked as [IUnknownConstant] then the argument is // new UnknownWrapper(null) // * Otherwise, if the parameter is marked as [IDispatchConstant] then the argument is // new DispatchWrapper(null) // * Otherwise, the argument is Type.Missing. BoundExpression? defaultValue = null; if (parameter.IsMarshalAsObject) { // default(object) defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; } else if (parameter.IsIUnknownConstant) { if (GetWellKnownTypeMember(Compilation, WellKnownMember.System_Runtime_InteropServices_UnknownWrapper__ctor, diagnostics, syntax: syntax) is MethodSymbol methodSymbol) { // new UnknownWrapper(default(object)) var unknownArgument = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; defaultValue = new BoundObjectCreationExpression(syntax, methodSymbol, unknownArgument) { WasCompilerGenerated = true }; } } else if (parameter.IsIDispatchConstant) { if (GetWellKnownTypeMember(Compilation, WellKnownMember.System_Runtime_InteropServices_DispatchWrapper__ctor, diagnostics, syntax: syntax) is MethodSymbol methodSymbol) { // new DispatchWrapper(default(object)) var dispatchArgument = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; defaultValue = new BoundObjectCreationExpression(syntax, methodSymbol, dispatchArgument) { WasCompilerGenerated = true }; } } else { if (GetWellKnownTypeMember(Compilation, WellKnownMember.System_Type__Missing, diagnostics, syntax: syntax) is FieldSymbol fieldSymbol) { // Type.Missing defaultValue = new BoundFieldAccess(syntax, null, fieldSymbol, ConstantValue.NotAvailable) { WasCompilerGenerated = true }; } } return defaultValue ?? BadExpression(syntax).MakeCompilerGenerated(); } internal static ParameterSymbol? GetCorrespondingParameter( int argumentOrdinal, ImmutableArray<ParameterSymbol> parameters, ImmutableArray<int> argsToParamsOpt, bool expanded) { int n = parameters.Length; ParameterSymbol? parameter; if (argsToParamsOpt.IsDefault) { if (argumentOrdinal < n) { parameter = parameters[argumentOrdinal]; } else if (expanded) { parameter = parameters[n - 1]; } else { parameter = null; } } else { Debug.Assert(argumentOrdinal < argsToParamsOpt.Length); int parameterOrdinal = argsToParamsOpt[argumentOrdinal]; if (parameterOrdinal < n) { parameter = parameters[parameterOrdinal]; } else { parameter = null; } } return parameter; } internal void BindDefaultArguments( SyntaxNode node, ImmutableArray<ParameterSymbol> parameters, ArrayBuilder<BoundExpression> argumentsBuilder, ArrayBuilder<RefKind>? argumentRefKindsBuilder, ref ImmutableArray<int> argsToParamsOpt, out BitVector defaultArguments, bool expanded, bool enableCallerInfo, BindingDiagnosticBag diagnostics, bool assertMissingParametersAreOptional = true) { var visitedParameters = BitVector.Create(parameters.Length); for (var i = 0; i < argumentsBuilder.Count; i++) { var parameter = GetCorrespondingParameter(i, parameters, argsToParamsOpt, expanded); if (parameter is not null) { visitedParameters[parameter.Ordinal] = true; } } // only proceed with binding default arguments if we know there is some parameter that has not been matched by an explicit argument if (parameters.All(static (param, visitedParameters) => visitedParameters[param.Ordinal], visitedParameters)) { defaultArguments = default; return; } // In a scenario like `string Prop { get; } = M();`, the containing symbol could be the synthesized field. // We want to use the associated user-declared symbol instead where possible. var containingMember = ContainingMember() switch { FieldSymbol { AssociatedSymbol: { } symbol } => symbol, var c => c }; defaultArguments = BitVector.Create(parameters.Length); ArrayBuilder<int>? argsToParamsBuilder = null; if (!argsToParamsOpt.IsDefault) { argsToParamsBuilder = ArrayBuilder<int>.GetInstance(argsToParamsOpt.Length); argsToParamsBuilder.AddRange(argsToParamsOpt); } // Params methods can be invoked in normal form, so the strongest assertion we can make is that, if // we're in an expanded context, the last param must be params. The inverse is not necessarily true. Debug.Assert(!expanded || parameters[^1].IsParams); // Params array is filled in the local rewriter var lastIndex = expanded ? ^1 : ^0; var argumentsCount = argumentsBuilder.Count; // Go over missing parameters, inserting default values for optional parameters foreach (var parameter in parameters.AsSpan()[..lastIndex]) { if (!visitedParameters[parameter.Ordinal]) { Debug.Assert(parameter.IsOptional || !assertMissingParametersAreOptional); defaultArguments[argumentsBuilder.Count] = true; argumentsBuilder.Add(bindDefaultArgument(node, parameter, containingMember, enableCallerInfo, diagnostics, argumentsBuilder, argumentsCount, argsToParamsOpt)); if (argumentRefKindsBuilder is { Count: > 0 }) { argumentRefKindsBuilder.Add(RefKind.None); } argsToParamsBuilder?.Add(parameter.Ordinal); } } Debug.Assert(argumentRefKindsBuilder is null || argumentRefKindsBuilder.Count == 0 || argumentRefKindsBuilder.Count == argumentsBuilder.Count); Debug.Assert(argsToParamsBuilder is null || argsToParamsBuilder.Count == argumentsBuilder.Count); if (argsToParamsBuilder is object) { argsToParamsOpt = argsToParamsBuilder.ToImmutableOrNull(); argsToParamsBuilder.Free(); } BoundExpression bindDefaultArgument(SyntaxNode syntax, ParameterSymbol parameter, Symbol containingMember, bool enableCallerInfo, BindingDiagnosticBag diagnostics, ArrayBuilder<BoundExpression> argumentsBuilder, int argumentsCount, ImmutableArray<int> argsToParamsOpt) { TypeSymbol parameterType = parameter.Type; if (Flags.Includes(BinderFlags.ParameterDefaultValue)) { // This is only expected to occur in recursive error scenarios, for example: `object F(object param = F()) { }` // We return a non-error expression here to ensure ERR_DefaultValueMustBeConstant (or another appropriate diagnostics) is produced by the caller. return new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; } var defaultConstantValue = parameter.ExplicitDefaultConstantValue switch { // Bad default values are implicitly replaced with default(T) at call sites. { IsBad: true } => ConstantValue.Null, var constantValue => constantValue }; Debug.Assert((object?)defaultConstantValue != ConstantValue.Unset); var callerSourceLocation = enableCallerInfo ? GetCallerLocation(syntax) : null; BoundExpression defaultValue; if (callerSourceLocation is object && parameter.IsCallerLineNumber) { int line = callerSourceLocation.SourceTree.GetDisplayLineNumber(callerSourceLocation.SourceSpan); defaultValue = new BoundLiteral(syntax, ConstantValue.Create(line), Compilation.GetSpecialType(SpecialType.System_Int32)) { WasCompilerGenerated = true }; } else if (callerSourceLocation is object && parameter.IsCallerFilePath) { string path = callerSourceLocation.SourceTree.GetDisplayPath(callerSourceLocation.SourceSpan, Compilation.Options.SourceReferenceResolver); defaultValue = new BoundLiteral(syntax, ConstantValue.Create(path), Compilation.GetSpecialType(SpecialType.System_String)) { WasCompilerGenerated = true }; } else if (callerSourceLocation is object && parameter.IsCallerMemberName) { var memberName = containingMember.GetMemberCallerName(); defaultValue = new BoundLiteral(syntax, ConstantValue.Create(memberName), Compilation.GetSpecialType(SpecialType.System_String)) { WasCompilerGenerated = true }; } else if (callerSourceLocation is object && getArgumentIndex(parameter.CallerArgumentExpressionParameterIndex, argsToParamsOpt) is int argumentIndex && argumentIndex > -1 && argumentIndex < argumentsCount) { var argument = argumentsBuilder[argumentIndex]; defaultValue = new BoundLiteral(syntax, ConstantValue.Create(argument.Syntax.ToString()), Compilation.GetSpecialType(SpecialType.System_String)) { WasCompilerGenerated = true }; } else if (defaultConstantValue == ConstantValue.NotAvailable) { // There is no constant value given for the parameter in source/metadata. if (parameterType.IsDynamic() || parameterType.SpecialType == SpecialType.System_Object) { // We have something like M([Optional] object x). We have special handling for such situations. defaultValue = GetDefaultParameterSpecialNoConversion(syntax, parameter, diagnostics); } else { // The argument to M([Optional] int x) becomes default(int) defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; } } else if (defaultConstantValue.IsNull) { defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; } else { TypeSymbol constantType = Compilation.GetSpecialType(defaultConstantValue.SpecialType); defaultValue = new BoundLiteral(syntax, defaultConstantValue, constantType) { WasCompilerGenerated = true }; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion conversion = Conversions.ClassifyConversionFromExpression(defaultValue, parameterType, ref useSiteInfo); diagnostics.Add(syntax, useSiteInfo); if (!conversion.IsValid && defaultConstantValue is { SpecialType: SpecialType.System_Decimal or SpecialType.System_DateTime }) { // Usually, if a default constant value fails to convert to the parameter type, we want an error at the call site. // For legacy reasons, decimal and DateTime constants are special. If such a constant fails to convert to the parameter type // then we want to silently replace it with default(ParameterType). defaultValue = new BoundDefaultExpression(syntax, parameterType) { WasCompilerGenerated = true }; } else { if (!conversion.IsValid) { GenerateImplicitConversionError(diagnostics, syntax, conversion, defaultValue, parameterType); } var isCast = conversion.IsExplicit; defaultValue = CreateConversion( defaultValue.Syntax, defaultValue, conversion, isCast, isCast ? new ConversionGroup(conversion, parameter.TypeWithAnnotations) : null, parameterType, diagnostics); } return defaultValue; static int getArgumentIndex(int parameterIndex, ImmutableArray<int> argsToParamsOpt) => argsToParamsOpt.IsDefault ? parameterIndex : argsToParamsOpt.IndexOf(parameterIndex); } } #nullable disable /// <summary> /// Returns false if an implicit 'this' copy will occur due to an instance member invocation in a readonly member. /// </summary> internal bool CheckImplicitThisCopyInReadOnlyMember(BoundExpression receiver, MethodSymbol method, BindingDiagnosticBag diagnostics) { // For now we are warning only in implicit copy scenarios that are only possible with readonly members. // Eventually we will warn on implicit value copies in more scenarios. See https://github.com/dotnet/roslyn/issues/33968. if (receiver is BoundThisReference && receiver.Type.IsValueType && ContainingMemberOrLambda is MethodSymbol containingMethod && containingMethod.IsEffectivelyReadOnly && // Ignore calls to base members. TypeSymbol.Equals(containingMethod.ContainingType, method.ContainingType, TypeCompareKind.ConsiderEverything) && !method.IsEffectivelyReadOnly && method.RequiresInstanceReceiver) { Error(diagnostics, ErrorCode.WRN_ImplicitCopyInReadOnlyMember, receiver.Syntax, method, ThisParameterSymbol.SymbolName); return false; } return true; } /// <param name="node">Invocation syntax node.</param> /// <param name="expression">The syntax for the invoked method, including receiver.</param> private static Location GetLocationForOverloadResolutionDiagnostic(SyntaxNode node, SyntaxNode expression) { if (node != expression) { switch (expression.Kind()) { case SyntaxKind.QualifiedName: return ((QualifiedNameSyntax)expression).Right.GetLocation(); case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: return ((MemberAccessExpressionSyntax)expression).Name.GetLocation(); } } return expression.GetLocation(); } /// <summary> /// Replace a BoundTypeOrValueExpression with a BoundExpression for either a type (if useType is true) /// or a value (if useType is false). Any other node is bound to its natural type. /// </summary> /// <remarks> /// Call this once overload resolution has succeeded on the method group of which the BoundTypeOrValueExpression /// is the receiver. Generally, useType will be true if the chosen method is static and false otherwise. /// </remarks> private BoundExpression ReplaceTypeOrValueReceiver(BoundExpression receiver, bool useType, BindingDiagnosticBag diagnostics) { if ((object)receiver == null) { return null; } switch (receiver.Kind) { case BoundKind.TypeOrValueExpression: var typeOrValue = (BoundTypeOrValueExpression)receiver; if (useType) { diagnostics.AddRange(typeOrValue.Data.TypeDiagnostics); return typeOrValue.Data.TypeExpression; } else { diagnostics.AddRange(typeOrValue.Data.ValueDiagnostics); return CheckValue(typeOrValue.Data.ValueExpression, BindValueKind.RValue, diagnostics); } case BoundKind.QueryClause: // a query clause may wrap a TypeOrValueExpression. var q = (BoundQueryClause)receiver; var value = q.Value; var replaced = ReplaceTypeOrValueReceiver(value, useType, diagnostics); return (value == replaced) ? q : q.Update(replaced, q.DefinedSymbol, q.Operation, q.Cast, q.Binder, q.UnoptimizedForm, q.Type); default: return BindToNaturalType(receiver, diagnostics); } } /// <summary> /// Return the delegate type if this expression represents a delegate. /// </summary> private static NamedTypeSymbol GetDelegateType(BoundExpression expr) { if ((object)expr != null && expr.Kind != BoundKind.TypeExpression) { var type = expr.Type as NamedTypeSymbol; if (((object)type != null) && type.IsDelegateType()) { return type; } } return null; } private BoundCall CreateBadCall( SyntaxNode node, string name, BoundExpression receiver, ImmutableArray<MethodSymbol> methods, LookupResultKind resultKind, ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations, AnalyzedArguments analyzedArguments, bool invokedAsExtensionMethod, bool isDelegate) { MethodSymbol method; ImmutableArray<BoundExpression> args; if (!typeArgumentsWithAnnotations.IsDefaultOrEmpty) { var constructedMethods = ArrayBuilder<MethodSymbol>.GetInstance(); foreach (var m in methods) { constructedMethods.Add(m.ConstructedFrom == m && m.Arity == typeArgumentsWithAnnotations.Length ? m.Construct(typeArgumentsWithAnnotations) : m); } methods = constructedMethods.ToImmutableAndFree(); } if (methods.Length == 1 && !IsUnboundGeneric(methods[0])) { method = methods[0]; } else { var returnType = GetCommonTypeOrReturnType(methods) ?? new ExtendedErrorTypeSymbol(this.Compilation, string.Empty, arity: 0, errorInfo: null); var methodContainer = (object)receiver != null && (object)receiver.Type != null ? receiver.Type : this.ContainingType; method = new ErrorMethodSymbol(methodContainer, returnType, name); } args = BuildArgumentsForErrorRecovery(analyzedArguments, methods); var argNames = analyzedArguments.GetNames(); var argRefKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); receiver = BindToTypeForErrorRecovery(receiver); return BoundCall.ErrorCall(node, receiver, method, args, argNames, argRefKinds, isDelegate, invokedAsExtensionMethod: invokedAsExtensionMethod, originalMethods: methods, resultKind: resultKind, binder: this); } private static bool IsUnboundGeneric(MethodSymbol method) { return method.IsGenericMethod && method.ConstructedFrom() == method; } // Arbitrary limit on the number of parameter lists from overload // resolution candidates considered when binding argument types. // Any additional parameter lists are ignored. internal const int MaxParameterListsForErrorRecovery = 10; private ImmutableArray<BoundExpression> BuildArgumentsForErrorRecovery(AnalyzedArguments analyzedArguments, ImmutableArray<MethodSymbol> methods) { var parameterListList = ArrayBuilder<ImmutableArray<ParameterSymbol>>.GetInstance(); foreach (var m in methods) { if (!IsUnboundGeneric(m) && m.ParameterCount > 0) { parameterListList.Add(m.Parameters); if (parameterListList.Count == MaxParameterListsForErrorRecovery) { break; } } } var result = BuildArgumentsForErrorRecovery(analyzedArguments, parameterListList); parameterListList.Free(); return result; } private ImmutableArray<BoundExpression> BuildArgumentsForErrorRecovery(AnalyzedArguments analyzedArguments, ImmutableArray<PropertySymbol> properties) { var parameterListList = ArrayBuilder<ImmutableArray<ParameterSymbol>>.GetInstance(); foreach (var p in properties) { if (p.ParameterCount > 0) { parameterListList.Add(p.Parameters); if (parameterListList.Count == MaxParameterListsForErrorRecovery) { break; } } } var result = BuildArgumentsForErrorRecovery(analyzedArguments, parameterListList); parameterListList.Free(); return result; } private ImmutableArray<BoundExpression> BuildArgumentsForErrorRecovery(AnalyzedArguments analyzedArguments, IEnumerable<ImmutableArray<ParameterSymbol>> parameterListList) { var discardedDiagnostics = DiagnosticBag.GetInstance(); int argumentCount = analyzedArguments.Arguments.Count; ArrayBuilder<BoundExpression> newArguments = ArrayBuilder<BoundExpression>.GetInstance(argumentCount); newArguments.AddRange(analyzedArguments.Arguments); for (int i = 0; i < argumentCount; i++) { var argument = newArguments[i]; switch (argument.Kind) { case BoundKind.UnboundLambda: { // bind the argument against each applicable parameter var unboundArgument = (UnboundLambda)argument; foreach (var parameterList in parameterListList) { var parameterType = GetCorrespondingParameterType(analyzedArguments, i, parameterList); if (parameterType?.Kind == SymbolKind.NamedType && (object)parameterType.GetDelegateType() != null) { // Just assume we're not in an expression tree for the purposes of error recovery. var discarded = unboundArgument.Bind((NamedTypeSymbol)parameterType, isExpressionTree: false); } } // replace the unbound lambda with its best inferred bound version newArguments[i] = unboundArgument.BindForErrorRecovery(); break; } case BoundKind.OutVariablePendingInference: case BoundKind.DiscardExpression: { if (argument.HasExpressionType()) { break; } var candidateType = getCorrespondingParameterType(i); if (argument.Kind == BoundKind.OutVariablePendingInference) { if ((object)candidateType == null) { newArguments[i] = ((OutVariablePendingInference)argument).FailInference(this, null); } else { newArguments[i] = ((OutVariablePendingInference)argument).SetInferredTypeWithAnnotations(TypeWithAnnotations.Create(candidateType), null); } } else if (argument.Kind == BoundKind.DiscardExpression) { if ((object)candidateType == null) { newArguments[i] = ((BoundDiscardExpression)argument).FailInference(this, null); } else { newArguments[i] = ((BoundDiscardExpression)argument).SetInferredTypeWithAnnotations(TypeWithAnnotations.Create(candidateType)); } } break; } case BoundKind.OutDeconstructVarPendingInference: { newArguments[i] = ((OutDeconstructVarPendingInference)argument).FailInference(this); break; } case BoundKind.Parameter: case BoundKind.Local: { newArguments[i] = BindToTypeForErrorRecovery(argument); break; } default: { newArguments[i] = BindToTypeForErrorRecovery(argument, getCorrespondingParameterType(i)); break; } } } discardedDiagnostics.Free(); return newArguments.ToImmutableAndFree(); TypeSymbol getCorrespondingParameterType(int i) { // See if all applicable parameters have the same type TypeSymbol candidateType = null; foreach (var parameterList in parameterListList) { var parameterType = GetCorrespondingParameterType(analyzedArguments, i, parameterList); if ((object)parameterType != null) { if ((object)candidateType == null) { candidateType = parameterType; } else if (!candidateType.Equals(parameterType, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { // type mismatch candidateType = null; break; } } } return candidateType; } } /// <summary> /// Compute the type of the corresponding parameter, if any. This is used to improve error recovery, /// for bad invocations, not for semantic analysis of correct invocations, so it is a heuristic. /// If no parameter appears to correspond to the given argument, we return null. /// </summary> /// <param name="analyzedArguments">The analyzed argument list</param> /// <param name="i">The index of the argument</param> /// <param name="parameterList">The parameter list to match against</param> /// <returns>The type of the corresponding parameter.</returns> private static TypeSymbol GetCorrespondingParameterType(AnalyzedArguments analyzedArguments, int i, ImmutableArray<ParameterSymbol> parameterList) { string name = analyzedArguments.Name(i); if (name != null) { // look for a parameter by that name foreach (var parameter in parameterList) { if (parameter.Name == name) return parameter.Type; } return null; } return (i < parameterList.Length) ? parameterList[i].Type : null; // CONSIDER: should we handle variable argument lists? } /// <summary> /// Absent parameter types to bind the arguments, we simply use the arguments provided for error recovery. /// </summary> private ImmutableArray<BoundExpression> BuildArgumentsForErrorRecovery(AnalyzedArguments analyzedArguments) { return BuildArgumentsForErrorRecovery(analyzedArguments, Enumerable.Empty<ImmutableArray<ParameterSymbol>>()); } private BoundCall CreateBadCall( SyntaxNode node, BoundExpression expr, LookupResultKind resultKind, AnalyzedArguments analyzedArguments) { TypeSymbol returnType = new ExtendedErrorTypeSymbol(this.Compilation, string.Empty, arity: 0, errorInfo: null); var methodContainer = expr.Type ?? this.ContainingType; MethodSymbol method = new ErrorMethodSymbol(methodContainer, returnType, string.Empty); var args = BuildArgumentsForErrorRecovery(analyzedArguments); var argNames = analyzedArguments.GetNames(); var argRefKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); var originalMethods = (expr.Kind == BoundKind.MethodGroup) ? ((BoundMethodGroup)expr).Methods : ImmutableArray<MethodSymbol>.Empty; return BoundCall.ErrorCall(node, expr, method, args, argNames, argRefKinds, isDelegateCall: false, invokedAsExtensionMethod: false, originalMethods: originalMethods, resultKind: resultKind, binder: this); } private static TypeSymbol GetCommonTypeOrReturnType<TMember>(ImmutableArray<TMember> members) where TMember : Symbol { TypeSymbol type = null; for (int i = 0, n = members.Length; i < n; i++) { TypeSymbol returnType = members[i].GetTypeOrReturnType().Type; if ((object)type == null) { type = returnType; } else if (!TypeSymbol.Equals(type, returnType, TypeCompareKind.ConsiderEverything2)) { return null; } } return type; } private bool TryBindNameofOperator(InvocationExpressionSyntax node, BindingDiagnosticBag diagnostics, out BoundExpression result) { result = null; if (node.Expression.Kind() != SyntaxKind.IdentifierName || ((IdentifierNameSyntax)node.Expression).Identifier.ContextualKind() != SyntaxKind.NameOfKeyword || node.ArgumentList.Arguments.Count != 1) { return false; } ArgumentSyntax argument = node.ArgumentList.Arguments[0]; if (argument.NameColon != null || argument.RefOrOutKeyword != default(SyntaxToken) || InvocableNameofInScope()) { return false; } result = BindNameofOperatorInternal(node, diagnostics); return true; } private BoundExpression BindNameofOperatorInternal(InvocationExpressionSyntax node, BindingDiagnosticBag diagnostics) { CheckFeatureAvailability(node, MessageID.IDS_FeatureNameof, diagnostics); var argument = node.ArgumentList.Arguments[0].Expression; // We relax the instance-vs-static requirement for top-level member access expressions by creating a NameofBinder binder. var nameofBinder = new NameofBinder(argument, this); var boundArgument = nameofBinder.BindExpression(argument, diagnostics); bool syntaxIsOk = CheckSyntaxForNameofArgument(argument, out string name, boundArgument.HasAnyErrors ? BindingDiagnosticBag.Discarded : diagnostics); if (!boundArgument.HasAnyErrors && syntaxIsOk && boundArgument.Kind == BoundKind.MethodGroup) { var methodGroup = (BoundMethodGroup)boundArgument; if (!methodGroup.TypeArgumentsOpt.IsDefaultOrEmpty) { // method group with type parameters not allowed diagnostics.Add(ErrorCode.ERR_NameofMethodGroupWithTypeParameters, argument.Location); } else { nameofBinder.EnsureNameofExpressionSymbols(methodGroup, diagnostics); } } if (boundArgument is BoundNamespaceExpression nsExpr) { diagnostics.AddAssembliesUsedByNamespaceReference(nsExpr.NamespaceSymbol); } boundArgument = BindToNaturalType(boundArgument, diagnostics, reportNoTargetType: false); return new BoundNameOfOperator(node, boundArgument, ConstantValue.Create(name), Compilation.GetSpecialType(SpecialType.System_String)); } private void EnsureNameofExpressionSymbols(BoundMethodGroup methodGroup, BindingDiagnosticBag diagnostics) { // Check that the method group contains something applicable. Otherwise error. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var resolution = ResolveMethodGroup(methodGroup, analyzedArguments: null, isMethodGroupConversion: false, useSiteInfo: ref useSiteInfo); diagnostics.Add(methodGroup.Syntax, useSiteInfo); diagnostics.AddRange(resolution.Diagnostics); if (resolution.IsExtensionMethodGroup) { diagnostics.Add(ErrorCode.ERR_NameofExtensionMethod, methodGroup.Syntax.Location); } } /// <summary> /// Returns true if syntax form is OK (so no errors were reported) /// </summary> private bool CheckSyntaxForNameofArgument(ExpressionSyntax argument, out string name, BindingDiagnosticBag diagnostics, bool top = true) { switch (argument.Kind()) { case SyntaxKind.IdentifierName: { var syntax = (IdentifierNameSyntax)argument; name = syntax.Identifier.ValueText; return true; } case SyntaxKind.GenericName: { var syntax = (GenericNameSyntax)argument; name = syntax.Identifier.ValueText; return true; } case SyntaxKind.SimpleMemberAccessExpression: { var syntax = (MemberAccessExpressionSyntax)argument; bool ok = true; switch (syntax.Expression.Kind()) { case SyntaxKind.BaseExpression: case SyntaxKind.ThisExpression: break; default: ok = CheckSyntaxForNameofArgument(syntax.Expression, out name, diagnostics, false); break; } name = syntax.Name.Identifier.ValueText; return ok; } case SyntaxKind.AliasQualifiedName: { var syntax = (AliasQualifiedNameSyntax)argument; bool ok = true; if (top) { diagnostics.Add(ErrorCode.ERR_AliasQualifiedNameNotAnExpression, argument.Location); ok = false; } name = syntax.Name.Identifier.ValueText; return ok; } case SyntaxKind.ThisExpression: case SyntaxKind.BaseExpression: case SyntaxKind.PredefinedType: name = ""; if (top) goto default; return true; default: { var code = top ? ErrorCode.ERR_ExpressionHasNoName : ErrorCode.ERR_SubexpressionNotInNameof; diagnostics.Add(code, argument.Location); name = ""; return false; } } } /// <summary> /// Helper method that checks whether there is an invocable 'nameof' in scope. /// </summary> private bool InvocableNameofInScope() { var lookupResult = LookupResult.GetInstance(); const LookupOptions options = LookupOptions.AllMethodsOnArityZero | LookupOptions.MustBeInvocableIfMember; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; this.LookupSymbolsWithFallback(lookupResult, SyntaxFacts.GetText(SyntaxKind.NameOfKeyword), useSiteInfo: ref discardedUseSiteInfo, arity: 0, options: options); var result = lookupResult.IsMultiViable; lookupResult.Free(); return result; } #nullable enable private BoundFunctionPointerInvocation BindFunctionPointerInvocation(SyntaxNode node, BoundExpression boundExpression, AnalyzedArguments analyzedArguments, BindingDiagnosticBag diagnostics) { RoslynDebug.Assert(boundExpression.Type is FunctionPointerTypeSymbol); var funcPtr = (FunctionPointerTypeSymbol)boundExpression.Type; var overloadResolutionResult = OverloadResolutionResult<FunctionPointerMethodSymbol>.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var methodsBuilder = ArrayBuilder<FunctionPointerMethodSymbol>.GetInstance(1); methodsBuilder.Add(funcPtr.Signature); OverloadResolution.FunctionPointerOverloadResolution( methodsBuilder, analyzedArguments, overloadResolutionResult, ref useSiteInfo); diagnostics.Add(node, useSiteInfo); if (!overloadResolutionResult.Succeeded) { ImmutableArray<FunctionPointerMethodSymbol> methods = methodsBuilder.ToImmutableAndFree(); overloadResolutionResult.ReportDiagnostics( binder: this, node.Location, nodeOpt: null, diagnostics, name: null, boundExpression, boundExpression.Syntax, analyzedArguments, methods, typeContainingConstructor: null, delegateTypeBeingInvoked: null, returnRefKind: funcPtr.Signature.RefKind); return new BoundFunctionPointerInvocation( node, boundExpression, BuildArgumentsForErrorRecovery(analyzedArguments, StaticCast<MethodSymbol>.From(methods)), analyzedArguments.RefKinds.ToImmutableOrNull(), LookupResultKind.OverloadResolutionFailure, funcPtr.Signature.ReturnType, hasErrors: true); } methodsBuilder.Free(); MemberResolutionResult<FunctionPointerMethodSymbol> methodResult = overloadResolutionResult.ValidResult; CoerceArguments( methodResult, analyzedArguments.Arguments, diagnostics, receiverType: null, receiverRefKind: null, receiverEscapeScope: Binder.ExternalScope); var args = analyzedArguments.Arguments.ToImmutable(); var refKinds = analyzedArguments.RefKinds.ToImmutableOrNull(); bool hasErrors = ReportUnsafeIfNotAllowed(node, diagnostics); if (!hasErrors) { hasErrors = !CheckInvocationArgMixing( node, funcPtr.Signature, receiverOpt: null, funcPtr.Signature.Parameters, args, methodResult.Result.ArgsToParamsOpt, LocalScopeDepth, diagnostics); } return new BoundFunctionPointerInvocation( node, boundExpression, args, refKinds, LookupResultKind.Viable, funcPtr.Signature.ReturnType, hasErrors); } } }
1
dotnet/roslyn
55,125
Don't use DefaultInterpolatedStringHandler in expression trees
Introduces a binder flag to track whether we are currently in an expression tree or not. Fixes https://github.com/dotnet/roslyn/issues/55114.
333fred
2021-07-26T22:08:39Z
2021-07-27T19:33:24Z
5840335153dcca42570a853cdacd06d660fe9596
cfc12ce93ce377c4b9581ccf88403e6740d63977
Don't use DefaultInterpolatedStringHandler in expression trees. Introduces a binder flag to track whether we are currently in an expression tree or not. Fixes https://github.com/dotnet/roslyn/issues/55114.
./src/Compilers/CSharp/Portable/Binder/Binder_Statements.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.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This portion of the binder converts StatementSyntax nodes into BoundStatements /// </summary> internal partial class Binder { /// <summary> /// This is the set of parameters and local variables that were used as arguments to /// lock or using statements in enclosing scopes. /// </summary> /// <remarks> /// using (x) { } // x counts /// using (IDisposable y = null) { } // y does not count /// </remarks> internal virtual ImmutableHashSet<Symbol> LockedOrDisposedVariables { get { return Next.LockedOrDisposedVariables; } } /// <remarks> /// Noteworthy override is in MemberSemanticModel.IncrementalBinder (used for caching). /// </remarks> public virtual BoundStatement BindStatement(StatementSyntax node, BindingDiagnosticBag diagnostics) { if (node.AttributeLists.Count > 0) { var attributeList = node.AttributeLists[0]; // Currently, attributes are only allowed on local-functions. if (node.Kind() == SyntaxKind.LocalFunctionStatement) { CheckFeatureAvailability(attributeList, MessageID.IDS_FeatureLocalFunctionAttributes, diagnostics); } else if (node.Kind() != SyntaxKind.Block) { // Don't explicitly error here for blocks. Some codepaths bypass BindStatement // to directly call BindBlock. Error(diagnostics, ErrorCode.ERR_AttributesNotAllowed, attributeList); } } Debug.Assert(node != null); BoundStatement result; switch (node.Kind()) { case SyntaxKind.Block: result = BindBlock((BlockSyntax)node, diagnostics); break; case SyntaxKind.LocalDeclarationStatement: result = BindLocalDeclarationStatement((LocalDeclarationStatementSyntax)node, diagnostics); break; case SyntaxKind.LocalFunctionStatement: result = BindLocalFunctionStatement((LocalFunctionStatementSyntax)node, diagnostics); break; case SyntaxKind.ExpressionStatement: result = BindExpressionStatement((ExpressionStatementSyntax)node, diagnostics); break; case SyntaxKind.IfStatement: result = BindIfStatement((IfStatementSyntax)node, diagnostics); break; case SyntaxKind.SwitchStatement: result = BindSwitchStatement((SwitchStatementSyntax)node, diagnostics); break; case SyntaxKind.DoStatement: result = BindDo((DoStatementSyntax)node, diagnostics); break; case SyntaxKind.WhileStatement: result = BindWhile((WhileStatementSyntax)node, diagnostics); break; case SyntaxKind.ForStatement: result = BindFor((ForStatementSyntax)node, diagnostics); break; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: result = BindForEach((CommonForEachStatementSyntax)node, diagnostics); break; case SyntaxKind.BreakStatement: result = BindBreak((BreakStatementSyntax)node, diagnostics); break; case SyntaxKind.ContinueStatement: result = BindContinue((ContinueStatementSyntax)node, diagnostics); break; case SyntaxKind.ReturnStatement: result = BindReturn((ReturnStatementSyntax)node, diagnostics); break; case SyntaxKind.FixedStatement: result = BindFixedStatement((FixedStatementSyntax)node, diagnostics); break; case SyntaxKind.LabeledStatement: result = BindLabeled((LabeledStatementSyntax)node, diagnostics); break; case SyntaxKind.GotoStatement: case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoDefaultStatement: result = BindGoto((GotoStatementSyntax)node, diagnostics); break; case SyntaxKind.TryStatement: result = BindTryStatement((TryStatementSyntax)node, diagnostics); break; case SyntaxKind.EmptyStatement: result = BindEmpty((EmptyStatementSyntax)node); break; case SyntaxKind.ThrowStatement: result = BindThrow((ThrowStatementSyntax)node, diagnostics); break; case SyntaxKind.UnsafeStatement: result = BindUnsafeStatement((UnsafeStatementSyntax)node, diagnostics); break; case SyntaxKind.UncheckedStatement: case SyntaxKind.CheckedStatement: result = BindCheckedStatement((CheckedStatementSyntax)node, diagnostics); break; case SyntaxKind.UsingStatement: result = BindUsingStatement((UsingStatementSyntax)node, diagnostics); break; case SyntaxKind.YieldBreakStatement: result = BindYieldBreakStatement((YieldStatementSyntax)node, diagnostics); break; case SyntaxKind.YieldReturnStatement: result = BindYieldReturnStatement((YieldStatementSyntax)node, diagnostics); break; case SyntaxKind.LockStatement: result = BindLockStatement((LockStatementSyntax)node, diagnostics); break; default: // NOTE: We could probably throw an exception here, but it's conceivable // that a non-parser syntax tree could reach this point with an unexpected // SyntaxKind and we don't want to throw if that occurs. result = new BoundBadStatement(node, ImmutableArray<BoundNode>.Empty, hasErrors: true); break; } BoundBlock block; Debug.Assert(result.WasCompilerGenerated == false || (result.Kind == BoundKind.Block && (block = (BoundBlock)result).Statements.Length == 1 && block.Statements.Single().WasCompilerGenerated == false), "Synthetic node would not get cached"); Debug.Assert(result.Syntax is StatementSyntax, "BoundStatement should be associated with a statement syntax."); Debug.Assert(System.Linq.Enumerable.Contains(result.Syntax.AncestorsAndSelf(), node), @"Bound statement (or one of its parents) should have same syntax as the given syntax node. Otherwise it may be confusing to the binder cache that uses syntax node as keys."); return result; } private BoundStatement BindCheckedStatement(CheckedStatementSyntax node, BindingDiagnosticBag diagnostics) { return BindEmbeddedBlock(node.Block, diagnostics); } private BoundStatement BindUnsafeStatement(UnsafeStatementSyntax node, BindingDiagnosticBag diagnostics) { var unsafeBinder = this.GetBinder(node); if (!this.Compilation.Options.AllowUnsafe) { Error(diagnostics, ErrorCode.ERR_IllegalUnsafe, node.UnsafeKeyword); } else if (this.IsIndirectlyInIterator) // called *after* we know the binder map has been created. { // Spec 8.2: "An iterator block always defines a safe context, even when its declaration // is nested in an unsafe context." Error(diagnostics, ErrorCode.ERR_IllegalInnerUnsafe, node.UnsafeKeyword); } return BindEmbeddedBlock(node.Block, diagnostics); } private BoundStatement BindFixedStatement(FixedStatementSyntax node, BindingDiagnosticBag diagnostics) { var fixedBinder = this.GetBinder(node); Debug.Assert(fixedBinder != null); fixedBinder.ReportUnsafeIfNotAllowed(node, diagnostics); return fixedBinder.BindFixedStatementParts(node, diagnostics); } private BoundStatement BindFixedStatementParts(FixedStatementSyntax node, BindingDiagnosticBag diagnostics) { VariableDeclarationSyntax declarationSyntax = node.Declaration; ImmutableArray<BoundLocalDeclaration> declarations; BindForOrUsingOrFixedDeclarations(declarationSyntax, LocalDeclarationKind.FixedVariable, diagnostics, out declarations); Debug.Assert(!declarations.IsEmpty); BoundMultipleLocalDeclarations boundMultipleDeclarations = new BoundMultipleLocalDeclarations(declarationSyntax, declarations); BoundStatement boundBody = BindPossibleEmbeddedStatement(node.Statement, diagnostics); return new BoundFixedStatement(node, GetDeclaredLocalsForScope(node), boundMultipleDeclarations, boundBody); } private void CheckRequiredLangVersionForAsyncIteratorMethods(BindingDiagnosticBag diagnostics) { var method = (MethodSymbol)this.ContainingMemberOrLambda; if (method.IsAsync) { MessageID.IDS_FeatureAsyncStreams.CheckFeatureAvailability( diagnostics, method.DeclaringCompilation, method.Locations[0]); } } protected virtual void ValidateYield(YieldStatementSyntax node, BindingDiagnosticBag diagnostics) { Next?.ValidateYield(node, diagnostics); } private BoundStatement BindYieldReturnStatement(YieldStatementSyntax node, BindingDiagnosticBag diagnostics) { ValidateYield(node, diagnostics); TypeSymbol elementType = GetIteratorElementType().Type; BoundExpression argument = (node.Expression == null) ? BadExpression(node).MakeCompilerGenerated() : BindValue(node.Expression, diagnostics, BindValueKind.RValue); argument = ValidateEscape(argument, ExternalScope, isByRef: false, diagnostics: diagnostics); if (!argument.HasAnyErrors) { argument = GenerateConversionForAssignment(elementType, argument, diagnostics); } else { argument = BindToTypeForErrorRecovery(argument); } // NOTE: it's possible that more than one of these conditions is satisfied and that // we won't report the syntactically innermost. However, dev11 appears to check // them in this order, regardless of syntactic nesting (StatementBinder::bindYield). if (this.Flags.Includes(BinderFlags.InFinallyBlock)) { Error(diagnostics, ErrorCode.ERR_BadYieldInFinally, node.YieldKeyword); } else if (this.Flags.Includes(BinderFlags.InTryBlockOfTryCatch)) { Error(diagnostics, ErrorCode.ERR_BadYieldInTryOfCatch, node.YieldKeyword); } else if (this.Flags.Includes(BinderFlags.InCatchBlock)) { Error(diagnostics, ErrorCode.ERR_BadYieldInCatch, node.YieldKeyword); } else if (BindingTopLevelScriptCode) { Error(diagnostics, ErrorCode.ERR_YieldNotAllowedInScript, node.YieldKeyword); } CheckRequiredLangVersionForAsyncIteratorMethods(diagnostics); return new BoundYieldReturnStatement(node, argument); } private BoundStatement BindYieldBreakStatement(YieldStatementSyntax node, BindingDiagnosticBag diagnostics) { if (this.Flags.Includes(BinderFlags.InFinallyBlock)) { Error(diagnostics, ErrorCode.ERR_BadYieldInFinally, node.YieldKeyword); } else if (BindingTopLevelScriptCode) { Error(diagnostics, ErrorCode.ERR_YieldNotAllowedInScript, node.YieldKeyword); } ValidateYield(node, diagnostics); CheckRequiredLangVersionForAsyncIteratorMethods(diagnostics); return new BoundYieldBreakStatement(node); } private BoundStatement BindLockStatement(LockStatementSyntax node, BindingDiagnosticBag diagnostics) { var lockBinder = this.GetBinder(node); Debug.Assert(lockBinder != null); return lockBinder.BindLockStatementParts(diagnostics, lockBinder); } internal virtual BoundStatement BindLockStatementParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindLockStatementParts(diagnostics, originalBinder); } private BoundStatement BindUsingStatement(UsingStatementSyntax node, BindingDiagnosticBag diagnostics) { var usingBinder = this.GetBinder(node); Debug.Assert(usingBinder != null); return usingBinder.BindUsingStatementParts(diagnostics, usingBinder); } internal virtual BoundStatement BindUsingStatementParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindUsingStatementParts(diagnostics, originalBinder); } internal BoundStatement BindPossibleEmbeddedStatement(StatementSyntax node, BindingDiagnosticBag diagnostics) { Binder binder; switch (node.Kind()) { case SyntaxKind.LocalDeclarationStatement: // Local declarations are not legal in contexts where we need embedded statements. diagnostics.Add(ErrorCode.ERR_BadEmbeddedStmt, node.GetLocation()); // fall through goto case SyntaxKind.ExpressionStatement; case SyntaxKind.ExpressionStatement: case SyntaxKind.LockStatement: case SyntaxKind.IfStatement: case SyntaxKind.YieldReturnStatement: case SyntaxKind.ReturnStatement: case SyntaxKind.ThrowStatement: binder = this.GetBinder(node); Debug.Assert(binder != null); return binder.WrapWithVariablesIfAny(node, binder.BindStatement(node, diagnostics)); case SyntaxKind.LabeledStatement: case SyntaxKind.LocalFunctionStatement: // Labeled statements and local function statements are not legal in contexts where we need embedded statements. diagnostics.Add(ErrorCode.ERR_BadEmbeddedStmt, node.GetLocation()); binder = this.GetBinder(node); Debug.Assert(binder != null); return binder.WrapWithVariablesAndLocalFunctionsIfAny(node, binder.BindStatement(node, diagnostics)); case SyntaxKind.SwitchStatement: var switchStatement = (SwitchStatementSyntax)node; binder = this.GetBinder(switchStatement.Expression); Debug.Assert(binder != null); return binder.WrapWithVariablesIfAny(switchStatement.Expression, binder.BindStatement(node, diagnostics)); case SyntaxKind.EmptyStatement: var emptyStatement = (EmptyStatementSyntax)node; if (!emptyStatement.SemicolonToken.IsMissing) { switch (node.Parent.Kind()) { case SyntaxKind.ForStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: case SyntaxKind.WhileStatement: // For loop constructs, only warn if we see a block following the statement. // That indicates code like: "while (x) ; { }" // which is most likely a bug. if (emptyStatement.SemicolonToken.GetNextToken().Kind() != SyntaxKind.OpenBraceToken) { break; } goto default; default: // For non-loop constructs, always warn. This is for code like: // "if (x) ;" which is almost certainly a bug. diagnostics.Add(ErrorCode.WRN_PossibleMistakenNullStatement, node.GetLocation()); break; } } // fall through goto default; default: return BindStatement(node, diagnostics); } } private BoundExpression BindThrownExpression(ExpressionSyntax exprSyntax, BindingDiagnosticBag diagnostics, ref bool hasErrors) { var boundExpr = BindValue(exprSyntax, diagnostics, BindValueKind.RValue); if (Compilation.LanguageVersion < MessageID.IDS_FeatureSwitchExpression.RequiredVersion()) { // This is the pre-C# 8 algorithm for binding a thrown expression. // SPEC VIOLATION: The spec requires the thrown exception to have a type, and that the type // be System.Exception or derived from System.Exception. (Or, if a type parameter, to have // an effective base class that meets that criterion.) However, we allow the literal null // to be thrown, even though it does not meet that criterion and will at runtime always // produce a null reference exception. if (!boundExpr.IsLiteralNull()) { boundExpr = BindToNaturalType(boundExpr, diagnostics); var type = boundExpr.Type; // If the expression is a lambda, anonymous method, or method group then it will // have no compile-time type; give the same error as if the type was wrong. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if ((object)type == null || !type.IsErrorType() && !Compilation.IsExceptionType(type.EffectiveType(ref useSiteInfo), ref useSiteInfo)) { diagnostics.Add(ErrorCode.ERR_BadExceptionType, exprSyntax.Location); hasErrors = true; diagnostics.Add(exprSyntax, useSiteInfo); } else { diagnostics.AddDependencies(useSiteInfo); } } } else { // In C# 8 and later we follow the ECMA specification, which neatly handles null and expressions of exception type. boundExpr = GenerateConversionForAssignment(GetWellKnownType(WellKnownType.System_Exception, diagnostics, exprSyntax), boundExpr, diagnostics); } return boundExpr; } private BoundStatement BindThrow(ThrowStatementSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression boundExpr = null; bool hasErrors = false; ExpressionSyntax exprSyntax = node.Expression; if (exprSyntax != null) { boundExpr = BindThrownExpression(exprSyntax, diagnostics, ref hasErrors); } else if (!this.Flags.Includes(BinderFlags.InCatchBlock)) { diagnostics.Add(ErrorCode.ERR_BadEmptyThrow, node.ThrowKeyword.GetLocation()); hasErrors = true; } else if (this.Flags.Includes(BinderFlags.InNestedFinallyBlock)) { // There's a special error code for a rethrow in a finally clause in a catch clause. // Best guess interpretation: if an exception occurs within the nested try block // (i.e. the one in the catch clause, to which the finally clause is attached), // then it's not clear whether the runtime will try to rethrow the "inner" exception // or the "outer" exception. For this reason, the case is disallowed. diagnostics.Add(ErrorCode.ERR_BadEmptyThrowInFinally, node.ThrowKeyword.GetLocation()); hasErrors = true; } return new BoundThrowStatement(node, boundExpr, hasErrors); } private static BoundStatement BindEmpty(EmptyStatementSyntax node) { return new BoundNoOpStatement(node, NoOpStatementFlavor.Default); } private BoundLabeledStatement BindLabeled(LabeledStatementSyntax node, BindingDiagnosticBag diagnostics) { // TODO: verify that goto label lookup was valid (e.g. error checking of symbol resolution for labels) bool hasError = false; var result = LookupResult.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var binder = this.LookupSymbolsWithFallback(result, node.Identifier.ValueText, arity: 0, useSiteInfo: ref useSiteInfo, options: LookupOptions.LabelsOnly); // result.Symbols can be empty in some malformed code, e.g. when a labeled statement is used an embedded statement in an if or foreach statement // In this case we create new label symbol on the fly, and an error is reported by parser var symbol = result.Symbols.Count > 0 && result.IsMultiViable ? (LabelSymbol)result.Symbols.First() : new SourceLabelSymbol((MethodSymbol)ContainingMemberOrLambda, node.Identifier); if (!symbol.IdentifierNodeOrToken.IsToken || symbol.IdentifierNodeOrToken.AsToken() != node.Identifier) { Error(diagnostics, ErrorCode.ERR_DuplicateLabel, node.Identifier, node.Identifier.ValueText); hasError = true; } // check to see if this label (illegally) hides a label from an enclosing scope if (binder != null) { result.Clear(); binder.Next.LookupSymbolsWithFallback(result, node.Identifier.ValueText, arity: 0, useSiteInfo: ref useSiteInfo, options: LookupOptions.LabelsOnly); if (result.IsMultiViable) { // The label '{0}' shadows another label by the same name in a contained scope Error(diagnostics, ErrorCode.ERR_LabelShadow, node.Identifier, node.Identifier.ValueText); hasError = true; } } diagnostics.Add(node, useSiteInfo); result.Free(); var body = BindStatement(node.Statement, diagnostics); return new BoundLabeledStatement(node, symbol, body, hasError); } private BoundStatement BindGoto(GotoStatementSyntax node, BindingDiagnosticBag diagnostics) { switch (node.Kind()) { case SyntaxKind.GotoStatement: var expression = BindLabel(node.Expression, diagnostics); var boundLabel = expression as BoundLabel; if (boundLabel == null) { // diagnostics already reported return new BoundBadStatement(node, ImmutableArray.Create<BoundNode>(expression), true); } var symbol = boundLabel.Label; return new BoundGotoStatement(node, symbol, null, boundLabel); case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoDefaultStatement: // SPEC: If the goto case statement is not enclosed by a switch statement, a compile-time error occurs. // SPEC: If the goto default statement is not enclosed by a switch statement, a compile-time error occurs. SwitchBinder binder = GetSwitchBinder(this); if (binder == null) { Error(diagnostics, ErrorCode.ERR_InvalidGotoCase, node); ImmutableArray<BoundNode> childNodes; if (node.Expression != null) { var value = BindRValueWithoutTargetType(node.Expression, BindingDiagnosticBag.Discarded); childNodes = ImmutableArray.Create<BoundNode>(value); } else { childNodes = ImmutableArray<BoundNode>.Empty; } return new BoundBadStatement(node, childNodes, true); } return binder.BindGotoCaseOrDefault(node, this, diagnostics); default: throw ExceptionUtilities.UnexpectedValue(node.Kind()); } } private BoundStatement BindLocalFunctionStatement(LocalFunctionStatementSyntax node, BindingDiagnosticBag diagnostics) { // already defined symbol in containing block var localSymbol = this.LookupLocalFunction(node.Identifier); var hasErrors = localSymbol.ScopeBinder .ValidateDeclarationNameConflictsInScope(localSymbol, diagnostics); BoundBlock blockBody = null; BoundBlock expressionBody = null; if (node.Body != null) { blockBody = runAnalysis(BindEmbeddedBlock(node.Body, diagnostics), diagnostics); if (node.ExpressionBody != null) { expressionBody = runAnalysis(BindExpressionBodyAsBlock(node.ExpressionBody, BindingDiagnosticBag.Discarded), BindingDiagnosticBag.Discarded); } } else if (node.ExpressionBody != null) { expressionBody = runAnalysis(BindExpressionBodyAsBlock(node.ExpressionBody, diagnostics), diagnostics); } else if (!hasErrors && (!localSymbol.IsExtern || !localSymbol.IsStatic)) { hasErrors = true; diagnostics.Add(ErrorCode.ERR_LocalFunctionMissingBody, localSymbol.Locations[0], localSymbol); } if (!hasErrors && (blockBody != null || expressionBody != null) && localSymbol.IsExtern) { hasErrors = true; diagnostics.Add(ErrorCode.ERR_ExternHasBody, localSymbol.Locations[0], localSymbol); } Debug.Assert(blockBody != null || expressionBody != null || (localSymbol.IsExtern && localSymbol.IsStatic) || hasErrors); localSymbol.GetDeclarationDiagnostics(diagnostics); Symbol.CheckForBlockAndExpressionBody( node.Body, node.ExpressionBody, node, diagnostics); return new BoundLocalFunctionStatement(node, localSymbol, blockBody, expressionBody, hasErrors); BoundBlock runAnalysis(BoundBlock block, BindingDiagnosticBag blockDiagnostics) { if (block != null) { // Have to do ControlFlowPass here because in MethodCompiler, we don't call this for synthed methods // rather we go directly to LowerBodyOrInitializer, which skips over flow analysis (which is in CompileMethod) // (the same thing - calling ControlFlowPass.Analyze in the lowering - is done for lambdas) // It's a bit of code duplication, but refactoring would make things worse. // However, we don't need to report diagnostics here. They will be reported when analyzing the parent method. var ignored = DiagnosticBag.GetInstance(); var endIsReachable = ControlFlowPass.Analyze(localSymbol.DeclaringCompilation, localSymbol, block, ignored); ignored.Free(); if (endIsReachable) { if (ImplicitReturnIsOkay(localSymbol)) { block = FlowAnalysisPass.AppendImplicitReturn(block, localSymbol); } else { blockDiagnostics.Add(ErrorCode.ERR_ReturnExpected, localSymbol.Locations[0], localSymbol); } } } return block; } } private bool ImplicitReturnIsOkay(MethodSymbol method) { return method.ReturnsVoid || method.IsIterator || method.IsAsyncEffectivelyReturningTask(this.Compilation); } public BoundStatement BindExpressionStatement(ExpressionStatementSyntax node, BindingDiagnosticBag diagnostics) { return BindExpressionStatement(node, node.Expression, node.AllowsAnyExpression, diagnostics); } private BoundExpressionStatement BindExpressionStatement(CSharpSyntaxNode node, ExpressionSyntax syntax, bool allowsAnyExpression, BindingDiagnosticBag diagnostics) { BoundExpressionStatement expressionStatement; var expression = BindRValueWithoutTargetType(syntax, diagnostics); ReportSuppressionIfNeeded(expression, diagnostics); if (!allowsAnyExpression && !IsValidStatementExpression(syntax, expression)) { if (!node.HasErrors) { Error(diagnostics, ErrorCode.ERR_IllegalStatement, syntax); } expressionStatement = new BoundExpressionStatement(node, expression, hasErrors: true); } else { expressionStatement = new BoundExpressionStatement(node, expression); } CheckForUnobservedAwaitable(expression, diagnostics); return expressionStatement; } /// <summary> /// Report an error if this is an awaitable async method invocation that is not being awaited. /// </summary> /// <remarks> /// The checks here are equivalent to StatementBinder::CheckForUnobservedAwaitable() in the native compiler. /// </remarks> private void CheckForUnobservedAwaitable(BoundExpression expression, BindingDiagnosticBag diagnostics) { if (CouldBeAwaited(expression)) { Error(diagnostics, ErrorCode.WRN_UnobservedAwaitableExpression, expression.Syntax); } } internal BoundStatement BindLocalDeclarationStatement(LocalDeclarationStatementSyntax node, BindingDiagnosticBag diagnostics) { if (node.UsingKeyword != default) { return BindUsingDeclarationStatementParts(node, diagnostics); } else { return BindDeclarationStatementParts(node, diagnostics); } } private BoundStatement BindUsingDeclarationStatementParts(LocalDeclarationStatementSyntax node, BindingDiagnosticBag diagnostics) { var usingDeclaration = UsingStatementBinder.BindUsingStatementOrDeclarationFromParts(node, node.UsingKeyword, node.AwaitKeyword, originalBinder: this, usingBinderOpt: null, diagnostics); Debug.Assert(usingDeclaration is BoundUsingLocalDeclarations); return usingDeclaration; } private BoundStatement BindDeclarationStatementParts(LocalDeclarationStatementSyntax node, BindingDiagnosticBag diagnostics) { var typeSyntax = node.Declaration.Type.SkipRef(out _); bool isConst = node.IsConst; bool isVar; AliasSymbol alias; TypeWithAnnotations declType = BindVariableTypeWithAnnotations(node.Declaration, diagnostics, typeSyntax, ref isConst, isVar: out isVar, alias: out alias); var kind = isConst ? LocalDeclarationKind.Constant : LocalDeclarationKind.RegularVariable; var variableList = node.Declaration.Variables; int variableCount = variableList.Count; if (variableCount == 1) { return BindVariableDeclaration(kind, isVar, variableList[0], typeSyntax, declType, alias, diagnostics, includeBoundType: true, associatedSyntaxNode: node); } else { BoundLocalDeclaration[] boundDeclarations = new BoundLocalDeclaration[variableCount]; int i = 0; foreach (var variableDeclarationSyntax in variableList) { bool includeBoundType = i == 0; //To avoid duplicated expressions, only the first declaration should contain the bound type. boundDeclarations[i++] = BindVariableDeclaration(kind, isVar, variableDeclarationSyntax, typeSyntax, declType, alias, diagnostics, includeBoundType); } return new BoundMultipleLocalDeclarations(node, boundDeclarations.AsImmutableOrNull()); } } /// <summary> /// Checks for a Dispose method on <paramref name="expr"/> and returns its <see cref="MethodSymbol"/> if found. /// </summary> /// <param name="expr">Expression on which to perform lookup</param> /// <param name="syntaxNode">The syntax node to perform lookup on</param> /// <param name="diagnostics">Populated with invocation errors, and warnings of near misses</param> /// <returns>The <see cref="MethodSymbol"/> of the Dispose method if one is found, otherwise null.</returns> internal MethodSymbol TryFindDisposePatternMethod(BoundExpression expr, SyntaxNode syntaxNode, bool hasAwait, BindingDiagnosticBag diagnostics) { Debug.Assert(expr is object); Debug.Assert(expr.Type is object); Debug.Assert(expr.Type.IsRefLikeType || hasAwait); // pattern dispose lookup is only valid on ref structs or asynchronous usings var result = PerformPatternMethodLookup(expr, hasAwait ? WellKnownMemberNames.DisposeAsyncMethodName : WellKnownMemberNames.DisposeMethodName, syntaxNode, diagnostics, out var disposeMethod); if (disposeMethod?.IsExtensionMethod == true) { // Extension methods should just be ignored, rather than rejected after-the-fact // Tracked by https://github.com/dotnet/roslyn/issues/32767 // extension methods do not contribute to pattern-based disposal disposeMethod = null; } else if ((!hasAwait && disposeMethod?.ReturnsVoid == false) || result == PatternLookupResult.NotAMethod) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if (this.IsAccessible(disposeMethod, ref useSiteInfo)) { diagnostics.Add(ErrorCode.WRN_PatternBadSignature, syntaxNode.Location, expr.Type, MessageID.IDS_Disposable.Localize(), disposeMethod); } diagnostics.Add(syntaxNode, useSiteInfo); disposeMethod = null; } return disposeMethod; } private TypeWithAnnotations BindVariableTypeWithAnnotations(CSharpSyntaxNode declarationNode, BindingDiagnosticBag diagnostics, TypeSyntax typeSyntax, ref bool isConst, out bool isVar, out AliasSymbol alias) { Debug.Assert( declarationNode is VariableDesignationSyntax || declarationNode.Kind() == SyntaxKind.VariableDeclaration || declarationNode.Kind() == SyntaxKind.DeclarationExpression || declarationNode.Kind() == SyntaxKind.DiscardDesignation); // If the type is "var" then suppress errors when binding it. "var" might be a legal type // or it might not; if it is not then we do not want to report an error. If it is, then // we want to treat the declaration as an explicitly typed declaration. TypeWithAnnotations declType = BindTypeOrVarKeyword(typeSyntax.SkipRef(out _), diagnostics, out isVar, out alias); Debug.Assert(declType.HasType || isVar); if (isVar) { // There are a number of ways in which a var decl can be illegal, but in these // cases we should report an error and then keep right on going with the inference. if (isConst) { Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableCannotBeConst, declarationNode); // Keep processing it as a non-const local. isConst = false; } // In the dev10 compiler the error recovery semantics for the illegal case // "var x = 10, y = 123.4;" are somewhat undesirable. // // First off, this is an error because a straw poll of language designers and // users showed that there was no consensus on whether the above should mean // "double x = 10, y = 123.4;", taking the best type available and substituting // that for "var", or treating it as "var x = 10; var y = 123.4;" -- since there // was no consensus we decided to simply make it illegal. // // In dev10 for error recovery in the IDE we do an odd thing -- we simply take // the type of the first variable and use it. So that is "int x = 10, y = 123.4;". // // This seems less than ideal. In the error recovery scenario it probably makes // more sense to treat that as "var x = 10; var y = 123.4;" and do each inference // separately. if (declarationNode.Parent.Kind() == SyntaxKind.LocalDeclarationStatement && ((VariableDeclarationSyntax)declarationNode).Variables.Count > 1 && !declarationNode.HasErrors) { Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, declarationNode); } } else { // In the native compiler when given a situation like // // D[] x; // // where D is a static type we report both that D cannot be an element type // of an array, and that D[] is not a valid type for a local variable. // This seems silly; the first error is entirely sufficient. We no longer // produce additional errors for local variables of arrays of static types. if (declType.IsStatic) { Error(diagnostics, ErrorCode.ERR_VarDeclIsStaticClass, typeSyntax, declType.Type); } if (isConst && !declType.Type.CanBeConst()) { Error(diagnostics, ErrorCode.ERR_BadConstType, typeSyntax, declType.Type); // Keep processing it as a non-const local. isConst = false; } } return declType; } internal BoundExpression BindInferredVariableInitializer(BindingDiagnosticBag diagnostics, RefKind refKind, EqualsValueClauseSyntax initializer, CSharpSyntaxNode errorSyntax) { BindValueKind valueKind; ExpressionSyntax value; IsInitializerRefKindValid(initializer, initializer, refKind, diagnostics, out valueKind, out value); // The return value isn't important here; we just want the diagnostics and the BindValueKind return BindInferredVariableInitializer(diagnostics, value, valueKind, errorSyntax); } // The location where the error is reported might not be the initializer. protected BoundExpression BindInferredVariableInitializer(BindingDiagnosticBag diagnostics, ExpressionSyntax initializer, BindValueKind valueKind, CSharpSyntaxNode errorSyntax) { if (initializer == null) { if (!errorSyntax.HasErrors) { Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, errorSyntax); } return null; } if (initializer.Kind() == SyntaxKind.ArrayInitializerExpression) { var result = BindUnexpectedArrayInitializer((InitializerExpressionSyntax)initializer, diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableAssignedArrayInitializer, errorSyntax); return CheckValue(result, valueKind, diagnostics); } BoundExpression value = BindValue(initializer, diagnostics, valueKind); BoundExpression expression = value.Kind is BoundKind.UnboundLambda or BoundKind.MethodGroup ? BindToInferredDelegateType(value, diagnostics) : BindToNaturalType(value, diagnostics); // Certain expressions (null literals, method groups and anonymous functions) have no type of // their own and therefore cannot be the initializer of an implicitly typed local. if (!expression.HasAnyErrors && !expression.HasExpressionType()) { // Cannot assign {0} to an implicitly-typed local variable Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, errorSyntax, expression.Display); } return expression; } private static bool IsInitializerRefKindValid( EqualsValueClauseSyntax initializer, CSharpSyntaxNode node, RefKind variableRefKind, BindingDiagnosticBag diagnostics, out BindValueKind valueKind, out ExpressionSyntax value) { RefKind expressionRefKind = RefKind.None; value = initializer?.Value.CheckAndUnwrapRefExpression(diagnostics, out expressionRefKind); if (variableRefKind == RefKind.None) { valueKind = BindValueKind.RValue; if (expressionRefKind == RefKind.Ref) { Error(diagnostics, ErrorCode.ERR_InitializeByValueVariableWithReference, node); return false; } } else { valueKind = variableRefKind == RefKind.RefReadOnly ? BindValueKind.ReadonlyRef : BindValueKind.RefOrOut; if (initializer == null) { Error(diagnostics, ErrorCode.ERR_ByReferenceVariableMustBeInitialized, node); return false; } else if (expressionRefKind != RefKind.Ref) { Error(diagnostics, ErrorCode.ERR_InitializeByReferenceVariableWithValue, node); return false; } } return true; } protected BoundLocalDeclaration BindVariableDeclaration( LocalDeclarationKind kind, bool isVar, VariableDeclaratorSyntax declarator, TypeSyntax typeSyntax, TypeWithAnnotations declTypeOpt, AliasSymbol aliasOpt, BindingDiagnosticBag diagnostics, bool includeBoundType, CSharpSyntaxNode associatedSyntaxNode = null) { Debug.Assert(declarator != null); return BindVariableDeclaration(LocateDeclaredVariableSymbol(declarator, typeSyntax, kind), kind, isVar, declarator, typeSyntax, declTypeOpt, aliasOpt, diagnostics, includeBoundType, associatedSyntaxNode); } protected BoundLocalDeclaration BindVariableDeclaration( SourceLocalSymbol localSymbol, LocalDeclarationKind kind, bool isVar, VariableDeclaratorSyntax declarator, TypeSyntax typeSyntax, TypeWithAnnotations declTypeOpt, AliasSymbol aliasOpt, BindingDiagnosticBag diagnostics, bool includeBoundType, CSharpSyntaxNode associatedSyntaxNode = null) { Debug.Assert(declarator != null); Debug.Assert(declTypeOpt.HasType || isVar); Debug.Assert(typeSyntax != null); var localDiagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, diagnostics.AccumulatesDependencies); // if we are not given desired syntax, we use declarator associatedSyntaxNode = associatedSyntaxNode ?? declarator; // Check for variable declaration errors. // Use the binder that owns the scope for the local because this (the current) binder // might own nested scope. bool nameConflict = localSymbol.ScopeBinder.ValidateDeclarationNameConflictsInScope(localSymbol, diagnostics); bool hasErrors = false; if (localSymbol.RefKind != RefKind.None) { CheckRefLocalInAsyncOrIteratorMethod(localSymbol.IdentifierToken, diagnostics); } EqualsValueClauseSyntax equalsClauseSyntax = declarator.Initializer; BindValueKind valueKind; ExpressionSyntax value; if (!IsInitializerRefKindValid(equalsClauseSyntax, declarator, localSymbol.RefKind, diagnostics, out valueKind, out value)) { hasErrors = true; } BoundExpression initializerOpt; if (isVar) { aliasOpt = null; initializerOpt = BindInferredVariableInitializer(diagnostics, value, valueKind, declarator); // If we got a good result then swap the inferred type for the "var" TypeSymbol initializerType = initializerOpt?.Type; if ((object)initializerType != null) { declTypeOpt = TypeWithAnnotations.Create(initializerType); if (declTypeOpt.IsVoidType()) { Error(localDiagnostics, ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, declarator, declTypeOpt.Type); declTypeOpt = TypeWithAnnotations.Create(CreateErrorType("var")); hasErrors = true; } if (!declTypeOpt.Type.IsErrorType()) { if (declTypeOpt.IsStatic) { Error(localDiagnostics, ErrorCode.ERR_VarDeclIsStaticClass, typeSyntax, initializerType); hasErrors = true; } } } else { declTypeOpt = TypeWithAnnotations.Create(CreateErrorType("var")); hasErrors = true; } } else { if (ReferenceEquals(equalsClauseSyntax, null)) { initializerOpt = null; } else { // Basically inlined BindVariableInitializer, but with conversion optional. initializerOpt = BindPossibleArrayInitializer(value, declTypeOpt.Type, valueKind, diagnostics); if (kind != LocalDeclarationKind.FixedVariable) { // If this is for a fixed statement, we'll do our own conversion since there are some special cases. initializerOpt = GenerateConversionForAssignment( declTypeOpt.Type, initializerOpt, localDiagnostics, isRefAssignment: localSymbol.RefKind != RefKind.None); } } } Debug.Assert(declTypeOpt.HasType); if (kind == LocalDeclarationKind.FixedVariable) { // NOTE: this is an error, but it won't prevent further binding. if (isVar) { if (!hasErrors) { Error(localDiagnostics, ErrorCode.ERR_ImplicitlyTypedLocalCannotBeFixed, declarator); hasErrors = true; } } if (!declTypeOpt.Type.IsPointerType()) { if (!hasErrors) { Error(localDiagnostics, declTypeOpt.Type.IsFunctionPointer() ? ErrorCode.ERR_CannotUseFunctionPointerAsFixedLocal : ErrorCode.ERR_BadFixedInitType, declarator); hasErrors = true; } } else if (!IsValidFixedVariableInitializer(declTypeOpt.Type, localSymbol, ref initializerOpt, localDiagnostics)) { hasErrors = true; } } if (CheckRestrictedTypeInAsyncMethod(this.ContainingMemberOrLambda, declTypeOpt.Type, localDiagnostics, typeSyntax)) { hasErrors = true; } localSymbol.SetTypeWithAnnotations(declTypeOpt); if (initializerOpt != null) { var currentScope = LocalScopeDepth; localSymbol.SetValEscape(GetValEscape(initializerOpt, currentScope)); if (localSymbol.RefKind != RefKind.None) { localSymbol.SetRefEscape(GetRefEscape(initializerOpt, currentScope)); } } ImmutableArray<BoundExpression> arguments = BindDeclaratorArguments(declarator, localDiagnostics); if (kind == LocalDeclarationKind.FixedVariable || kind == LocalDeclarationKind.UsingVariable) { // CONSIDER: The error message is "you must provide an initializer in a fixed // CONSIDER: or using declaration". The error message could be targeted to // CONSIDER: the actual situation. "you must provide an initializer in a // CONSIDER: 'fixed' declaration." if (initializerOpt == null) { Error(localDiagnostics, ErrorCode.ERR_FixedMustInit, declarator); hasErrors = true; } } else if (kind == LocalDeclarationKind.Constant && initializerOpt != null && !localDiagnostics.HasAnyResolvedErrors()) { var constantValueDiagnostics = localSymbol.GetConstantValueDiagnostics(initializerOpt); diagnostics.AddRange(constantValueDiagnostics, allowMismatchInDependencyAccumulation: true); hasErrors = constantValueDiagnostics.Diagnostics.HasAnyErrors(); } diagnostics.AddRangeAndFree(localDiagnostics); BoundTypeExpression boundDeclType = null; if (includeBoundType) { var invalidDimensions = ArrayBuilder<BoundExpression>.GetInstance(); typeSyntax.VisitRankSpecifiers((rankSpecifier, args) => { bool _ = false; foreach (var expressionSyntax in rankSpecifier.Sizes) { var size = args.binder.BindArrayDimension(expressionSyntax, args.diagnostics, ref _); if (size != null) { args.invalidDimensions.Add(size); } } }, (binder: this, invalidDimensions: invalidDimensions, diagnostics: diagnostics)); boundDeclType = new BoundTypeExpression(typeSyntax, aliasOpt, dimensionsOpt: invalidDimensions.ToImmutableAndFree(), typeWithAnnotations: declTypeOpt); } return new BoundLocalDeclaration( syntax: associatedSyntaxNode, localSymbol: localSymbol, declaredTypeOpt: boundDeclType, initializerOpt: hasErrors ? BindToTypeForErrorRecovery(initializerOpt)?.WithHasErrors() : initializerOpt, argumentsOpt: arguments, inferredType: isVar, hasErrors: hasErrors | nameConflict); } protected bool CheckRefLocalInAsyncOrIteratorMethod(SyntaxToken identifierToken, BindingDiagnosticBag diagnostics) { if (IsInAsyncMethod()) { Error(diagnostics, ErrorCode.ERR_BadAsyncLocalType, identifierToken); return true; } else if (IsDirectlyInIterator) { Error(diagnostics, ErrorCode.ERR_BadIteratorLocalType, identifierToken); return true; } return false; } internal ImmutableArray<BoundExpression> BindDeclaratorArguments(VariableDeclaratorSyntax declarator, BindingDiagnosticBag diagnostics) { // It is possible that we have a bracketed argument list, like "int x[];" or "int x[123];" // in a non-fixed-size-array declaration . This is a common error made by C++ programmers. // We have already given a good error at parse time telling the user to either make it "fixed" // or to move the brackets to the type. However, we should still do semantic analysis of // the arguments, so that errors in them are discovered, hovering over them in the IDE // gives good results, and so on. var arguments = default(ImmutableArray<BoundExpression>); if (declarator.ArgumentList != null) { AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance(); BindArgumentsAndNames(declarator.ArgumentList, diagnostics, analyzedArguments); arguments = BuildArgumentsForErrorRecovery(analyzedArguments); analyzedArguments.Free(); } return arguments; } private SourceLocalSymbol LocateDeclaredVariableSymbol(VariableDeclaratorSyntax declarator, TypeSyntax typeSyntax, LocalDeclarationKind outerKind) { LocalDeclarationKind kind = outerKind == LocalDeclarationKind.UsingVariable ? LocalDeclarationKind.UsingVariable : LocalDeclarationKind.RegularVariable; return LocateDeclaredVariableSymbol(declarator.Identifier, typeSyntax, declarator.Initializer, kind); } private SourceLocalSymbol LocateDeclaredVariableSymbol(SyntaxToken identifier, TypeSyntax typeSyntax, EqualsValueClauseSyntax equalsValue, LocalDeclarationKind kind) { SourceLocalSymbol localSymbol = this.LookupLocal(identifier); // In error scenarios with misplaced code, it is possible we can't bind the local declaration. // This occurs through the semantic model. In that case concoct a plausible result. if ((object)localSymbol == null) { localSymbol = SourceLocalSymbol.MakeLocal( ContainingMemberOrLambda, this, false, // do not allow ref typeSyntax, identifier, kind, equalsValue); } return localSymbol; } private bool IsValidFixedVariableInitializer(TypeSymbol declType, SourceLocalSymbol localSymbol, ref BoundExpression initializerOpt, BindingDiagnosticBag diagnostics) { Debug.Assert(!ReferenceEquals(declType, null)); Debug.Assert(declType.IsPointerType()); if (initializerOpt?.HasAnyErrors != false) { return false; } TypeSymbol initializerType = initializerOpt.Type; SyntaxNode initializerSyntax = initializerOpt.Syntax; if ((object)initializerType == null) { Error(diagnostics, ErrorCode.ERR_ExprCannotBeFixed, initializerSyntax); return false; } TypeSymbol elementType; bool hasErrors = false; MethodSymbol fixedPatternMethod = null; switch (initializerOpt.Kind) { case BoundKind.AddressOfOperator: elementType = ((BoundAddressOfOperator)initializerOpt).Operand.Type; break; case BoundKind.FieldAccess: var fa = (BoundFieldAccess)initializerOpt; if (fa.FieldSymbol.IsFixedSizeBuffer) { elementType = ((PointerTypeSymbol)fa.Type).PointedAtType; break; } goto default; default: // fixed (T* variable = <expr>) ... // check for arrays if (initializerType.IsArray()) { // See ExpressionBinder::BindPtrToArray (though most of that functionality is now in LocalRewriter). elementType = ((ArrayTypeSymbol)initializerType).ElementType; break; } // check for a special ref-returning method var additionalDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); fixedPatternMethod = GetFixedPatternMethodOpt(initializerOpt, additionalDiagnostics); // check for String // NOTE: We will allow the pattern method to take precedence, but only if it is an instance member of System.String if (initializerType.SpecialType == SpecialType.System_String && ((object)fixedPatternMethod == null || fixedPatternMethod.ContainingType.SpecialType != SpecialType.System_String)) { fixedPatternMethod = null; elementType = this.GetSpecialType(SpecialType.System_Char, diagnostics, initializerSyntax); additionalDiagnostics.Free(); break; } // if the feature was enabled, but something went wrong with the method, report that, otherwise don't. // If feature is not enabled, additional errors would be just noise. bool extensibleFixedEnabled = ((CSharpParseOptions)initializerOpt.SyntaxTree.Options)?.IsFeatureEnabled(MessageID.IDS_FeatureExtensibleFixedStatement) != false; if (extensibleFixedEnabled) { diagnostics.AddRange(additionalDiagnostics); } additionalDiagnostics.Free(); if ((object)fixedPatternMethod != null) { elementType = fixedPatternMethod.ReturnType; CheckFeatureAvailability(initializerOpt.Syntax, MessageID.IDS_FeatureExtensibleFixedStatement, diagnostics); break; } else { Error(diagnostics, ErrorCode.ERR_ExprCannotBeFixed, initializerSyntax); return false; } } if (CheckManagedAddr(Compilation, elementType, initializerSyntax.Location, diagnostics)) { hasErrors = true; } initializerOpt = BindToNaturalType(initializerOpt, diagnostics, reportNoTargetType: false); initializerOpt = GetFixedLocalCollectionInitializer(initializerOpt, elementType, declType, fixedPatternMethod, hasErrors, diagnostics); return true; } private MethodSymbol GetFixedPatternMethodOpt(BoundExpression initializer, BindingDiagnosticBag additionalDiagnostics) { if (initializer.Type.IsVoidType()) { return null; } const string methodName = "GetPinnableReference"; var result = PerformPatternMethodLookup(initializer, methodName, initializer.Syntax, additionalDiagnostics, out var patternMethodSymbol); if (patternMethodSymbol is null) { return null; } if (HasOptionalOrVariableParameters(patternMethodSymbol) || patternMethodSymbol.ReturnsVoid || !patternMethodSymbol.RefKind.IsManagedReference() || !(patternMethodSymbol.ParameterCount == 0 || patternMethodSymbol.IsStatic && patternMethodSymbol.ParameterCount == 1)) { // the method does not fit the pattern additionalDiagnostics.Add(ErrorCode.WRN_PatternBadSignature, initializer.Syntax.Location, initializer.Type, "fixed", patternMethodSymbol); return null; } return patternMethodSymbol; } /// <summary> /// Wrap the initializer in a BoundFixedLocalCollectionInitializer so that the rewriter will have the /// information it needs (e.g. conversions, helper methods). /// </summary> private BoundExpression GetFixedLocalCollectionInitializer( BoundExpression initializer, TypeSymbol elementType, TypeSymbol declType, MethodSymbol patternMethodOpt, bool hasErrors, BindingDiagnosticBag diagnostics) { Debug.Assert(initializer != null); SyntaxNode initializerSyntax = initializer.Syntax; TypeSymbol pointerType = new PointerTypeSymbol(TypeWithAnnotations.Create(elementType)); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion elementConversion = this.Conversions.ClassifyConversionFromType(pointerType, declType, ref useSiteInfo); diagnostics.Add(initializerSyntax, useSiteInfo); if (!elementConversion.IsValid || !elementConversion.IsImplicit) { GenerateImplicitConversionError(diagnostics, this.Compilation, initializerSyntax, elementConversion, pointerType, declType); hasErrors = true; } return new BoundFixedLocalCollectionInitializer( initializerSyntax, pointerType, elementConversion, initializer, patternMethodOpt, declType, hasErrors); } private BoundExpression BindAssignment(AssignmentExpressionSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); Debug.Assert(node.Left != null); Debug.Assert(node.Right != null); node.Left.CheckDeconstructionCompatibleArgument(diagnostics); if (node.Left.Kind() == SyntaxKind.TupleExpression || node.Left.Kind() == SyntaxKind.DeclarationExpression) { return BindDeconstruction(node, diagnostics); } BindValueKind lhsKind; BindValueKind rhsKind; ExpressionSyntax rhsExpr; bool isRef = false; if (node.Right.Kind() == SyntaxKind.RefExpression) { isRef = true; lhsKind = BindValueKind.RefAssignable; rhsKind = BindValueKind.RefersToLocation; rhsExpr = ((RefExpressionSyntax)node.Right).Expression; } else { lhsKind = BindValueKind.Assignable; rhsKind = BindValueKind.RValue; rhsExpr = node.Right; } var op1 = BindValue(node.Left, diagnostics, lhsKind); ReportSuppressionIfNeeded(op1, diagnostics); var lhsRefKind = RefKind.None; // If the LHS is a ref (not ref-readonly), the rhs // must also be value-assignable if (lhsKind == BindValueKind.RefAssignable && !op1.HasErrors) { // We should now know that op1 is a valid lvalue lhsRefKind = op1.GetRefKind(); if (lhsRefKind == RefKind.Ref || lhsRefKind == RefKind.Out) { rhsKind |= BindValueKind.Assignable; } } var op2 = BindValue(rhsExpr, diagnostics, rhsKind); if (op1.Kind == BoundKind.DiscardExpression) { op2 = BindToNaturalType(op2, diagnostics); op1 = InferTypeForDiscardAssignment((BoundDiscardExpression)op1, op2, diagnostics); } return BindAssignment(node, op1, op2, isRef, diagnostics); } private BoundExpression InferTypeForDiscardAssignment(BoundDiscardExpression op1, BoundExpression op2, BindingDiagnosticBag diagnostics) { var inferredType = op2.Type; if ((object)inferredType == null) { return op1.FailInference(this, diagnostics); } if (inferredType.IsVoidType()) { diagnostics.Add(ErrorCode.ERR_VoidAssignment, op1.Syntax.Location); } return op1.SetInferredTypeWithAnnotations(TypeWithAnnotations.Create(inferredType)); } private BoundAssignmentOperator BindAssignment( SyntaxNode node, BoundExpression op1, BoundExpression op2, bool isRef, BindingDiagnosticBag diagnostics) { Debug.Assert(op1 != null); Debug.Assert(op2 != null); bool hasErrors = op1.HasAnyErrors || op2.HasAnyErrors; if (!op1.HasAnyErrors) { // Build bound conversion. The node might not be used if this is a dynamic conversion // but diagnostics should be reported anyways. var conversion = GenerateConversionForAssignment(op1.Type, op2, diagnostics, isRefAssignment: isRef); // If the result is a dynamic assignment operation (SetMember or SetIndex), // don't generate the boxing conversion to the dynamic type. // Leave the values as they are, and deal with the conversions at runtime. if (op1.Kind != BoundKind.DynamicIndexerAccess && op1.Kind != BoundKind.DynamicMemberAccess && op1.Kind != BoundKind.DynamicObjectInitializerMember) { op2 = conversion; } else { op2 = BindToNaturalType(op2, diagnostics); } if (isRef) { var leftEscape = GetRefEscape(op1, LocalScopeDepth); var rightEscape = GetRefEscape(op2, LocalScopeDepth); if (leftEscape < rightEscape) { Error(diagnostics, ErrorCode.ERR_RefAssignNarrower, node, op1.ExpressionSymbol.Name, op2.Syntax); op2 = ToBadExpression(op2); } } if (op1.Type.IsRefLikeType) { var leftEscape = GetValEscape(op1, LocalScopeDepth); op2 = ValidateEscape(op2, leftEscape, isByRef: false, diagnostics); } } else { op2 = BindToTypeForErrorRecovery(op2); } TypeSymbol type; if ((op1.Kind == BoundKind.EventAccess) && ((BoundEventAccess)op1).EventSymbol.IsWindowsRuntimeEvent) { // Event assignment is a call to void WindowsRuntimeMarshal.AddEventHandler<T>(). type = this.GetSpecialType(SpecialType.System_Void, diagnostics, node); } else { type = op1.Type; } return new BoundAssignmentOperator(node, op1, op2, isRef, type, hasErrors); } private static PropertySymbol GetPropertySymbol(BoundExpression expr, out BoundExpression receiver, out SyntaxNode propertySyntax) { PropertySymbol propertySymbol; switch (expr.Kind) { case BoundKind.PropertyAccess: { var propertyAccess = (BoundPropertyAccess)expr; receiver = propertyAccess.ReceiverOpt; propertySymbol = propertyAccess.PropertySymbol; } break; case BoundKind.IndexerAccess: { var indexerAccess = (BoundIndexerAccess)expr; receiver = indexerAccess.ReceiverOpt; propertySymbol = indexerAccess.Indexer; } break; case BoundKind.IndexOrRangePatternIndexerAccess: { var patternIndexer = (BoundIndexOrRangePatternIndexerAccess)expr; receiver = patternIndexer.Receiver; propertySymbol = (PropertySymbol)patternIndexer.PatternSymbol; } break; default: receiver = null; propertySymbol = null; propertySyntax = null; return null; } var syntax = expr.Syntax; switch (syntax.Kind()) { case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: propertySyntax = ((MemberAccessExpressionSyntax)syntax).Name; break; case SyntaxKind.IdentifierName: propertySyntax = syntax; break; case SyntaxKind.ElementAccessExpression: propertySyntax = ((ElementAccessExpressionSyntax)syntax).ArgumentList; break; default: // Other syntax types, such as QualifiedName, // might occur in invalid code. propertySyntax = syntax; break; } return propertySymbol; } private static SyntaxNode GetEventName(BoundEventAccess expr) { SyntaxNode syntax = expr.Syntax; switch (syntax.Kind()) { case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: return ((MemberAccessExpressionSyntax)syntax).Name; case SyntaxKind.QualifiedName: // This case is reachable only through SemanticModel return ((QualifiedNameSyntax)syntax).Right; case SyntaxKind.IdentifierName: return syntax; case SyntaxKind.MemberBindingExpression: return ((MemberBindingExpressionSyntax)syntax).Name; default: throw ExceptionUtilities.UnexpectedValue(syntax.Kind()); } } /// <summary> /// There are two BadEventUsage error codes and this method decides which one should /// be used for a given event. /// </summary> private DiagnosticInfo GetBadEventUsageDiagnosticInfo(EventSymbol eventSymbol) { var leastOverridden = (EventSymbol)eventSymbol.GetLeastOverriddenMember(this.ContainingType); return leastOverridden.HasAssociatedField ? new CSDiagnosticInfo(ErrorCode.ERR_BadEventUsage, leastOverridden, leastOverridden.ContainingType) : new CSDiagnosticInfo(ErrorCode.ERR_BadEventUsageNoField, leastOverridden); } internal static bool AccessingAutoPropertyFromConstructor(BoundPropertyAccess propertyAccess, Symbol fromMember) { return AccessingAutoPropertyFromConstructor(propertyAccess.ReceiverOpt, propertyAccess.PropertySymbol, fromMember); } private static bool AccessingAutoPropertyFromConstructor(BoundExpression receiver, PropertySymbol propertySymbol, Symbol fromMember) { if (!propertySymbol.IsDefinition && propertySymbol.ContainingType.Equals(propertySymbol.ContainingType.OriginalDefinition, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { propertySymbol = propertySymbol.OriginalDefinition; } var sourceProperty = propertySymbol as SourcePropertySymbolBase; var propertyIsStatic = propertySymbol.IsStatic; return (object)sourceProperty != null && sourceProperty.IsAutoPropertyWithGetAccessor && TypeSymbol.Equals(sourceProperty.ContainingType, fromMember.ContainingType, TypeCompareKind.ConsiderEverything2) && IsConstructorOrField(fromMember, isStatic: propertyIsStatic) && (propertyIsStatic || receiver.Kind == BoundKind.ThisReference); } private static bool IsConstructorOrField(Symbol member, bool isStatic) { return (member as MethodSymbol)?.MethodKind == (isStatic ? MethodKind.StaticConstructor : MethodKind.Constructor) || (member as FieldSymbol)?.IsStatic == isStatic; } private TypeSymbol GetAccessThroughType(BoundExpression receiver) { if (receiver == null) { return this.ContainingType; } else if (receiver.Kind == BoundKind.BaseReference) { // Allow protected access to members defined // in base classes. See spec section 3.5.3. return null; } else { Debug.Assert((object)receiver.Type != null); return receiver.Type; } } private BoundExpression BindPossibleArrayInitializer( ExpressionSyntax node, TypeSymbol destinationType, BindValueKind valueKind, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); if (node.Kind() != SyntaxKind.ArrayInitializerExpression) { return BindValue(node, diagnostics, valueKind); } BoundExpression result; if (destinationType.Kind == SymbolKind.ArrayType) { result = BindArrayCreationWithInitializer(diagnostics, null, (InitializerExpressionSyntax)node, (ArrayTypeSymbol)destinationType, ImmutableArray<BoundExpression>.Empty); } else { result = BindUnexpectedArrayInitializer((InitializerExpressionSyntax)node, diagnostics, ErrorCode.ERR_ArrayInitToNonArrayType); } return CheckValue(result, valueKind, diagnostics); } protected virtual SourceLocalSymbol LookupLocal(SyntaxToken nameToken) { return Next.LookupLocal(nameToken); } protected virtual LocalFunctionSymbol LookupLocalFunction(SyntaxToken nameToken) { return Next.LookupLocalFunction(nameToken); } /// <summary> /// Returns a value that tells how many local scopes are visible, including the current. /// I.E. outside of any method will be 0 /// immediately inside a method - 1 /// </summary> internal virtual uint LocalScopeDepth => Next.LocalScopeDepth; internal virtual BoundBlock BindEmbeddedBlock(BlockSyntax node, BindingDiagnosticBag diagnostics) { return BindBlock(node, diagnostics); } private BoundBlock BindBlock(BlockSyntax node, BindingDiagnosticBag diagnostics) { if (node.AttributeLists.Count > 0) { Error(diagnostics, ErrorCode.ERR_AttributesNotAllowed, node.AttributeLists[0]); } var binder = GetBinder(node); Debug.Assert(binder != null); return binder.BindBlockParts(node, diagnostics); } private BoundBlock BindBlockParts(BlockSyntax node, BindingDiagnosticBag diagnostics) { var syntaxStatements = node.Statements; int nStatements = syntaxStatements.Count; ArrayBuilder<BoundStatement> boundStatements = ArrayBuilder<BoundStatement>.GetInstance(nStatements); for (int i = 0; i < nStatements; i++) { var boundStatement = BindStatement(syntaxStatements[i], diagnostics); boundStatements.Add(boundStatement); } return FinishBindBlockParts(node, boundStatements.ToImmutableAndFree(), diagnostics); } private BoundBlock FinishBindBlockParts(CSharpSyntaxNode node, ImmutableArray<BoundStatement> boundStatements, BindingDiagnosticBag diagnostics) { ImmutableArray<LocalSymbol> locals = GetDeclaredLocalsForScope(node); if (IsDirectlyInIterator) { var method = ContainingMemberOrLambda as MethodSymbol; if ((object)method != null) { method.IteratorElementTypeWithAnnotations = GetIteratorElementType(); } else { Debug.Assert(diagnostics.DiagnosticBag is null || !diagnostics.DiagnosticBag.IsEmptyWithoutResolution); } } return new BoundBlock( node, locals, GetDeclaredLocalFunctionsForScope(node), boundStatements); } internal BoundExpression GenerateConversionForAssignment(TypeSymbol targetType, BoundExpression expression, BindingDiagnosticBag diagnostics, bool isDefaultParameter = false, bool isRefAssignment = false) { Debug.Assert((object)targetType != null); Debug.Assert(expression != null); // We wish to avoid "cascading" errors, so if the expression we are // attempting to convert to a type had errors, suppress additional // diagnostics. However, if the expression // with errors is an unbound lambda then the errors are almost certainly // syntax errors. For error recovery analysis purposes we wish to bind // error lambdas like "Action<int> f = x=>{ x. };" because IntelliSense // needs to know that x is of type int. if (expression.HasAnyErrors && expression.Kind != BoundKind.UnboundLambda) { diagnostics = BindingDiagnosticBag.Discarded; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var conversion = this.Conversions.ClassifyConversionFromExpression(expression, targetType, ref useSiteInfo); diagnostics.Add(expression.Syntax, useSiteInfo); if (isRefAssignment) { if (conversion.Kind != ConversionKind.Identity) { Error(diagnostics, ErrorCode.ERR_RefAssignmentMustHaveIdentityConversion, expression.Syntax, targetType); } else { return expression; } } else if (!conversion.IsImplicit || !conversion.IsValid) { // We suppress conversion errors on default parameters; eg, // if someone says "void M(string s = 123) {}". We will report // a special error in the default parameter binder. if (!isDefaultParameter) { GenerateImplicitConversionError(diagnostics, expression.Syntax, conversion, expression, targetType); } // Suppress any additional diagnostics diagnostics = BindingDiagnosticBag.Discarded; } return CreateConversion(expression.Syntax, expression, conversion, isCast: false, conversionGroupOpt: null, targetType, diagnostics); } #nullable enable internal void GenerateAnonymousFunctionConversionError(BindingDiagnosticBag diagnostics, SyntaxNode syntax, UnboundLambda anonymousFunction, TypeSymbol targetType) { Debug.Assert((object)targetType != null); Debug.Assert(anonymousFunction != null); // Is the target type simply bad? // If the target type is an error then we've already reported a diagnostic. Don't bother // reporting the conversion error. if (targetType.IsErrorType()) { return; } // CONSIDER: Instead of computing this again, cache the reason why the conversion failed in // CONSIDER: the Conversion result, and simply report that. var reason = Conversions.IsAnonymousFunctionCompatibleWithType(anonymousFunction, targetType); // It is possible that the conversion from lambda to delegate is just fine, and // that we ended up here because the target type, though itself is not an error // type, contains a type argument which is an error type. For example, converting // (Goo goo)=>{} to Action<Goo> is a perfectly legal conversion even if Goo is undefined! // In that case we have already reported an error that Goo is undefined, so just bail out. if (reason == LambdaConversionResult.Success) { return; } var id = anonymousFunction.MessageID.Localize(); if (reason == LambdaConversionResult.BadTargetType) { if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, targetType, node: syntax)) { return; } // Cannot convert {0} to type '{1}' because it is not a delegate type Error(diagnostics, ErrorCode.ERR_AnonMethToNonDel, syntax, id, targetType); return; } if (reason == LambdaConversionResult.ExpressionTreeMustHaveDelegateTypeArgument) { Debug.Assert(targetType.IsExpressionTree()); Error(diagnostics, ErrorCode.ERR_ExpressionTreeMustHaveDelegate, syntax, ((NamedTypeSymbol)targetType).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type); return; } if (reason == LambdaConversionResult.ExpressionTreeFromAnonymousMethod) { Debug.Assert(targetType.IsGenericOrNonGenericExpressionType(out _)); Error(diagnostics, ErrorCode.ERR_AnonymousMethodToExpressionTree, syntax); return; } if (reason == LambdaConversionResult.MismatchedReturnType) { Error(diagnostics, ErrorCode.ERR_CantConvAnonMethReturnType, syntax, id, targetType); return; } // At this point we know that we have either a delegate type or an expression type for the target. // The target type is a valid delegate or expression tree type. Is there something wrong with the // parameter list? // First off, is there a parameter list at all? if (reason == LambdaConversionResult.MissingSignatureWithOutParameter) { // COMPATIBILITY: The C# 4 compiler produces two errors for: // // delegate void D (out int x); // ... // D d = delegate {}; // // error CS1676: Parameter 1 must be declared with the 'out' keyword // error CS1688: Cannot convert anonymous method block without a parameter list // to delegate type 'D' because it has one or more out parameters // // This seems redundant, (because there is no "parameter 1" in the source code) // and unnecessary. I propose that we eliminate the first error. Error(diagnostics, ErrorCode.ERR_CantConvAnonMethNoParams, syntax, targetType); return; } var delegateType = targetType.GetDelegateType(); Debug.Assert(delegateType is not null); // There is a parameter list. Does it have the right number of elements? if (reason == LambdaConversionResult.BadParameterCount) { // Delegate '{0}' does not take {1} arguments Error(diagnostics, ErrorCode.ERR_BadDelArgCount, syntax, delegateType, anonymousFunction.ParameterCount); return; } // The parameter list exists and had the right number of parameters. Were any of its types bad? // If any parameter type of the lambda is an error type then suppress // further errors. We've already reported errors on the bad type. if (anonymousFunction.HasExplicitlyTypedParameterList) { for (int i = 0; i < anonymousFunction.ParameterCount; ++i) { if (anonymousFunction.ParameterType(i).IsErrorType()) { return; } } } // The parameter list exists and had the right number of parameters. Were any of its types // mismatched with the delegate parameter types? // The simplest possible case is (x, y, z)=>whatever where the target type has a ref or out parameter. var delegateParameters = delegateType.DelegateParameters(); if (reason == LambdaConversionResult.RefInImplicitlyTypedLambda) { for (int i = 0; i < anonymousFunction.ParameterCount; ++i) { var delegateRefKind = delegateParameters[i].RefKind; if (delegateRefKind != RefKind.None) { // Parameter {0} must be declared with the '{1}' keyword Error(diagnostics, ErrorCode.ERR_BadParamRef, anonymousFunction.ParameterLocation(i), i + 1, delegateRefKind.ToParameterDisplayString()); } } return; } // See the comments in IsAnonymousFunctionCompatibleWithDelegate for an explanation of this one. if (reason == LambdaConversionResult.StaticTypeInImplicitlyTypedLambda) { for (int i = 0; i < anonymousFunction.ParameterCount; ++i) { if (delegateParameters[i].TypeWithAnnotations.IsStatic) { // {0}: Static types cannot be used as parameter Error(diagnostics, ErrorFacts.GetStaticClassParameterCode(useWarning: false), anonymousFunction.ParameterLocation(i), delegateParameters[i].Type); } } return; } // Otherwise, there might be a more complex reason why the parameter types are mismatched. if (reason == LambdaConversionResult.MismatchedParameterType) { // Cannot convert {0} to type '{1}' because the parameter types do not match the delegate parameter types Error(diagnostics, ErrorCode.ERR_CantConvAnonMethParams, syntax, id, targetType); Debug.Assert(anonymousFunction.ParameterCount == delegateParameters.Length); for (int i = 0; i < anonymousFunction.ParameterCount; ++i) { var lambdaParameterType = anonymousFunction.ParameterType(i); if (lambdaParameterType.IsErrorType()) { continue; } var lambdaParameterLocation = anonymousFunction.ParameterLocation(i); var lambdaRefKind = anonymousFunction.RefKind(i); var delegateParameterType = delegateParameters[i].Type; var delegateRefKind = delegateParameters[i].RefKind; if (!lambdaParameterType.Equals(delegateParameterType, TypeCompareKind.AllIgnoreOptions)) { SymbolDistinguisher distinguisher = new SymbolDistinguisher(this.Compilation, lambdaParameterType, delegateParameterType); // Parameter {0} is declared as type '{1}{2}' but should be '{3}{4}' Error(diagnostics, ErrorCode.ERR_BadParamType, lambdaParameterLocation, i + 1, lambdaRefKind.ToParameterPrefix(), distinguisher.First, delegateRefKind.ToParameterPrefix(), distinguisher.Second); } else if (lambdaRefKind != delegateRefKind) { if (delegateRefKind == RefKind.None) { // Parameter {0} should not be declared with the '{1}' keyword Error(diagnostics, ErrorCode.ERR_BadParamExtraRef, lambdaParameterLocation, i + 1, lambdaRefKind.ToParameterDisplayString()); } else { // Parameter {0} must be declared with the '{1}' keyword Error(diagnostics, ErrorCode.ERR_BadParamRef, lambdaParameterLocation, i + 1, delegateRefKind.ToParameterDisplayString()); } } } return; } if (reason == LambdaConversionResult.BindingFailed) { var bindingResult = anonymousFunction.Bind(delegateType); Debug.Assert(ErrorFacts.PreventsSuccessfulDelegateConversion(bindingResult.Diagnostics.Diagnostics)); diagnostics.AddRange(bindingResult.Diagnostics); return; } // UNDONE: LambdaConversionResult.VoidExpressionLambdaMustBeStatementExpression: Debug.Assert(false, "Missing case in lambda conversion error reporting"); diagnostics.Add(ErrorCode.ERR_InternalError, syntax.Location); } #nullable disable protected static void GenerateImplicitConversionError(BindingDiagnosticBag diagnostics, CSharpCompilation compilation, SyntaxNode syntax, Conversion conversion, TypeSymbol sourceType, TypeSymbol targetType, ConstantValue sourceConstantValueOpt = null) { Debug.Assert(!conversion.IsImplicit || !conversion.IsValid); // If the either type is an error then an error has already been reported // for some aspect of the analysis of this expression. (For example, something like // "garbage g = null; short s = g;" -- we don't want to report that g is not // convertible to short because we've already reported that g does not have a good type. if (!sourceType.IsErrorType() && !targetType.IsErrorType()) { if (conversion.IsExplicit) { if (sourceType.SpecialType == SpecialType.System_Double && syntax.Kind() == SyntaxKind.NumericLiteralExpression && (targetType.SpecialType == SpecialType.System_Single || targetType.SpecialType == SpecialType.System_Decimal)) { Error(diagnostics, ErrorCode.ERR_LiteralDoubleCast, syntax, (targetType.SpecialType == SpecialType.System_Single) ? "F" : "M", targetType); } else if (conversion.Kind == ConversionKind.ExplicitNumeric && sourceConstantValueOpt != null && sourceConstantValueOpt != ConstantValue.Bad && ConversionsBase.HasImplicitConstantExpressionConversion(new BoundLiteral(syntax, ConstantValue.Bad, sourceType), targetType)) { // CLEVERNESS: By passing ConstantValue.Bad, we tell HasImplicitConstantExpressionConversion to ignore the constant // value and only consider the types. // If there would be an implicit constant conversion for a different constant of the same type // (i.e. one that's not out of range), then it's more helpful to report the range check failure // than to suggest inserting a cast. Error(diagnostics, ErrorCode.ERR_ConstOutOfRange, syntax, sourceConstantValueOpt.Value, targetType); } else { SymbolDistinguisher distinguisher = new SymbolDistinguisher(compilation, sourceType, targetType); Error(diagnostics, ErrorCode.ERR_NoImplicitConvCast, syntax, distinguisher.First, distinguisher.Second); } } else if (conversion.ResultKind == LookupResultKind.OverloadResolutionFailure) { Debug.Assert(conversion.IsUserDefined); ImmutableArray<MethodSymbol> originalUserDefinedConversions = conversion.OriginalUserDefinedConversions; if (originalUserDefinedConversions.Length > 1) { Error(diagnostics, ErrorCode.ERR_AmbigUDConv, syntax, originalUserDefinedConversions[0], originalUserDefinedConversions[1], sourceType, targetType); } else { Debug.Assert(originalUserDefinedConversions.Length == 0, "How can there be exactly one applicable user-defined conversion if the conversion doesn't exist?"); SymbolDistinguisher distinguisher = new SymbolDistinguisher(compilation, sourceType, targetType); Error(diagnostics, ErrorCode.ERR_NoImplicitConv, syntax, distinguisher.First, distinguisher.Second); } } else if (TypeSymbol.Equals(sourceType, targetType, TypeCompareKind.ConsiderEverything2)) { // This occurs for `void`, which cannot even convert to itself. Since SymbolDistinguisher // requires two distinct types, we preempt its use here. The diagnostic is strange, but correct. // Though this diagnostic tends to be a cascaded one, we cannot suppress it until // we have proven that it is always so. Error(diagnostics, ErrorCode.ERR_NoImplicitConv, syntax, sourceType, targetType); } else { SymbolDistinguisher distinguisher = new SymbolDistinguisher(compilation, sourceType, targetType); Error(diagnostics, ErrorCode.ERR_NoImplicitConv, syntax, distinguisher.First, distinguisher.Second); } } } protected void GenerateImplicitConversionError( BindingDiagnosticBag diagnostics, SyntaxNode syntax, Conversion conversion, BoundExpression operand, TypeSymbol targetType) { Debug.Assert(operand != null); Debug.Assert((object)targetType != null); if (targetType.TypeKind == TypeKind.Error) { return; } if (targetType.IsVoidType()) { Error(diagnostics, ErrorCode.ERR_NoImplicitConv, syntax, operand.Display, targetType); return; } switch (operand.Kind) { case BoundKind.BadExpression: { return; } case BoundKind.UnboundLambda: { GenerateAnonymousFunctionConversionError(diagnostics, syntax, (UnboundLambda)operand, targetType); return; } case BoundKind.TupleLiteral: { var tuple = (BoundTupleLiteral)operand; var targetElementTypes = default(ImmutableArray<TypeWithAnnotations>); // If target is a tuple or compatible type with the same number of elements, // report errors for tuple arguments that failed to convert, which would be more useful. if (targetType.TryGetElementTypesWithAnnotationsIfTupleType(out targetElementTypes) && targetElementTypes.Length == tuple.Arguments.Length) { GenerateImplicitConversionErrorsForTupleLiteralArguments(diagnostics, tuple.Arguments, targetElementTypes); return; } // target is not compatible with source and source does not have a type if ((object)tuple.Type == null) { Error(diagnostics, ErrorCode.ERR_ConversionNotTupleCompatible, syntax, tuple.Arguments.Length, targetType); return; } // Otherwise it is just a regular conversion failure from T1 to T2. break; } case BoundKind.MethodGroup: { reportMethodGroupErrors((BoundMethodGroup)operand, fromAddressOf: false); return; } case BoundKind.UnconvertedAddressOfOperator: { reportMethodGroupErrors(((BoundUnconvertedAddressOfOperator)operand).Operand, fromAddressOf: true); return; } case BoundKind.Literal: { if (operand.IsLiteralNull()) { if (targetType.TypeKind == TypeKind.TypeParameter) { Error(diagnostics, ErrorCode.ERR_TypeVarCantBeNull, syntax, targetType); return; } if (targetType.IsValueType) { Error(diagnostics, ErrorCode.ERR_ValueCantBeNull, syntax, targetType); return; } } break; } case BoundKind.StackAllocArrayCreation: { var stackAllocExpression = (BoundStackAllocArrayCreation)operand; Error(diagnostics, ErrorCode.ERR_StackAllocConversionNotPossible, syntax, stackAllocExpression.ElementType, targetType); return; } case BoundKind.UnconvertedSwitchExpression: { var switchExpression = (BoundUnconvertedSwitchExpression)operand; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; bool reportedError = false; foreach (var arm in switchExpression.SwitchArms) { tryConversion(arm.Value, ref reportedError, ref discardedUseSiteInfo); } Debug.Assert(reportedError); return; } case BoundKind.AddressOfOperator when targetType.IsFunctionPointer(): { Error(diagnostics, ErrorCode.ERR_InvalidAddrOp, ((BoundAddressOfOperator)operand).Operand.Syntax); return; } case BoundKind.UnconvertedConditionalOperator: { var conditionalOperator = (BoundUnconvertedConditionalOperator)operand; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; bool reportedError = false; tryConversion(conditionalOperator.Consequence, ref reportedError, ref discardedUseSiteInfo); tryConversion(conditionalOperator.Alternative, ref reportedError, ref discardedUseSiteInfo); Debug.Assert(reportedError); return; } void tryConversion(BoundExpression expr, ref bool reportedError, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var conversion = this.Conversions.ClassifyImplicitConversionFromExpression(expr, targetType, ref useSiteInfo); if (!conversion.IsImplicit || !conversion.IsValid) { GenerateImplicitConversionError(diagnostics, expr.Syntax, conversion, expr, targetType); reportedError = true; } } } var sourceType = operand.Type; if ((object)sourceType != null) { GenerateImplicitConversionError(diagnostics, this.Compilation, syntax, conversion, sourceType, targetType, operand.ConstantValue); return; } Debug.Assert(operand.HasAnyErrors && operand.Kind != BoundKind.UnboundLambda, "Missing a case in implicit conversion error reporting"); void reportMethodGroupErrors(BoundMethodGroup methodGroup, bool fromAddressOf) { if (!Conversions.ReportDelegateOrFunctionPointerMethodGroupDiagnostics(this, methodGroup, targetType, diagnostics)) { var nodeForError = syntax; while (nodeForError.Kind() == SyntaxKind.ParenthesizedExpression) { nodeForError = ((ParenthesizedExpressionSyntax)nodeForError).Expression; } if (nodeForError.Kind() == SyntaxKind.SimpleMemberAccessExpression || nodeForError.Kind() == SyntaxKind.PointerMemberAccessExpression) { nodeForError = ((MemberAccessExpressionSyntax)nodeForError).Name; } var location = nodeForError.Location; if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, targetType, location)) { return; } ErrorCode errorCode; switch (targetType.TypeKind) { case TypeKind.FunctionPointer when fromAddressOf: errorCode = ErrorCode.ERR_MethFuncPtrMismatch; break; case TypeKind.FunctionPointer: Error(diagnostics, ErrorCode.ERR_MissingAddressOf, location); return; case TypeKind.Delegate when fromAddressOf: errorCode = ErrorCode.ERR_CannotConvertAddressOfToDelegate; break; case TypeKind.Delegate: errorCode = ErrorCode.ERR_MethDelegateMismatch; break; default: if (fromAddressOf) { errorCode = ErrorCode.ERR_AddressOfToNonFunctionPointer; } else if (targetType.SpecialType == SpecialType.System_Delegate) { Error(diagnostics, ErrorCode.ERR_CannotInferDelegateType, location); return; } else { errorCode = ErrorCode.ERR_MethGrpToNonDel; } break; } Error(diagnostics, errorCode, location, methodGroup.Name, targetType); } } } private void GenerateImplicitConversionErrorsForTupleLiteralArguments( BindingDiagnosticBag diagnostics, ImmutableArray<BoundExpression> tupleArguments, ImmutableArray<TypeWithAnnotations> targetElementTypes) { var argLength = tupleArguments.Length; // report all leaf elements of the tuple literal that failed to convert // NOTE: we are not responsible for reporting use site errors here, just the failed leaf conversions. // By the time we get here we have done analysis and know we have failed the cast in general, and diagnostics collected in the process is already in the bag. // The only thing left is to form a diagnostics about the actually failing conversion(s). // This whole method does not itself collect any usesite diagnostics. Its only purpose is to produce an error better than "conversion failed here" var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; for (int i = 0; i < targetElementTypes.Length; i++) { var argument = tupleArguments[i]; var targetElementType = targetElementTypes[i].Type; var elementConversion = Conversions.ClassifyImplicitConversionFromExpression(argument, targetElementType, ref discardedUseSiteInfo); if (!elementConversion.IsValid) { GenerateImplicitConversionError(diagnostics, argument.Syntax, elementConversion, argument, targetElementType); } } } private BoundStatement BindIfStatement(IfStatementSyntax node, BindingDiagnosticBag diagnostics) { var condition = BindBooleanExpression(node.Condition, diagnostics); var consequence = BindPossibleEmbeddedStatement(node.Statement, diagnostics); BoundStatement alternative = (node.Else == null) ? null : BindPossibleEmbeddedStatement(node.Else.Statement, diagnostics); BoundStatement result = new BoundIfStatement(node, condition, consequence, alternative); return result; } internal BoundExpression BindBooleanExpression(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { // SPEC: // A boolean-expression is an expression that yields a result of type bool; // either directly or through application of operator true in certain // contexts as specified in the following. // // The controlling conditional expression of an if-statement, while-statement, // do-statement, or for-statement is a boolean-expression. The controlling // conditional expression of the ?: operator follows the same rules as a // boolean-expression, but for reasons of operator precedence is classified // as a conditional-or-expression. // // A boolean-expression is required to be implicitly convertible to bool // or of a type that implements operator true. If neither requirement // is satisfied, a binding-time error occurs. // // When a boolean expression cannot be implicitly converted to bool but does // implement operator true, then following evaluation of the expression, // the operator true implementation provided by that type is invoked // to produce a bool value. // // SPEC ERROR: The third paragraph above is obviously not correct; we need // SPEC ERROR: to do more than just check to see whether the type implements // SPEC ERROR: operator true. First off, the type could implement the operator // SPEC ERROR: several times: if it is a struct then it could implement it // SPEC ERROR: twice, to take both nullable and non-nullable arguments, and // SPEC ERROR: if it is a class or type parameter then it could have several // SPEC ERROR: implementations on its base classes or effective base classes. // SPEC ERROR: Second, the type of the argument could be S? where S implements // SPEC ERROR: operator true(S?); we want to look at S, not S?, when looking // SPEC ERROR: for applicable candidates. // // SPEC ERROR: Basically, the spec should say "use unary operator overload resolution // SPEC ERROR: to find the candidate set and choose a unique best operator true". var expr = BindValue(node, diagnostics, BindValueKind.RValue); var boolean = GetSpecialType(SpecialType.System_Boolean, diagnostics, node); if (expr.HasAnyErrors) { // The expression could not be bound. Insert a fake conversion // around it to bool and keep on going. // NOTE: no user-defined conversion candidates. return BoundConversion.Synthesized(node, BindToTypeForErrorRecovery(expr), Conversion.NoConversion, false, explicitCastInCode: false, conversionGroupOpt: null, ConstantValue.NotAvailable, boolean, hasErrors: true); } // Oddly enough, "if(dyn)" is bound not as a dynamic conversion to bool, but as a dynamic // invocation of operator true. if (expr.HasDynamicType()) { return new BoundUnaryOperator( node, UnaryOperatorKind.DynamicTrue, BindToNaturalType(expr, diagnostics), ConstantValue.NotAvailable, methodOpt: null, constrainedToTypeOpt: null, LookupResultKind.Viable, boolean) { WasCompilerGenerated = true }; } // Is the operand implicitly convertible to bool? CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var conversion = this.Conversions.ClassifyConversionFromExpression(expr, boolean, ref useSiteInfo); diagnostics.Add(expr.Syntax, useSiteInfo); if (conversion.IsImplicit) { if (conversion.Kind == ConversionKind.Identity) { // Check to see if we're assigning a boolean literal in a place where an // equality check would be more conventional. // NOTE: Don't do this check unless the expression will be returned // without being wrapped in another bound node (i.e. identity conversion). if (expr.Kind == BoundKind.AssignmentOperator) { var assignment = (BoundAssignmentOperator)expr; if (assignment.Right.Kind == BoundKind.Literal && assignment.Right.ConstantValue.Discriminator == ConstantValueTypeDiscriminator.Boolean) { Error(diagnostics, ErrorCode.WRN_IncorrectBooleanAssg, assignment.Syntax); } } } return CreateConversion( syntax: expr.Syntax, source: expr, conversion: conversion, isCast: false, conversionGroupOpt: null, wasCompilerGenerated: true, destination: boolean, diagnostics: diagnostics); } // It was not. Does it implement operator true? expr = BindToNaturalType(expr, diagnostics); var best = this.UnaryOperatorOverloadResolution(UnaryOperatorKind.True, expr, node, diagnostics, out LookupResultKind resultKind, out ImmutableArray<MethodSymbol> originalUserDefinedOperators); if (!best.HasValue) { // No. Give a "not convertible to bool" error. Debug.Assert(resultKind == LookupResultKind.Empty, "How could overload resolution fail if a user-defined true operator was found?"); Debug.Assert(originalUserDefinedOperators.IsEmpty, "How could overload resolution fail if a user-defined true operator was found?"); GenerateImplicitConversionError(diagnostics, node, conversion, expr, boolean); return BoundConversion.Synthesized(node, expr, Conversion.NoConversion, false, explicitCastInCode: false, conversionGroupOpt: null, ConstantValue.NotAvailable, boolean, hasErrors: true); } UnaryOperatorSignature signature = best.Signature; BoundExpression resultOperand = CreateConversion( node, expr, best.Conversion, isCast: false, conversionGroupOpt: null, destination: best.Signature.OperandType, diagnostics: diagnostics); CheckConstraintLanguageVersionAndRuntimeSupportForOperator(node, signature.Method, signature.ConstrainedToTypeOpt, diagnostics); // Consider op_true to be compiler-generated so that it doesn't appear in the semantic model. // UNDONE: If we decide to expose the operator in the semantic model, we'll have to remove the // WasCompilerGenerated flag (and possibly suppress the symbol in specific APIs). return new BoundUnaryOperator(node, signature.Kind, resultOperand, ConstantValue.NotAvailable, signature.Method, signature.ConstrainedToTypeOpt, resultKind, originalUserDefinedOperators, signature.ReturnType) { WasCompilerGenerated = true }; } private BoundStatement BindSwitchStatement(SwitchStatementSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); Binder switchBinder = this.GetBinder(node); return switchBinder.BindSwitchStatementCore(node, switchBinder, diagnostics); } internal virtual BoundStatement BindSwitchStatementCore(SwitchStatementSyntax node, Binder originalBinder, BindingDiagnosticBag diagnostics) { return this.Next.BindSwitchStatementCore(node, originalBinder, diagnostics); } internal virtual void BindPatternSwitchLabelForInference(CasePatternSwitchLabelSyntax node, BindingDiagnosticBag diagnostics) { this.Next.BindPatternSwitchLabelForInference(node, diagnostics); } private BoundStatement BindWhile(WhileStatementSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); var loopBinder = this.GetBinder(node); Debug.Assert(loopBinder != null); return loopBinder.BindWhileParts(diagnostics, loopBinder); } internal virtual BoundWhileStatement BindWhileParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindWhileParts(diagnostics, originalBinder); } private BoundStatement BindDo(DoStatementSyntax node, BindingDiagnosticBag diagnostics) { var loopBinder = this.GetBinder(node); Debug.Assert(loopBinder != null); return loopBinder.BindDoParts(diagnostics, loopBinder); } internal virtual BoundDoStatement BindDoParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindDoParts(diagnostics, originalBinder); } internal BoundForStatement BindFor(ForStatementSyntax node, BindingDiagnosticBag diagnostics) { var loopBinder = this.GetBinder(node); Debug.Assert(loopBinder != null); return loopBinder.BindForParts(diagnostics, loopBinder); } internal virtual BoundForStatement BindForParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindForParts(diagnostics, originalBinder); } internal BoundStatement BindForOrUsingOrFixedDeclarations(VariableDeclarationSyntax nodeOpt, LocalDeclarationKind localKind, BindingDiagnosticBag diagnostics, out ImmutableArray<BoundLocalDeclaration> declarations) { if (nodeOpt == null) { declarations = ImmutableArray<BoundLocalDeclaration>.Empty; return null; } var typeSyntax = nodeOpt.Type; // Fixed and using variables are not allowed to be ref-like, but regular variables are if (localKind == LocalDeclarationKind.RegularVariable) { typeSyntax = typeSyntax.SkipRef(out _); } AliasSymbol alias; bool isVar; TypeWithAnnotations declType = BindTypeOrVarKeyword(typeSyntax, diagnostics, out isVar, out alias); Debug.Assert(declType.HasType || isVar); var variables = nodeOpt.Variables; int count = variables.Count; Debug.Assert(count > 0); if (isVar && count > 1) { // There are a number of ways in which a var decl can be illegal, but in these // cases we should report an error and then keep right on going with the inference. Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, nodeOpt); } var declarationArray = new BoundLocalDeclaration[count]; for (int i = 0; i < count; i++) { var variableDeclarator = variables[i]; bool includeBoundType = i == 0; //To avoid duplicated expressions, only the first declaration should contain the bound type. var declaration = BindVariableDeclaration(localKind, isVar, variableDeclarator, typeSyntax, declType, alias, diagnostics, includeBoundType); declarationArray[i] = declaration; } declarations = declarationArray.AsImmutableOrNull(); return (count == 1) ? (BoundStatement)declarations[0] : new BoundMultipleLocalDeclarations(nodeOpt, declarations); } internal BoundStatement BindStatementExpressionList(SeparatedSyntaxList<ExpressionSyntax> statements, BindingDiagnosticBag diagnostics) { int count = statements.Count; if (count == 0) { return null; } else if (count == 1) { var syntax = statements[0]; return BindExpressionStatement(syntax, syntax, false, diagnostics); } else { var statementBuilder = ArrayBuilder<BoundStatement>.GetInstance(); for (int i = 0; i < count; i++) { var syntax = statements[i]; var statement = BindExpressionStatement(syntax, syntax, false, diagnostics); statementBuilder.Add(statement); } return BoundStatementList.Synthesized(statements.Node, statementBuilder.ToImmutableAndFree()); } } private BoundStatement BindForEach(CommonForEachStatementSyntax node, BindingDiagnosticBag diagnostics) { Binder loopBinder = this.GetBinder(node); return this.GetBinder(node.Expression).WrapWithVariablesIfAny(node.Expression, loopBinder.BindForEachParts(diagnostics, loopBinder)); } internal virtual BoundStatement BindForEachParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindForEachParts(diagnostics, originalBinder); } /// <summary> /// Like BindForEachParts, but only bind the deconstruction part of the foreach, for purpose of inferring the types of the declared locals. /// </summary> internal virtual BoundStatement BindForEachDeconstruction(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindForEachDeconstruction(diagnostics, originalBinder); } private BoundStatement BindBreak(BreakStatementSyntax node, BindingDiagnosticBag diagnostics) { var target = this.BreakLabel; if ((object)target == null) { Error(diagnostics, ErrorCode.ERR_NoBreakOrCont, node); return new BoundBadStatement(node, ImmutableArray<BoundNode>.Empty, hasErrors: true); } return new BoundBreakStatement(node, target); } private BoundStatement BindContinue(ContinueStatementSyntax node, BindingDiagnosticBag diagnostics) { var target = this.ContinueLabel; if ((object)target == null) { Error(diagnostics, ErrorCode.ERR_NoBreakOrCont, node); return new BoundBadStatement(node, ImmutableArray<BoundNode>.Empty, hasErrors: true); } return new BoundContinueStatement(node, target); } private static SwitchBinder GetSwitchBinder(Binder binder) { SwitchBinder switchBinder = binder as SwitchBinder; while (binder != null && switchBinder == null) { binder = binder.Next; switchBinder = binder as SwitchBinder; } return switchBinder; } protected static bool IsInAsyncMethod(MethodSymbol method) { return (object)method != null && method.IsAsync; } protected bool IsInAsyncMethod() { return IsInAsyncMethod(this.ContainingMemberOrLambda as MethodSymbol); } protected bool IsEffectivelyTaskReturningAsyncMethod() { var symbol = this.ContainingMemberOrLambda; return symbol?.Kind == SymbolKind.Method && ((MethodSymbol)symbol).IsAsyncEffectivelyReturningTask(this.Compilation); } protected bool IsEffectivelyGenericTaskReturningAsyncMethod() { var symbol = this.ContainingMemberOrLambda; return symbol?.Kind == SymbolKind.Method && ((MethodSymbol)symbol).IsAsyncEffectivelyReturningGenericTask(this.Compilation); } protected bool IsIAsyncEnumerableOrIAsyncEnumeratorReturningAsyncMethod() { var symbol = this.ContainingMemberOrLambda; if (symbol?.Kind == SymbolKind.Method) { var method = (MethodSymbol)symbol; return method.IsAsyncReturningIAsyncEnumerable(this.Compilation) || method.IsAsyncReturningIAsyncEnumerator(this.Compilation); } return false; } protected virtual TypeSymbol GetCurrentReturnType(out RefKind refKind) { var symbol = this.ContainingMemberOrLambda as MethodSymbol; if ((object)symbol != null) { refKind = symbol.RefKind; TypeSymbol returnType = symbol.ReturnType; if ((object)returnType == LambdaSymbol.ReturnTypeIsBeingInferred) { return null; } return returnType; } refKind = RefKind.None; return null; } private BoundStatement BindReturn(ReturnStatementSyntax syntax, BindingDiagnosticBag diagnostics) { var refKind = RefKind.None; var expressionSyntax = syntax.Expression?.CheckAndUnwrapRefExpression(diagnostics, out refKind); BoundExpression arg = null; if (expressionSyntax != null) { BindValueKind requiredValueKind = GetRequiredReturnValueKind(refKind); arg = BindValue(expressionSyntax, diagnostics, requiredValueKind); } else { // If this is a void return statement in a script, return default(T). var interactiveInitializerMethod = this.ContainingMemberOrLambda as SynthesizedInteractiveInitializerMethod; if (interactiveInitializerMethod != null) { arg = new BoundDefaultExpression(interactiveInitializerMethod.GetNonNullSyntaxNode(), interactiveInitializerMethod.ResultType); } } RefKind sigRefKind; TypeSymbol retType = GetCurrentReturnType(out sigRefKind); bool hasErrors = false; if (IsDirectlyInIterator) { diagnostics.Add(ErrorCode.ERR_ReturnInIterator, syntax.ReturnKeyword.GetLocation()); hasErrors = true; } else if (IsInAsyncMethod()) { if (refKind != RefKind.None) { // This can happen if we are binding an async anonymous method to a delegate type. diagnostics.Add(ErrorCode.ERR_MustNotHaveRefReturn, syntax.ReturnKeyword.GetLocation()); hasErrors = true; } else if (IsIAsyncEnumerableOrIAsyncEnumeratorReturningAsyncMethod()) { diagnostics.Add(ErrorCode.ERR_ReturnInIterator, syntax.ReturnKeyword.GetLocation()); hasErrors = true; } } else if ((object)retType != null && (refKind != RefKind.None) != (sigRefKind != RefKind.None)) { var errorCode = refKind != RefKind.None ? ErrorCode.ERR_MustNotHaveRefReturn : ErrorCode.ERR_MustHaveRefReturn; diagnostics.Add(errorCode, syntax.ReturnKeyword.GetLocation()); hasErrors = true; } if (arg != null) { hasErrors |= arg.HasErrors || ((object)arg.Type != null && arg.Type.IsErrorType()); } if (hasErrors) { return new BoundReturnStatement(syntax, refKind, BindToTypeForErrorRecovery(arg), hasErrors: true); } // The return type could be null; we might be attempting to infer the return type either // because of method type inference, or because we are attempting to do error analysis // on a lambda expression of unknown return type. if ((object)retType != null) { if (retType.IsVoidType() || IsEffectivelyTaskReturningAsyncMethod()) { if (arg != null) { var container = this.ContainingMemberOrLambda; var lambda = container as LambdaSymbol; if ((object)lambda != null) { // Error case: void-returning or async task-returning method or lambda with "return x;" var errorCode = retType.IsVoidType() ? ErrorCode.ERR_RetNoObjectRequiredLambda : ErrorCode.ERR_TaskRetNoObjectRequiredLambda; // Anonymous function converted to a void returning delegate cannot return a value Error(diagnostics, errorCode, syntax.ReturnKeyword); hasErrors = true; // COMPATIBILITY: The native compiler also produced an error // COMPATIBILITY: "Cannot convert lambda expression to delegate type 'Action' because some of the // COMPATIBILITY: return types in the block are not implicitly convertible to the delegate return type" // COMPATIBILITY: This error doesn't make sense in the "void" case because the whole idea of // COMPATIBILITY: "conversion to void" is a bit unusual, and we've already given a good error. } else { // Error case: void-returning or async task-returning method or lambda with "return x;" var errorCode = retType.IsVoidType() ? ErrorCode.ERR_RetNoObjectRequired : ErrorCode.ERR_TaskRetNoObjectRequired; Error(diagnostics, errorCode, syntax.ReturnKeyword, container); hasErrors = true; } } } else { if (arg == null) { // Error case: non-void-returning or Task<T>-returning method or lambda but just have "return;" var requiredType = IsEffectivelyGenericTaskReturningAsyncMethod() ? retType.GetMemberTypeArgumentsNoUseSiteDiagnostics().Single() : retType; Error(diagnostics, ErrorCode.ERR_RetObjectRequired, syntax.ReturnKeyword, requiredType); hasErrors = true; } else { arg = CreateReturnConversion(syntax, diagnostics, arg, sigRefKind, retType); arg = ValidateEscape(arg, Binder.ExternalScope, refKind != RefKind.None, diagnostics); } } } else { // Check that the returned expression is not void. if ((object)arg?.Type != null && arg.Type.IsVoidType()) { Error(diagnostics, ErrorCode.ERR_CantReturnVoid, expressionSyntax); hasErrors = true; } } return new BoundReturnStatement(syntax, refKind, hasErrors ? BindToTypeForErrorRecovery(arg) : arg, hasErrors); } internal BoundExpression CreateReturnConversion( SyntaxNode syntax, BindingDiagnosticBag diagnostics, BoundExpression argument, RefKind returnRefKind, TypeSymbol returnType) { // If the return type is not void then the expression must be implicitly convertible. Conversion conversion; bool badAsyncReturnAlreadyReported = false; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if (IsInAsyncMethod()) { Debug.Assert(returnRefKind == RefKind.None); if (!IsEffectivelyGenericTaskReturningAsyncMethod()) { conversion = Conversion.NoConversion; badAsyncReturnAlreadyReported = true; } else { returnType = returnType.GetMemberTypeArgumentsNoUseSiteDiagnostics().Single(); conversion = this.Conversions.ClassifyConversionFromExpression(argument, returnType, ref useSiteInfo); } } else { conversion = this.Conversions.ClassifyConversionFromExpression(argument, returnType, ref useSiteInfo); } diagnostics.Add(syntax, useSiteInfo); if (!argument.HasAnyErrors) { if (returnRefKind != RefKind.None) { if (conversion.Kind != ConversionKind.Identity) { Error(diagnostics, ErrorCode.ERR_RefReturnMustHaveIdentityConversion, argument.Syntax, returnType); argument = argument.WithHasErrors(); } else { return BindToNaturalType(argument, diagnostics); } } else if (!conversion.IsImplicit || !conversion.IsValid) { if (!badAsyncReturnAlreadyReported) { RefKind unusedRefKind; if (IsEffectivelyGenericTaskReturningAsyncMethod() && TypeSymbol.Equals(argument.Type, this.GetCurrentReturnType(out unusedRefKind), TypeCompareKind.ConsiderEverything2)) { // Since this is an async method, the return expression must be of type '{0}' rather than 'Task<{0}>' Error(diagnostics, ErrorCode.ERR_BadAsyncReturnExpression, argument.Syntax, returnType); } else { GenerateImplicitConversionError(diagnostics, argument.Syntax, conversion, argument, returnType); if (this.ContainingMemberOrLambda is LambdaSymbol) { ReportCantConvertLambdaReturn(argument.Syntax, diagnostics); } } } } } return CreateConversion(argument.Syntax, argument, conversion, isCast: false, conversionGroupOpt: null, returnType, diagnostics); } private BoundTryStatement BindTryStatement(TryStatementSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); var tryBlock = BindEmbeddedBlock(node.Block, diagnostics); var catchBlocks = BindCatchBlocks(node.Catches, diagnostics); var finallyBlockOpt = (node.Finally != null) ? BindEmbeddedBlock(node.Finally.Block, diagnostics) : null; return new BoundTryStatement(node, tryBlock, catchBlocks, finallyBlockOpt); } private ImmutableArray<BoundCatchBlock> BindCatchBlocks(SyntaxList<CatchClauseSyntax> catchClauses, BindingDiagnosticBag diagnostics) { int n = catchClauses.Count; if (n == 0) { return ImmutableArray<BoundCatchBlock>.Empty; } var catchBlocks = ArrayBuilder<BoundCatchBlock>.GetInstance(n); var hasCatchAll = false; foreach (var catchSyntax in catchClauses) { if (hasCatchAll) { diagnostics.Add(ErrorCode.ERR_TooManyCatches, catchSyntax.CatchKeyword.GetLocation()); } var catchBinder = this.GetBinder(catchSyntax); var catchBlock = catchBinder.BindCatchBlock(catchSyntax, catchBlocks, diagnostics); catchBlocks.Add(catchBlock); hasCatchAll |= catchSyntax.Declaration == null && catchSyntax.Filter == null; } return catchBlocks.ToImmutableAndFree(); } private BoundCatchBlock BindCatchBlock(CatchClauseSyntax node, ArrayBuilder<BoundCatchBlock> previousBlocks, BindingDiagnosticBag diagnostics) { bool hasError = false; TypeSymbol type = null; BoundExpression boundFilter = null; var declaration = node.Declaration; if (declaration != null) { // Note: The type is being bound twice: here and in LocalSymbol.Type. Currently, // LocalSymbol.Type ignores diagnostics so it seems cleaner to bind the type here // as well. However, if LocalSymbol.Type is changed to report diagnostics, we'll // need to avoid binding here since that will result in duplicate diagnostics. type = this.BindType(declaration.Type, diagnostics).Type; Debug.Assert((object)type != null); if (type.IsErrorType()) { hasError = true; } else { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); TypeSymbol effectiveType = type.EffectiveType(ref useSiteInfo); if (!Compilation.IsExceptionType(effectiveType, ref useSiteInfo)) { // "The type caught or thrown must be derived from System.Exception" Error(diagnostics, ErrorCode.ERR_BadExceptionType, declaration.Type); hasError = true; diagnostics.Add(declaration.Type, useSiteInfo); } else { diagnostics.AddDependencies(useSiteInfo); } } } var filter = node.Filter; if (filter != null) { var filterBinder = this.GetBinder(filter); boundFilter = filterBinder.BindCatchFilter(filter, diagnostics); hasError |= boundFilter.HasAnyErrors; } if (!hasError) { // TODO: Loop is O(n), caller is O(n^2). Perhaps we could iterate in reverse order (since it's easier to find // base types than to find derived types). Debug.Assert(((object)type == null) || !type.IsErrorType()); foreach (var previousBlock in previousBlocks) { var previousType = previousBlock.ExceptionTypeOpt; // If the previous type is a generic parameter we don't know what exception types it's gonna catch exactly. // If it is a class-type we know it's gonna catch all exception types of its type and types that are derived from it. // So if the current type is a class-type (or an effective base type of a generic parameter) // that derives from the previous type the current catch is unreachable. if (previousBlock.ExceptionFilterOpt == null && (object)previousType != null && !previousType.IsErrorType()) { if ((object)type != null) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if (Conversions.HasIdentityOrImplicitReferenceConversion(type, previousType, ref useSiteInfo)) { // "A previous catch clause already catches all exceptions of this or of a super type ('{0}')" Error(diagnostics, ErrorCode.ERR_UnreachableCatch, declaration.Type, previousType); diagnostics.Add(declaration.Type, useSiteInfo); hasError = true; break; } diagnostics.Add(declaration.Type, useSiteInfo); } else if (TypeSymbol.Equals(previousType, Compilation.GetWellKnownType(WellKnownType.System_Exception), TypeCompareKind.ConsiderEverything2) && Compilation.SourceAssembly.RuntimeCompatibilityWrapNonExceptionThrows) { // If the RuntimeCompatibility(WrapNonExceptionThrows = false) is applied on the source assembly or any referenced netmodule. // an empty catch may catch exceptions that don't derive from System.Exception. // "A previous catch clause already catches all exceptions..." Error(diagnostics, ErrorCode.WRN_UnreachableGeneralCatch, node.CatchKeyword); break; } } } } var binder = GetBinder(node); Debug.Assert(binder != null); ImmutableArray<LocalSymbol> locals = binder.GetDeclaredLocalsForScope(node); BoundExpression exceptionSource = null; LocalSymbol local = locals.FirstOrDefault(); if (local?.DeclarationKind == LocalDeclarationKind.CatchVariable) { Debug.Assert(local.Type.IsErrorType() || (TypeSymbol.Equals(local.Type, type, TypeCompareKind.ConsiderEverything2))); // Check for local variable conflicts in the *enclosing* binder, not the *current* binder; // obviously we will find a local of the given name in the current binder. hasError |= this.ValidateDeclarationNameConflictsInScope(local, diagnostics); exceptionSource = new BoundLocal(declaration, local, ConstantValue.NotAvailable, local.Type); } var block = BindEmbeddedBlock(node.Block, diagnostics); return new BoundCatchBlock(node, locals, exceptionSource, type, exceptionFilterPrologueOpt: null, boundFilter, block, hasError); } private BoundExpression BindCatchFilter(CatchFilterClauseSyntax filter, BindingDiagnosticBag diagnostics) { BoundExpression boundFilter = this.BindBooleanExpression(filter.FilterExpression, diagnostics); if (boundFilter.ConstantValue != ConstantValue.NotAvailable) { // Depending on whether the filter constant is true or false, and whether there are other catch clauses, // we suggest different actions var errorCode = boundFilter.ConstantValue.BooleanValue ? ErrorCode.WRN_FilterIsConstantTrue : (filter.Parent.Parent is TryStatementSyntax s && s.Catches.Count == 1 && s.Finally == null) ? ErrorCode.WRN_FilterIsConstantFalseRedundantTryCatch : ErrorCode.WRN_FilterIsConstantFalse; // Since the expression is a constant, the name can be retrieved from the first token Error(diagnostics, errorCode, filter.FilterExpression); } return boundFilter; } // Report an extra error on the return if we are in a lambda conversion. private void ReportCantConvertLambdaReturn(SyntaxNode syntax, BindingDiagnosticBag diagnostics) { // Suppress this error if the lambda is a result of a query rewrite. if (syntax.Parent is QueryClauseSyntax || syntax.Parent is SelectOrGroupClauseSyntax) return; var lambda = this.ContainingMemberOrLambda as LambdaSymbol; if ((object)lambda != null) { Location location = GetLocationForDiagnostics(syntax); if (IsInAsyncMethod()) { // Cannot convert async {0} to intended delegate type. An async {0} may return void, Task or Task<T>, none of which are convertible to '{1}'. Error(diagnostics, ErrorCode.ERR_CantConvAsyncAnonFuncReturns, location, lambda.MessageID.Localize(), lambda.ReturnType); } else { // 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 Error(diagnostics, ErrorCode.ERR_CantConvAnonMethReturns, location, lambda.MessageID.Localize()); } } } private static Location GetLocationForDiagnostics(SyntaxNode node) { switch (node) { case LambdaExpressionSyntax lambdaSyntax: return Location.Create(lambdaSyntax.SyntaxTree, Text.TextSpan.FromBounds(lambdaSyntax.SpanStart, lambdaSyntax.ArrowToken.Span.End)); case AnonymousMethodExpressionSyntax anonymousMethodSyntax: return Location.Create(anonymousMethodSyntax.SyntaxTree, Text.TextSpan.FromBounds(anonymousMethodSyntax.SpanStart, anonymousMethodSyntax.ParameterList?.Span.End ?? anonymousMethodSyntax.DelegateKeyword.Span.End)); } return node.Location; } private static bool IsValidStatementExpression(SyntaxNode syntax, BoundExpression expression) { bool syntacticallyValid = SyntaxFacts.IsStatementExpression(syntax); if (!syntacticallyValid) { return false; } if (expression.IsSuppressed) { return false; } // It is possible that an expression is syntactically valid but semantic analysis // reveals it to be illegal in a statement expression: "new MyDelegate(M)" for example // is not legal because it is a delegate-creation-expression and not an // object-creation-expression, but of course we don't know that syntactically. if (expression.Kind == BoundKind.DelegateCreationExpression || expression.Kind == BoundKind.NameOfOperator) { return false; } return true; } /// <summary> /// Wrap a given expression e into a block as either { e; } or { return e; } /// Shared between lambda and expression-bodied method binding. /// </summary> internal BoundBlock CreateBlockFromExpression(CSharpSyntaxNode node, ImmutableArray<LocalSymbol> locals, RefKind refKind, BoundExpression expression, ExpressionSyntax expressionSyntax, BindingDiagnosticBag diagnostics) { RefKind returnRefKind; var returnType = GetCurrentReturnType(out returnRefKind); var syntax = expressionSyntax ?? expression.Syntax; BoundStatement statement; if (IsInAsyncMethod() && refKind != RefKind.None) { // This can happen if we are binding an async anonymous method to a delegate type. Error(diagnostics, ErrorCode.ERR_MustNotHaveRefReturn, syntax); expression = BindToTypeForErrorRecovery(expression); statement = new BoundReturnStatement(syntax, refKind, expression) { WasCompilerGenerated = true }; } else if ((object)returnType != null) { if ((refKind != RefKind.None) != (returnRefKind != RefKind.None) && expression.Kind != BoundKind.ThrowExpression) { var errorCode = refKind != RefKind.None ? ErrorCode.ERR_MustNotHaveRefReturn : ErrorCode.ERR_MustHaveRefReturn; Error(diagnostics, errorCode, syntax); expression = BindToTypeForErrorRecovery(expression); statement = new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true }; } else if (returnType.IsVoidType() || IsEffectivelyTaskReturningAsyncMethod()) { // If the return type is void then the expression is required to be a legal // statement expression. Debug.Assert(expressionSyntax != null || !IsValidExpressionBody(expressionSyntax, expression)); bool errors = false; if (expressionSyntax == null || !IsValidExpressionBody(expressionSyntax, expression)) { expression = BindToTypeForErrorRecovery(expression); Error(diagnostics, ErrorCode.ERR_IllegalStatement, syntax); errors = true; } else { expression = BindToNaturalType(expression, diagnostics); } // Don't mark compiler generated so that the rewriter generates sequence points var expressionStatement = new BoundExpressionStatement(syntax, expression, errors); CheckForUnobservedAwaitable(expression, diagnostics); statement = expressionStatement; } else if (IsIAsyncEnumerableOrIAsyncEnumeratorReturningAsyncMethod()) { Error(diagnostics, ErrorCode.ERR_ReturnInIterator, syntax); expression = BindToTypeForErrorRecovery(expression); statement = new BoundReturnStatement(syntax, returnRefKind, expression) { WasCompilerGenerated = true }; } else { expression = returnType.IsErrorType() ? BindToTypeForErrorRecovery(expression) : CreateReturnConversion(syntax, diagnostics, expression, refKind, returnType); statement = new BoundReturnStatement(syntax, returnRefKind, expression) { WasCompilerGenerated = true }; } } else if (expression.Type?.SpecialType == SpecialType.System_Void) { expression = BindToNaturalType(expression, diagnostics); statement = new BoundExpressionStatement(syntax, expression) { WasCompilerGenerated = true }; } else { // When binding for purpose of inferring the return type of a lambda, we do not require returned expressions (such as `default` or switch expressions) to have a natural type var inferringLambda = this.ContainingMemberOrLambda is MethodSymbol method && (object)method.ReturnType == LambdaSymbol.ReturnTypeIsBeingInferred; if (!inferringLambda) { expression = BindToNaturalType(expression, diagnostics); } statement = new BoundReturnStatement(syntax, refKind, expression) { WasCompilerGenerated = true }; } // Need to attach the tree for when we generate sequence points. return new BoundBlock(node, locals, ImmutableArray.Create(statement)) { WasCompilerGenerated = node.Kind() != SyntaxKind.ArrowExpressionClause }; } private static bool IsValidExpressionBody(SyntaxNode expressionSyntax, BoundExpression expression) { return IsValidStatementExpression(expressionSyntax, expression) || expressionSyntax.Kind() == SyntaxKind.ThrowExpression; } /// <summary> /// Binds an expression-bodied member with expression e as either { return e; } or { e; }. /// </summary> internal virtual BoundBlock BindExpressionBodyAsBlock(ArrowExpressionClauseSyntax expressionBody, BindingDiagnosticBag diagnostics) { Binder bodyBinder = this.GetBinder(expressionBody); Debug.Assert(bodyBinder != null); return bindExpressionBodyAsBlockInternal(expressionBody, bodyBinder, diagnostics); // Use static local function to prevent accidentally calling instance methods on `this` instead of `bodyBinder` static BoundBlock bindExpressionBodyAsBlockInternal(ArrowExpressionClauseSyntax expressionBody, Binder bodyBinder, BindingDiagnosticBag diagnostics) { RefKind refKind; ExpressionSyntax expressionSyntax = expressionBody.Expression.CheckAndUnwrapRefExpression(diagnostics, out refKind); BindValueKind requiredValueKind = bodyBinder.GetRequiredReturnValueKind(refKind); BoundExpression expression = bodyBinder.BindValue(expressionSyntax, diagnostics, requiredValueKind); expression = bodyBinder.ValidateEscape(expression, Binder.ExternalScope, refKind != RefKind.None, diagnostics); return bodyBinder.CreateBlockFromExpression(expressionBody, bodyBinder.GetDeclaredLocalsForScope(expressionBody), refKind, expression, expressionSyntax, diagnostics); } } /// <summary> /// Binds a lambda with expression e as either { return e; } or { e; }. /// </summary> public BoundBlock BindLambdaExpressionAsBlock(ExpressionSyntax body, BindingDiagnosticBag diagnostics) { Binder bodyBinder = this.GetBinder(body); Debug.Assert(bodyBinder != null); RefKind refKind; var expressionSyntax = body.CheckAndUnwrapRefExpression(diagnostics, out refKind); BindValueKind requiredValueKind = GetRequiredReturnValueKind(refKind); BoundExpression expression = bodyBinder.BindValue(expressionSyntax, diagnostics, requiredValueKind); expression = ValidateEscape(expression, Binder.ExternalScope, refKind != RefKind.None, diagnostics); return bodyBinder.CreateBlockFromExpression(body, bodyBinder.GetDeclaredLocalsForScope(body), refKind, expression, expressionSyntax, diagnostics); } public BoundBlock CreateBlockFromExpression(ExpressionSyntax body, BoundExpression expression, BindingDiagnosticBag diagnostics) { Binder bodyBinder = this.GetBinder(body); Debug.Assert(bodyBinder != null); Debug.Assert(body.Kind() != SyntaxKind.RefExpression); return bodyBinder.CreateBlockFromExpression(body, bodyBinder.GetDeclaredLocalsForScope(body), RefKind.None, expression, body, diagnostics); } private BindValueKind GetRequiredReturnValueKind(RefKind refKind) { BindValueKind requiredValueKind = BindValueKind.RValue; if (refKind != RefKind.None) { GetCurrentReturnType(out var sigRefKind); requiredValueKind = sigRefKind == RefKind.Ref ? BindValueKind.RefReturn : BindValueKind.ReadonlyRef; } return requiredValueKind; } public virtual BoundNode BindMethodBody(CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics, bool includesFieldInitializers = false) { switch (syntax) { case RecordDeclarationSyntax recordDecl: return BindRecordConstructorBody(recordDecl, diagnostics); case BaseMethodDeclarationSyntax method: if (method.Kind() == SyntaxKind.ConstructorDeclaration) { return BindConstructorBody((ConstructorDeclarationSyntax)method, diagnostics, includesFieldInitializers); } return BindMethodBody(method, method.Body, method.ExpressionBody, diagnostics); case AccessorDeclarationSyntax accessor: return BindMethodBody(accessor, accessor.Body, accessor.ExpressionBody, diagnostics); case ArrowExpressionClauseSyntax arrowExpression: return BindExpressionBodyAsBlock(arrowExpression, diagnostics); case CompilationUnitSyntax compilationUnit: return BindSimpleProgram(compilationUnit, diagnostics); default: throw ExceptionUtilities.UnexpectedValue(syntax.Kind()); } } private BoundNode BindSimpleProgram(CompilationUnitSyntax compilationUnit, BindingDiagnosticBag diagnostics) { var simpleProgram = (SynthesizedSimpleProgramEntryPointSymbol)ContainingMemberOrLambda; return GetBinder(compilationUnit).BindSimpleProgramCompilationUnit(compilationUnit, simpleProgram, diagnostics); } private BoundNode BindSimpleProgramCompilationUnit(CompilationUnitSyntax compilationUnit, SynthesizedSimpleProgramEntryPointSymbol simpleProgram, BindingDiagnosticBag diagnostics) { ArrayBuilder<BoundStatement> boundStatements = ArrayBuilder<BoundStatement>.GetInstance(); foreach (var statement in compilationUnit.Members) { if (statement is GlobalStatementSyntax topLevelStatement) { var boundStatement = BindStatement(topLevelStatement.Statement, diagnostics); boundStatements.Add(boundStatement); } } return new BoundNonConstructorMethodBody(compilationUnit, FinishBindBlockParts(compilationUnit, boundStatements.ToImmutableAndFree(), diagnostics).MakeCompilerGenerated(), expressionBody: null); } private BoundNode BindRecordConstructorBody(RecordDeclarationSyntax recordDecl, BindingDiagnosticBag diagnostics) { Debug.Assert(recordDecl.ParameterList is object); Debug.Assert(recordDecl.IsKind(SyntaxKind.RecordDeclaration)); Binder bodyBinder = this.GetBinder(recordDecl); Debug.Assert(bodyBinder != null); BoundExpressionStatement initializer = null; if (recordDecl.PrimaryConstructorBaseTypeIfClass is PrimaryConstructorBaseTypeSyntax baseWithArguments) { initializer = bodyBinder.BindConstructorInitializer(baseWithArguments, diagnostics); } return new BoundConstructorMethodBody(recordDecl, bodyBinder.GetDeclaredLocalsForScope(recordDecl), initializer, blockBody: new BoundBlock(recordDecl, ImmutableArray<LocalSymbol>.Empty, ImmutableArray<BoundStatement>.Empty).MakeCompilerGenerated(), expressionBody: null); } internal virtual BoundExpressionStatement BindConstructorInitializer(PrimaryConstructorBaseTypeSyntax initializer, BindingDiagnosticBag diagnostics) { BoundExpression initializerInvocation = GetBinder(initializer).BindConstructorInitializer(initializer.ArgumentList, (MethodSymbol)this.ContainingMember(), diagnostics); var constructorInitializer = new BoundExpressionStatement(initializer, initializerInvocation); Debug.Assert(initializerInvocation.HasAnyErrors || constructorInitializer.IsConstructorInitializer(), "Please keep this bound node in sync with BoundNodeExtensions.IsConstructorInitializer."); return constructorInitializer; } private BoundNode BindConstructorBody(ConstructorDeclarationSyntax constructor, BindingDiagnosticBag diagnostics, bool includesFieldInitializers) { ConstructorInitializerSyntax initializer = constructor.Initializer; if (initializer == null && constructor.Body == null && constructor.ExpressionBody == null) { return null; } Binder bodyBinder = this.GetBinder(constructor); Debug.Assert(bodyBinder != null); bool thisInitializer = initializer?.IsKind(SyntaxKind.ThisConstructorInitializer) == true; if (!thisInitializer && ContainingType.GetMembersUnordered().OfType<SynthesizedRecordConstructor>().Any()) { var constructorSymbol = (MethodSymbol)this.ContainingMember(); if (!constructorSymbol.IsStatic && !SynthesizedRecordCopyCtor.IsCopyConstructor(constructorSymbol)) { // Note: we check the constructor initializer of copy constructors elsewhere Error(diagnostics, ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, initializer?.ThisOrBaseKeyword ?? constructor.Identifier); } } // The `: this()` initializer is ignored when it is a default value type constructor // and we need to include field initializers into the constructor. bool skipInitializer = includesFieldInitializers && thisInitializer && ContainingType.IsDefaultValueTypeConstructor(initializer); // Using BindStatement to bind block to make sure we are reusing results of partial binding in SemanticModel return new BoundConstructorMethodBody(constructor, bodyBinder.GetDeclaredLocalsForScope(constructor), skipInitializer ? new BoundNoOpStatement(constructor, NoOpStatementFlavor.Default) : initializer == null ? null : bodyBinder.BindConstructorInitializer(initializer, diagnostics), constructor.Body == null ? null : (BoundBlock)bodyBinder.BindStatement(constructor.Body, diagnostics), constructor.ExpressionBody == null ? null : bodyBinder.BindExpressionBodyAsBlock(constructor.ExpressionBody, constructor.Body == null ? diagnostics : BindingDiagnosticBag.Discarded)); } internal virtual BoundExpressionStatement BindConstructorInitializer(ConstructorInitializerSyntax initializer, BindingDiagnosticBag diagnostics) { BoundExpression initializerInvocation = GetBinder(initializer).BindConstructorInitializer(initializer.ArgumentList, (MethodSymbol)this.ContainingMember(), diagnostics); // Base WasCompilerGenerated state off of whether constructor is implicitly declared, this will ensure proper instrumentation. Debug.Assert(!this.ContainingMember().IsImplicitlyDeclared); var constructorInitializer = new BoundExpressionStatement(initializer, initializerInvocation); Debug.Assert(initializerInvocation.HasAnyErrors || constructorInitializer.IsConstructorInitializer(), "Please keep this bound node in sync with BoundNodeExtensions.IsConstructorInitializer."); return constructorInitializer; } private BoundNode BindMethodBody(CSharpSyntaxNode declaration, BlockSyntax blockBody, ArrowExpressionClauseSyntax expressionBody, BindingDiagnosticBag diagnostics) { if (blockBody == null && expressionBody == null) { return null; } // Using BindStatement to bind block to make sure we are reusing results of partial binding in SemanticModel return new BoundNonConstructorMethodBody(declaration, blockBody == null ? null : (BoundBlock)BindStatement(blockBody, diagnostics), expressionBody == null ? null : BindExpressionBodyAsBlock(expressionBody, blockBody == null ? diagnostics : BindingDiagnosticBag.Discarded)); } internal virtual ImmutableArray<LocalSymbol> Locals { get { return ImmutableArray<LocalSymbol>.Empty; } } internal virtual ImmutableArray<LocalFunctionSymbol> LocalFunctions { get { return ImmutableArray<LocalFunctionSymbol>.Empty; } } internal virtual ImmutableArray<LabelSymbol> Labels { get { return ImmutableArray<LabelSymbol>.Empty; } } /// <summary> /// If this binder owns the scope that can declare extern aliases, a set of declared aliases should be returned (even if empty). /// Otherwise, a default instance should be returned. /// </summary> internal virtual ImmutableArray<AliasAndExternAliasDirective> ExternAliases { get { return default; } } /// <summary> /// If this binder owns the scope that can declare using aliases, a set of declared aliases should be returned (even if empty). /// Otherwise, a default instance should be returned. /// Note, only aliases syntactically declared within the enclosing declaration are included. For example, global aliases /// declared in a different compilation units are not included. /// </summary> internal virtual ImmutableArray<AliasAndUsingDirective> UsingAliases { get { return default; } } /// <summary> /// Perform a lookup for the specified method on the specified expression by attempting to invoke it /// </summary> /// <param name="receiver">The expression to perform pattern lookup on</param> /// <param name="methodName">Method to search for.</param> /// <param name="syntaxNode">The expression for which lookup is being performed</param> /// <param name="diagnostics">Populated with binding diagnostics.</param> /// <param name="result">The method symbol that was looked up, or null</param> /// <returns>A <see cref="PatternLookupResult"/> value with the outcome of the lookup</returns> internal PatternLookupResult PerformPatternMethodLookup(BoundExpression receiver, string methodName, SyntaxNode syntaxNode, BindingDiagnosticBag diagnostics, out MethodSymbol result) { var bindingDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); try { result = null; var boundAccess = BindInstanceMemberAccess( syntaxNode, syntaxNode, receiver, methodName, rightArity: 0, typeArgumentsSyntax: default, typeArgumentsWithAnnotations: default, invoked: true, indexed: false, bindingDiagnostics); if (boundAccess.Kind != BoundKind.MethodGroup) { // the thing is not a method return PatternLookupResult.NotAMethod; } // NOTE: Because we're calling this method with no arguments and we // explicitly ignore default values for params parameters // (see ParameterSymbol.IsOptional) we know that no ParameterArray // containing method can be invoked in normal form which allows // us to skip some work during the lookup. var analyzedArguments = AnalyzedArguments.GetInstance(); var patternMethodCall = BindMethodGroupInvocation( syntaxNode, syntaxNode, methodName, (BoundMethodGroup)boundAccess, analyzedArguments, bindingDiagnostics, queryClause: null, allowUnexpandedForm: false, anyApplicableCandidates: out _); analyzedArguments.Free(); if (patternMethodCall.Kind != BoundKind.Call) { return PatternLookupResult.NotCallable; } var call = (BoundCall)patternMethodCall; if (call.ResultKind == LookupResultKind.Empty) { return PatternLookupResult.NoResults; } // we have succeeded or almost succeeded to bind the method // report additional binding diagnostics that we have seen so far diagnostics.AddRange(bindingDiagnostics); var patternMethodSymbol = call.Method; if (patternMethodSymbol is ErrorMethodSymbol || patternMethodCall.HasAnyErrors) { return PatternLookupResult.ResultHasErrors; } // Success! result = patternMethodSymbol; return PatternLookupResult.Success; } finally { bindingDiagnostics.Free(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// This portion of the binder converts StatementSyntax nodes into BoundStatements /// </summary> internal partial class Binder { /// <summary> /// This is the set of parameters and local variables that were used as arguments to /// lock or using statements in enclosing scopes. /// </summary> /// <remarks> /// using (x) { } // x counts /// using (IDisposable y = null) { } // y does not count /// </remarks> internal virtual ImmutableHashSet<Symbol> LockedOrDisposedVariables { get { return Next.LockedOrDisposedVariables; } } /// <remarks> /// Noteworthy override is in MemberSemanticModel.IncrementalBinder (used for caching). /// </remarks> public virtual BoundStatement BindStatement(StatementSyntax node, BindingDiagnosticBag diagnostics) { if (node.AttributeLists.Count > 0) { var attributeList = node.AttributeLists[0]; // Currently, attributes are only allowed on local-functions. if (node.Kind() == SyntaxKind.LocalFunctionStatement) { CheckFeatureAvailability(attributeList, MessageID.IDS_FeatureLocalFunctionAttributes, diagnostics); } else if (node.Kind() != SyntaxKind.Block) { // Don't explicitly error here for blocks. Some codepaths bypass BindStatement // to directly call BindBlock. Error(diagnostics, ErrorCode.ERR_AttributesNotAllowed, attributeList); } } Debug.Assert(node != null); BoundStatement result; switch (node.Kind()) { case SyntaxKind.Block: result = BindBlock((BlockSyntax)node, diagnostics); break; case SyntaxKind.LocalDeclarationStatement: result = BindLocalDeclarationStatement((LocalDeclarationStatementSyntax)node, diagnostics); break; case SyntaxKind.LocalFunctionStatement: result = BindLocalFunctionStatement((LocalFunctionStatementSyntax)node, diagnostics); break; case SyntaxKind.ExpressionStatement: result = BindExpressionStatement((ExpressionStatementSyntax)node, diagnostics); break; case SyntaxKind.IfStatement: result = BindIfStatement((IfStatementSyntax)node, diagnostics); break; case SyntaxKind.SwitchStatement: result = BindSwitchStatement((SwitchStatementSyntax)node, diagnostics); break; case SyntaxKind.DoStatement: result = BindDo((DoStatementSyntax)node, diagnostics); break; case SyntaxKind.WhileStatement: result = BindWhile((WhileStatementSyntax)node, diagnostics); break; case SyntaxKind.ForStatement: result = BindFor((ForStatementSyntax)node, diagnostics); break; case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: result = BindForEach((CommonForEachStatementSyntax)node, diagnostics); break; case SyntaxKind.BreakStatement: result = BindBreak((BreakStatementSyntax)node, diagnostics); break; case SyntaxKind.ContinueStatement: result = BindContinue((ContinueStatementSyntax)node, diagnostics); break; case SyntaxKind.ReturnStatement: result = BindReturn((ReturnStatementSyntax)node, diagnostics); break; case SyntaxKind.FixedStatement: result = BindFixedStatement((FixedStatementSyntax)node, diagnostics); break; case SyntaxKind.LabeledStatement: result = BindLabeled((LabeledStatementSyntax)node, diagnostics); break; case SyntaxKind.GotoStatement: case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoDefaultStatement: result = BindGoto((GotoStatementSyntax)node, diagnostics); break; case SyntaxKind.TryStatement: result = BindTryStatement((TryStatementSyntax)node, diagnostics); break; case SyntaxKind.EmptyStatement: result = BindEmpty((EmptyStatementSyntax)node); break; case SyntaxKind.ThrowStatement: result = BindThrow((ThrowStatementSyntax)node, diagnostics); break; case SyntaxKind.UnsafeStatement: result = BindUnsafeStatement((UnsafeStatementSyntax)node, diagnostics); break; case SyntaxKind.UncheckedStatement: case SyntaxKind.CheckedStatement: result = BindCheckedStatement((CheckedStatementSyntax)node, diagnostics); break; case SyntaxKind.UsingStatement: result = BindUsingStatement((UsingStatementSyntax)node, diagnostics); break; case SyntaxKind.YieldBreakStatement: result = BindYieldBreakStatement((YieldStatementSyntax)node, diagnostics); break; case SyntaxKind.YieldReturnStatement: result = BindYieldReturnStatement((YieldStatementSyntax)node, diagnostics); break; case SyntaxKind.LockStatement: result = BindLockStatement((LockStatementSyntax)node, diagnostics); break; default: // NOTE: We could probably throw an exception here, but it's conceivable // that a non-parser syntax tree could reach this point with an unexpected // SyntaxKind and we don't want to throw if that occurs. result = new BoundBadStatement(node, ImmutableArray<BoundNode>.Empty, hasErrors: true); break; } BoundBlock block; Debug.Assert(result.WasCompilerGenerated == false || (result.Kind == BoundKind.Block && (block = (BoundBlock)result).Statements.Length == 1 && block.Statements.Single().WasCompilerGenerated == false), "Synthetic node would not get cached"); Debug.Assert(result.Syntax is StatementSyntax, "BoundStatement should be associated with a statement syntax."); Debug.Assert(System.Linq.Enumerable.Contains(result.Syntax.AncestorsAndSelf(), node), @"Bound statement (or one of its parents) should have same syntax as the given syntax node. Otherwise it may be confusing to the binder cache that uses syntax node as keys."); return result; } private BoundStatement BindCheckedStatement(CheckedStatementSyntax node, BindingDiagnosticBag diagnostics) { return BindEmbeddedBlock(node.Block, diagnostics); } private BoundStatement BindUnsafeStatement(UnsafeStatementSyntax node, BindingDiagnosticBag diagnostics) { var unsafeBinder = this.GetBinder(node); if (!this.Compilation.Options.AllowUnsafe) { Error(diagnostics, ErrorCode.ERR_IllegalUnsafe, node.UnsafeKeyword); } else if (this.IsIndirectlyInIterator) // called *after* we know the binder map has been created. { // Spec 8.2: "An iterator block always defines a safe context, even when its declaration // is nested in an unsafe context." Error(diagnostics, ErrorCode.ERR_IllegalInnerUnsafe, node.UnsafeKeyword); } return BindEmbeddedBlock(node.Block, diagnostics); } private BoundStatement BindFixedStatement(FixedStatementSyntax node, BindingDiagnosticBag diagnostics) { var fixedBinder = this.GetBinder(node); Debug.Assert(fixedBinder != null); fixedBinder.ReportUnsafeIfNotAllowed(node, diagnostics); return fixedBinder.BindFixedStatementParts(node, diagnostics); } private BoundStatement BindFixedStatementParts(FixedStatementSyntax node, BindingDiagnosticBag diagnostics) { VariableDeclarationSyntax declarationSyntax = node.Declaration; ImmutableArray<BoundLocalDeclaration> declarations; BindForOrUsingOrFixedDeclarations(declarationSyntax, LocalDeclarationKind.FixedVariable, diagnostics, out declarations); Debug.Assert(!declarations.IsEmpty); BoundMultipleLocalDeclarations boundMultipleDeclarations = new BoundMultipleLocalDeclarations(declarationSyntax, declarations); BoundStatement boundBody = BindPossibleEmbeddedStatement(node.Statement, diagnostics); return new BoundFixedStatement(node, GetDeclaredLocalsForScope(node), boundMultipleDeclarations, boundBody); } private void CheckRequiredLangVersionForAsyncIteratorMethods(BindingDiagnosticBag diagnostics) { var method = (MethodSymbol)this.ContainingMemberOrLambda; if (method.IsAsync) { MessageID.IDS_FeatureAsyncStreams.CheckFeatureAvailability( diagnostics, method.DeclaringCompilation, method.Locations[0]); } } protected virtual void ValidateYield(YieldStatementSyntax node, BindingDiagnosticBag diagnostics) { Next?.ValidateYield(node, diagnostics); } private BoundStatement BindYieldReturnStatement(YieldStatementSyntax node, BindingDiagnosticBag diagnostics) { ValidateYield(node, diagnostics); TypeSymbol elementType = GetIteratorElementType().Type; BoundExpression argument = (node.Expression == null) ? BadExpression(node).MakeCompilerGenerated() : BindValue(node.Expression, diagnostics, BindValueKind.RValue); argument = ValidateEscape(argument, ExternalScope, isByRef: false, diagnostics: diagnostics); if (!argument.HasAnyErrors) { argument = GenerateConversionForAssignment(elementType, argument, diagnostics); } else { argument = BindToTypeForErrorRecovery(argument); } // NOTE: it's possible that more than one of these conditions is satisfied and that // we won't report the syntactically innermost. However, dev11 appears to check // them in this order, regardless of syntactic nesting (StatementBinder::bindYield). if (this.Flags.Includes(BinderFlags.InFinallyBlock)) { Error(diagnostics, ErrorCode.ERR_BadYieldInFinally, node.YieldKeyword); } else if (this.Flags.Includes(BinderFlags.InTryBlockOfTryCatch)) { Error(diagnostics, ErrorCode.ERR_BadYieldInTryOfCatch, node.YieldKeyword); } else if (this.Flags.Includes(BinderFlags.InCatchBlock)) { Error(diagnostics, ErrorCode.ERR_BadYieldInCatch, node.YieldKeyword); } else if (BindingTopLevelScriptCode) { Error(diagnostics, ErrorCode.ERR_YieldNotAllowedInScript, node.YieldKeyword); } CheckRequiredLangVersionForAsyncIteratorMethods(diagnostics); return new BoundYieldReturnStatement(node, argument); } private BoundStatement BindYieldBreakStatement(YieldStatementSyntax node, BindingDiagnosticBag diagnostics) { if (this.Flags.Includes(BinderFlags.InFinallyBlock)) { Error(diagnostics, ErrorCode.ERR_BadYieldInFinally, node.YieldKeyword); } else if (BindingTopLevelScriptCode) { Error(diagnostics, ErrorCode.ERR_YieldNotAllowedInScript, node.YieldKeyword); } ValidateYield(node, diagnostics); CheckRequiredLangVersionForAsyncIteratorMethods(diagnostics); return new BoundYieldBreakStatement(node); } private BoundStatement BindLockStatement(LockStatementSyntax node, BindingDiagnosticBag diagnostics) { var lockBinder = this.GetBinder(node); Debug.Assert(lockBinder != null); return lockBinder.BindLockStatementParts(diagnostics, lockBinder); } internal virtual BoundStatement BindLockStatementParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindLockStatementParts(diagnostics, originalBinder); } private BoundStatement BindUsingStatement(UsingStatementSyntax node, BindingDiagnosticBag diagnostics) { var usingBinder = this.GetBinder(node); Debug.Assert(usingBinder != null); return usingBinder.BindUsingStatementParts(diagnostics, usingBinder); } internal virtual BoundStatement BindUsingStatementParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindUsingStatementParts(diagnostics, originalBinder); } internal BoundStatement BindPossibleEmbeddedStatement(StatementSyntax node, BindingDiagnosticBag diagnostics) { Binder binder; switch (node.Kind()) { case SyntaxKind.LocalDeclarationStatement: // Local declarations are not legal in contexts where we need embedded statements. diagnostics.Add(ErrorCode.ERR_BadEmbeddedStmt, node.GetLocation()); // fall through goto case SyntaxKind.ExpressionStatement; case SyntaxKind.ExpressionStatement: case SyntaxKind.LockStatement: case SyntaxKind.IfStatement: case SyntaxKind.YieldReturnStatement: case SyntaxKind.ReturnStatement: case SyntaxKind.ThrowStatement: binder = this.GetBinder(node); Debug.Assert(binder != null); return binder.WrapWithVariablesIfAny(node, binder.BindStatement(node, diagnostics)); case SyntaxKind.LabeledStatement: case SyntaxKind.LocalFunctionStatement: // Labeled statements and local function statements are not legal in contexts where we need embedded statements. diagnostics.Add(ErrorCode.ERR_BadEmbeddedStmt, node.GetLocation()); binder = this.GetBinder(node); Debug.Assert(binder != null); return binder.WrapWithVariablesAndLocalFunctionsIfAny(node, binder.BindStatement(node, diagnostics)); case SyntaxKind.SwitchStatement: var switchStatement = (SwitchStatementSyntax)node; binder = this.GetBinder(switchStatement.Expression); Debug.Assert(binder != null); return binder.WrapWithVariablesIfAny(switchStatement.Expression, binder.BindStatement(node, diagnostics)); case SyntaxKind.EmptyStatement: var emptyStatement = (EmptyStatementSyntax)node; if (!emptyStatement.SemicolonToken.IsMissing) { switch (node.Parent.Kind()) { case SyntaxKind.ForStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: case SyntaxKind.WhileStatement: // For loop constructs, only warn if we see a block following the statement. // That indicates code like: "while (x) ; { }" // which is most likely a bug. if (emptyStatement.SemicolonToken.GetNextToken().Kind() != SyntaxKind.OpenBraceToken) { break; } goto default; default: // For non-loop constructs, always warn. This is for code like: // "if (x) ;" which is almost certainly a bug. diagnostics.Add(ErrorCode.WRN_PossibleMistakenNullStatement, node.GetLocation()); break; } } // fall through goto default; default: return BindStatement(node, diagnostics); } } private BoundExpression BindThrownExpression(ExpressionSyntax exprSyntax, BindingDiagnosticBag diagnostics, ref bool hasErrors) { var boundExpr = BindValue(exprSyntax, diagnostics, BindValueKind.RValue); if (Compilation.LanguageVersion < MessageID.IDS_FeatureSwitchExpression.RequiredVersion()) { // This is the pre-C# 8 algorithm for binding a thrown expression. // SPEC VIOLATION: The spec requires the thrown exception to have a type, and that the type // be System.Exception or derived from System.Exception. (Or, if a type parameter, to have // an effective base class that meets that criterion.) However, we allow the literal null // to be thrown, even though it does not meet that criterion and will at runtime always // produce a null reference exception. if (!boundExpr.IsLiteralNull()) { boundExpr = BindToNaturalType(boundExpr, diagnostics); var type = boundExpr.Type; // If the expression is a lambda, anonymous method, or method group then it will // have no compile-time type; give the same error as if the type was wrong. CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if ((object)type == null || !type.IsErrorType() && !Compilation.IsExceptionType(type.EffectiveType(ref useSiteInfo), ref useSiteInfo)) { diagnostics.Add(ErrorCode.ERR_BadExceptionType, exprSyntax.Location); hasErrors = true; diagnostics.Add(exprSyntax, useSiteInfo); } else { diagnostics.AddDependencies(useSiteInfo); } } } else { // In C# 8 and later we follow the ECMA specification, which neatly handles null and expressions of exception type. boundExpr = GenerateConversionForAssignment(GetWellKnownType(WellKnownType.System_Exception, diagnostics, exprSyntax), boundExpr, diagnostics); } return boundExpr; } private BoundStatement BindThrow(ThrowStatementSyntax node, BindingDiagnosticBag diagnostics) { BoundExpression boundExpr = null; bool hasErrors = false; ExpressionSyntax exprSyntax = node.Expression; if (exprSyntax != null) { boundExpr = BindThrownExpression(exprSyntax, diagnostics, ref hasErrors); } else if (!this.Flags.Includes(BinderFlags.InCatchBlock)) { diagnostics.Add(ErrorCode.ERR_BadEmptyThrow, node.ThrowKeyword.GetLocation()); hasErrors = true; } else if (this.Flags.Includes(BinderFlags.InNestedFinallyBlock)) { // There's a special error code for a rethrow in a finally clause in a catch clause. // Best guess interpretation: if an exception occurs within the nested try block // (i.e. the one in the catch clause, to which the finally clause is attached), // then it's not clear whether the runtime will try to rethrow the "inner" exception // or the "outer" exception. For this reason, the case is disallowed. diagnostics.Add(ErrorCode.ERR_BadEmptyThrowInFinally, node.ThrowKeyword.GetLocation()); hasErrors = true; } return new BoundThrowStatement(node, boundExpr, hasErrors); } private static BoundStatement BindEmpty(EmptyStatementSyntax node) { return new BoundNoOpStatement(node, NoOpStatementFlavor.Default); } private BoundLabeledStatement BindLabeled(LabeledStatementSyntax node, BindingDiagnosticBag diagnostics) { // TODO: verify that goto label lookup was valid (e.g. error checking of symbol resolution for labels) bool hasError = false; var result = LookupResult.GetInstance(); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var binder = this.LookupSymbolsWithFallback(result, node.Identifier.ValueText, arity: 0, useSiteInfo: ref useSiteInfo, options: LookupOptions.LabelsOnly); // result.Symbols can be empty in some malformed code, e.g. when a labeled statement is used an embedded statement in an if or foreach statement // In this case we create new label symbol on the fly, and an error is reported by parser var symbol = result.Symbols.Count > 0 && result.IsMultiViable ? (LabelSymbol)result.Symbols.First() : new SourceLabelSymbol((MethodSymbol)ContainingMemberOrLambda, node.Identifier); if (!symbol.IdentifierNodeOrToken.IsToken || symbol.IdentifierNodeOrToken.AsToken() != node.Identifier) { Error(diagnostics, ErrorCode.ERR_DuplicateLabel, node.Identifier, node.Identifier.ValueText); hasError = true; } // check to see if this label (illegally) hides a label from an enclosing scope if (binder != null) { result.Clear(); binder.Next.LookupSymbolsWithFallback(result, node.Identifier.ValueText, arity: 0, useSiteInfo: ref useSiteInfo, options: LookupOptions.LabelsOnly); if (result.IsMultiViable) { // The label '{0}' shadows another label by the same name in a contained scope Error(diagnostics, ErrorCode.ERR_LabelShadow, node.Identifier, node.Identifier.ValueText); hasError = true; } } diagnostics.Add(node, useSiteInfo); result.Free(); var body = BindStatement(node.Statement, diagnostics); return new BoundLabeledStatement(node, symbol, body, hasError); } private BoundStatement BindGoto(GotoStatementSyntax node, BindingDiagnosticBag diagnostics) { switch (node.Kind()) { case SyntaxKind.GotoStatement: var expression = BindLabel(node.Expression, diagnostics); var boundLabel = expression as BoundLabel; if (boundLabel == null) { // diagnostics already reported return new BoundBadStatement(node, ImmutableArray.Create<BoundNode>(expression), true); } var symbol = boundLabel.Label; return new BoundGotoStatement(node, symbol, null, boundLabel); case SyntaxKind.GotoCaseStatement: case SyntaxKind.GotoDefaultStatement: // SPEC: If the goto case statement is not enclosed by a switch statement, a compile-time error occurs. // SPEC: If the goto default statement is not enclosed by a switch statement, a compile-time error occurs. SwitchBinder binder = GetSwitchBinder(this); if (binder == null) { Error(diagnostics, ErrorCode.ERR_InvalidGotoCase, node); ImmutableArray<BoundNode> childNodes; if (node.Expression != null) { var value = BindRValueWithoutTargetType(node.Expression, BindingDiagnosticBag.Discarded); childNodes = ImmutableArray.Create<BoundNode>(value); } else { childNodes = ImmutableArray<BoundNode>.Empty; } return new BoundBadStatement(node, childNodes, true); } return binder.BindGotoCaseOrDefault(node, this, diagnostics); default: throw ExceptionUtilities.UnexpectedValue(node.Kind()); } } private BoundStatement BindLocalFunctionStatement(LocalFunctionStatementSyntax node, BindingDiagnosticBag diagnostics) { // already defined symbol in containing block var localSymbol = this.LookupLocalFunction(node.Identifier); var hasErrors = localSymbol.ScopeBinder .ValidateDeclarationNameConflictsInScope(localSymbol, diagnostics); BoundBlock blockBody = null; BoundBlock expressionBody = null; if (node.Body != null) { blockBody = runAnalysis(BindEmbeddedBlock(node.Body, diagnostics), diagnostics); if (node.ExpressionBody != null) { expressionBody = runAnalysis(BindExpressionBodyAsBlock(node.ExpressionBody, BindingDiagnosticBag.Discarded), BindingDiagnosticBag.Discarded); } } else if (node.ExpressionBody != null) { expressionBody = runAnalysis(BindExpressionBodyAsBlock(node.ExpressionBody, diagnostics), diagnostics); } else if (!hasErrors && (!localSymbol.IsExtern || !localSymbol.IsStatic)) { hasErrors = true; diagnostics.Add(ErrorCode.ERR_LocalFunctionMissingBody, localSymbol.Locations[0], localSymbol); } if (!hasErrors && (blockBody != null || expressionBody != null) && localSymbol.IsExtern) { hasErrors = true; diagnostics.Add(ErrorCode.ERR_ExternHasBody, localSymbol.Locations[0], localSymbol); } Debug.Assert(blockBody != null || expressionBody != null || (localSymbol.IsExtern && localSymbol.IsStatic) || hasErrors); localSymbol.GetDeclarationDiagnostics(diagnostics); Symbol.CheckForBlockAndExpressionBody( node.Body, node.ExpressionBody, node, diagnostics); return new BoundLocalFunctionStatement(node, localSymbol, blockBody, expressionBody, hasErrors); BoundBlock runAnalysis(BoundBlock block, BindingDiagnosticBag blockDiagnostics) { if (block != null) { // Have to do ControlFlowPass here because in MethodCompiler, we don't call this for synthed methods // rather we go directly to LowerBodyOrInitializer, which skips over flow analysis (which is in CompileMethod) // (the same thing - calling ControlFlowPass.Analyze in the lowering - is done for lambdas) // It's a bit of code duplication, but refactoring would make things worse. // However, we don't need to report diagnostics here. They will be reported when analyzing the parent method. var ignored = DiagnosticBag.GetInstance(); var endIsReachable = ControlFlowPass.Analyze(localSymbol.DeclaringCompilation, localSymbol, block, ignored); ignored.Free(); if (endIsReachable) { if (ImplicitReturnIsOkay(localSymbol)) { block = FlowAnalysisPass.AppendImplicitReturn(block, localSymbol); } else { blockDiagnostics.Add(ErrorCode.ERR_ReturnExpected, localSymbol.Locations[0], localSymbol); } } } return block; } } private bool ImplicitReturnIsOkay(MethodSymbol method) { return method.ReturnsVoid || method.IsIterator || method.IsAsyncEffectivelyReturningTask(this.Compilation); } public BoundStatement BindExpressionStatement(ExpressionStatementSyntax node, BindingDiagnosticBag diagnostics) { return BindExpressionStatement(node, node.Expression, node.AllowsAnyExpression, diagnostics); } private BoundExpressionStatement BindExpressionStatement(CSharpSyntaxNode node, ExpressionSyntax syntax, bool allowsAnyExpression, BindingDiagnosticBag diagnostics) { BoundExpressionStatement expressionStatement; var expression = BindRValueWithoutTargetType(syntax, diagnostics); ReportSuppressionIfNeeded(expression, diagnostics); if (!allowsAnyExpression && !IsValidStatementExpression(syntax, expression)) { if (!node.HasErrors) { Error(diagnostics, ErrorCode.ERR_IllegalStatement, syntax); } expressionStatement = new BoundExpressionStatement(node, expression, hasErrors: true); } else { expressionStatement = new BoundExpressionStatement(node, expression); } CheckForUnobservedAwaitable(expression, diagnostics); return expressionStatement; } /// <summary> /// Report an error if this is an awaitable async method invocation that is not being awaited. /// </summary> /// <remarks> /// The checks here are equivalent to StatementBinder::CheckForUnobservedAwaitable() in the native compiler. /// </remarks> private void CheckForUnobservedAwaitable(BoundExpression expression, BindingDiagnosticBag diagnostics) { if (CouldBeAwaited(expression)) { Error(diagnostics, ErrorCode.WRN_UnobservedAwaitableExpression, expression.Syntax); } } internal BoundStatement BindLocalDeclarationStatement(LocalDeclarationStatementSyntax node, BindingDiagnosticBag diagnostics) { if (node.UsingKeyword != default) { return BindUsingDeclarationStatementParts(node, diagnostics); } else { return BindDeclarationStatementParts(node, diagnostics); } } private BoundStatement BindUsingDeclarationStatementParts(LocalDeclarationStatementSyntax node, BindingDiagnosticBag diagnostics) { var usingDeclaration = UsingStatementBinder.BindUsingStatementOrDeclarationFromParts(node, node.UsingKeyword, node.AwaitKeyword, originalBinder: this, usingBinderOpt: null, diagnostics); Debug.Assert(usingDeclaration is BoundUsingLocalDeclarations); return usingDeclaration; } private BoundStatement BindDeclarationStatementParts(LocalDeclarationStatementSyntax node, BindingDiagnosticBag diagnostics) { var typeSyntax = node.Declaration.Type.SkipRef(out _); bool isConst = node.IsConst; bool isVar; AliasSymbol alias; TypeWithAnnotations declType = BindVariableTypeWithAnnotations(node.Declaration, diagnostics, typeSyntax, ref isConst, isVar: out isVar, alias: out alias); var kind = isConst ? LocalDeclarationKind.Constant : LocalDeclarationKind.RegularVariable; var variableList = node.Declaration.Variables; int variableCount = variableList.Count; if (variableCount == 1) { return BindVariableDeclaration(kind, isVar, variableList[0], typeSyntax, declType, alias, diagnostics, includeBoundType: true, associatedSyntaxNode: node); } else { BoundLocalDeclaration[] boundDeclarations = new BoundLocalDeclaration[variableCount]; int i = 0; foreach (var variableDeclarationSyntax in variableList) { bool includeBoundType = i == 0; //To avoid duplicated expressions, only the first declaration should contain the bound type. boundDeclarations[i++] = BindVariableDeclaration(kind, isVar, variableDeclarationSyntax, typeSyntax, declType, alias, diagnostics, includeBoundType); } return new BoundMultipleLocalDeclarations(node, boundDeclarations.AsImmutableOrNull()); } } /// <summary> /// Checks for a Dispose method on <paramref name="expr"/> and returns its <see cref="MethodSymbol"/> if found. /// </summary> /// <param name="expr">Expression on which to perform lookup</param> /// <param name="syntaxNode">The syntax node to perform lookup on</param> /// <param name="diagnostics">Populated with invocation errors, and warnings of near misses</param> /// <returns>The <see cref="MethodSymbol"/> of the Dispose method if one is found, otherwise null.</returns> internal MethodSymbol TryFindDisposePatternMethod(BoundExpression expr, SyntaxNode syntaxNode, bool hasAwait, BindingDiagnosticBag diagnostics) { Debug.Assert(expr is object); Debug.Assert(expr.Type is object); Debug.Assert(expr.Type.IsRefLikeType || hasAwait); // pattern dispose lookup is only valid on ref structs or asynchronous usings var result = PerformPatternMethodLookup(expr, hasAwait ? WellKnownMemberNames.DisposeAsyncMethodName : WellKnownMemberNames.DisposeMethodName, syntaxNode, diagnostics, out var disposeMethod); if (disposeMethod?.IsExtensionMethod == true) { // Extension methods should just be ignored, rather than rejected after-the-fact // Tracked by https://github.com/dotnet/roslyn/issues/32767 // extension methods do not contribute to pattern-based disposal disposeMethod = null; } else if ((!hasAwait && disposeMethod?.ReturnsVoid == false) || result == PatternLookupResult.NotAMethod) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if (this.IsAccessible(disposeMethod, ref useSiteInfo)) { diagnostics.Add(ErrorCode.WRN_PatternBadSignature, syntaxNode.Location, expr.Type, MessageID.IDS_Disposable.Localize(), disposeMethod); } diagnostics.Add(syntaxNode, useSiteInfo); disposeMethod = null; } return disposeMethod; } private TypeWithAnnotations BindVariableTypeWithAnnotations(CSharpSyntaxNode declarationNode, BindingDiagnosticBag diagnostics, TypeSyntax typeSyntax, ref bool isConst, out bool isVar, out AliasSymbol alias) { Debug.Assert( declarationNode is VariableDesignationSyntax || declarationNode.Kind() == SyntaxKind.VariableDeclaration || declarationNode.Kind() == SyntaxKind.DeclarationExpression || declarationNode.Kind() == SyntaxKind.DiscardDesignation); // If the type is "var" then suppress errors when binding it. "var" might be a legal type // or it might not; if it is not then we do not want to report an error. If it is, then // we want to treat the declaration as an explicitly typed declaration. TypeWithAnnotations declType = BindTypeOrVarKeyword(typeSyntax.SkipRef(out _), diagnostics, out isVar, out alias); Debug.Assert(declType.HasType || isVar); if (isVar) { // There are a number of ways in which a var decl can be illegal, but in these // cases we should report an error and then keep right on going with the inference. if (isConst) { Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableCannotBeConst, declarationNode); // Keep processing it as a non-const local. isConst = false; } // In the dev10 compiler the error recovery semantics for the illegal case // "var x = 10, y = 123.4;" are somewhat undesirable. // // First off, this is an error because a straw poll of language designers and // users showed that there was no consensus on whether the above should mean // "double x = 10, y = 123.4;", taking the best type available and substituting // that for "var", or treating it as "var x = 10; var y = 123.4;" -- since there // was no consensus we decided to simply make it illegal. // // In dev10 for error recovery in the IDE we do an odd thing -- we simply take // the type of the first variable and use it. So that is "int x = 10, y = 123.4;". // // This seems less than ideal. In the error recovery scenario it probably makes // more sense to treat that as "var x = 10; var y = 123.4;" and do each inference // separately. if (declarationNode.Parent.Kind() == SyntaxKind.LocalDeclarationStatement && ((VariableDeclarationSyntax)declarationNode).Variables.Count > 1 && !declarationNode.HasErrors) { Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, declarationNode); } } else { // In the native compiler when given a situation like // // D[] x; // // where D is a static type we report both that D cannot be an element type // of an array, and that D[] is not a valid type for a local variable. // This seems silly; the first error is entirely sufficient. We no longer // produce additional errors for local variables of arrays of static types. if (declType.IsStatic) { Error(diagnostics, ErrorCode.ERR_VarDeclIsStaticClass, typeSyntax, declType.Type); } if (isConst && !declType.Type.CanBeConst()) { Error(diagnostics, ErrorCode.ERR_BadConstType, typeSyntax, declType.Type); // Keep processing it as a non-const local. isConst = false; } } return declType; } internal BoundExpression BindInferredVariableInitializer(BindingDiagnosticBag diagnostics, RefKind refKind, EqualsValueClauseSyntax initializer, CSharpSyntaxNode errorSyntax) { BindValueKind valueKind; ExpressionSyntax value; IsInitializerRefKindValid(initializer, initializer, refKind, diagnostics, out valueKind, out value); // The return value isn't important here; we just want the diagnostics and the BindValueKind return BindInferredVariableInitializer(diagnostics, value, valueKind, errorSyntax); } // The location where the error is reported might not be the initializer. protected BoundExpression BindInferredVariableInitializer(BindingDiagnosticBag diagnostics, ExpressionSyntax initializer, BindValueKind valueKind, CSharpSyntaxNode errorSyntax) { if (initializer == null) { if (!errorSyntax.HasErrors) { Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableWithNoInitializer, errorSyntax); } return null; } if (initializer.Kind() == SyntaxKind.ArrayInitializerExpression) { var result = BindUnexpectedArrayInitializer((InitializerExpressionSyntax)initializer, diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableAssignedArrayInitializer, errorSyntax); return CheckValue(result, valueKind, diagnostics); } BoundExpression value = BindValue(initializer, diagnostics, valueKind); BoundExpression expression = value.Kind is BoundKind.UnboundLambda or BoundKind.MethodGroup ? BindToInferredDelegateType(value, diagnostics) : BindToNaturalType(value, diagnostics); // Certain expressions (null literals, method groups and anonymous functions) have no type of // their own and therefore cannot be the initializer of an implicitly typed local. if (!expression.HasAnyErrors && !expression.HasExpressionType()) { // Cannot assign {0} to an implicitly-typed local variable Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, errorSyntax, expression.Display); } return expression; } private static bool IsInitializerRefKindValid( EqualsValueClauseSyntax initializer, CSharpSyntaxNode node, RefKind variableRefKind, BindingDiagnosticBag diagnostics, out BindValueKind valueKind, out ExpressionSyntax value) { RefKind expressionRefKind = RefKind.None; value = initializer?.Value.CheckAndUnwrapRefExpression(diagnostics, out expressionRefKind); if (variableRefKind == RefKind.None) { valueKind = BindValueKind.RValue; if (expressionRefKind == RefKind.Ref) { Error(diagnostics, ErrorCode.ERR_InitializeByValueVariableWithReference, node); return false; } } else { valueKind = variableRefKind == RefKind.RefReadOnly ? BindValueKind.ReadonlyRef : BindValueKind.RefOrOut; if (initializer == null) { Error(diagnostics, ErrorCode.ERR_ByReferenceVariableMustBeInitialized, node); return false; } else if (expressionRefKind != RefKind.Ref) { Error(diagnostics, ErrorCode.ERR_InitializeByReferenceVariableWithValue, node); return false; } } return true; } protected BoundLocalDeclaration BindVariableDeclaration( LocalDeclarationKind kind, bool isVar, VariableDeclaratorSyntax declarator, TypeSyntax typeSyntax, TypeWithAnnotations declTypeOpt, AliasSymbol aliasOpt, BindingDiagnosticBag diagnostics, bool includeBoundType, CSharpSyntaxNode associatedSyntaxNode = null) { Debug.Assert(declarator != null); return BindVariableDeclaration(LocateDeclaredVariableSymbol(declarator, typeSyntax, kind), kind, isVar, declarator, typeSyntax, declTypeOpt, aliasOpt, diagnostics, includeBoundType, associatedSyntaxNode); } protected BoundLocalDeclaration BindVariableDeclaration( SourceLocalSymbol localSymbol, LocalDeclarationKind kind, bool isVar, VariableDeclaratorSyntax declarator, TypeSyntax typeSyntax, TypeWithAnnotations declTypeOpt, AliasSymbol aliasOpt, BindingDiagnosticBag diagnostics, bool includeBoundType, CSharpSyntaxNode associatedSyntaxNode = null) { Debug.Assert(declarator != null); Debug.Assert(declTypeOpt.HasType || isVar); Debug.Assert(typeSyntax != null); var localDiagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, diagnostics.AccumulatesDependencies); // if we are not given desired syntax, we use declarator associatedSyntaxNode = associatedSyntaxNode ?? declarator; // Check for variable declaration errors. // Use the binder that owns the scope for the local because this (the current) binder // might own nested scope. bool nameConflict = localSymbol.ScopeBinder.ValidateDeclarationNameConflictsInScope(localSymbol, diagnostics); bool hasErrors = false; if (localSymbol.RefKind != RefKind.None) { CheckRefLocalInAsyncOrIteratorMethod(localSymbol.IdentifierToken, diagnostics); } EqualsValueClauseSyntax equalsClauseSyntax = declarator.Initializer; BindValueKind valueKind; ExpressionSyntax value; if (!IsInitializerRefKindValid(equalsClauseSyntax, declarator, localSymbol.RefKind, diagnostics, out valueKind, out value)) { hasErrors = true; } BoundExpression initializerOpt; if (isVar) { aliasOpt = null; initializerOpt = BindInferredVariableInitializer(diagnostics, value, valueKind, declarator); // If we got a good result then swap the inferred type for the "var" TypeSymbol initializerType = initializerOpt?.Type; if ((object)initializerType != null) { declTypeOpt = TypeWithAnnotations.Create(initializerType); if (declTypeOpt.IsVoidType()) { Error(localDiagnostics, ErrorCode.ERR_ImplicitlyTypedVariableAssignedBadValue, declarator, declTypeOpt.Type); declTypeOpt = TypeWithAnnotations.Create(CreateErrorType("var")); hasErrors = true; } if (!declTypeOpt.Type.IsErrorType()) { if (declTypeOpt.IsStatic) { Error(localDiagnostics, ErrorCode.ERR_VarDeclIsStaticClass, typeSyntax, initializerType); hasErrors = true; } } } else { declTypeOpt = TypeWithAnnotations.Create(CreateErrorType("var")); hasErrors = true; } } else { if (ReferenceEquals(equalsClauseSyntax, null)) { initializerOpt = null; } else { // Basically inlined BindVariableInitializer, but with conversion optional. initializerOpt = BindPossibleArrayInitializer(value, declTypeOpt.Type, valueKind, diagnostics); if (kind != LocalDeclarationKind.FixedVariable) { // If this is for a fixed statement, we'll do our own conversion since there are some special cases. initializerOpt = GenerateConversionForAssignment( declTypeOpt.Type, initializerOpt, localDiagnostics, isRefAssignment: localSymbol.RefKind != RefKind.None); } } } Debug.Assert(declTypeOpt.HasType); if (kind == LocalDeclarationKind.FixedVariable) { // NOTE: this is an error, but it won't prevent further binding. if (isVar) { if (!hasErrors) { Error(localDiagnostics, ErrorCode.ERR_ImplicitlyTypedLocalCannotBeFixed, declarator); hasErrors = true; } } if (!declTypeOpt.Type.IsPointerType()) { if (!hasErrors) { Error(localDiagnostics, declTypeOpt.Type.IsFunctionPointer() ? ErrorCode.ERR_CannotUseFunctionPointerAsFixedLocal : ErrorCode.ERR_BadFixedInitType, declarator); hasErrors = true; } } else if (!IsValidFixedVariableInitializer(declTypeOpt.Type, localSymbol, ref initializerOpt, localDiagnostics)) { hasErrors = true; } } if (CheckRestrictedTypeInAsyncMethod(this.ContainingMemberOrLambda, declTypeOpt.Type, localDiagnostics, typeSyntax)) { hasErrors = true; } localSymbol.SetTypeWithAnnotations(declTypeOpt); if (initializerOpt != null) { var currentScope = LocalScopeDepth; localSymbol.SetValEscape(GetValEscape(initializerOpt, currentScope)); if (localSymbol.RefKind != RefKind.None) { localSymbol.SetRefEscape(GetRefEscape(initializerOpt, currentScope)); } } ImmutableArray<BoundExpression> arguments = BindDeclaratorArguments(declarator, localDiagnostics); if (kind == LocalDeclarationKind.FixedVariable || kind == LocalDeclarationKind.UsingVariable) { // CONSIDER: The error message is "you must provide an initializer in a fixed // CONSIDER: or using declaration". The error message could be targeted to // CONSIDER: the actual situation. "you must provide an initializer in a // CONSIDER: 'fixed' declaration." if (initializerOpt == null) { Error(localDiagnostics, ErrorCode.ERR_FixedMustInit, declarator); hasErrors = true; } } else if (kind == LocalDeclarationKind.Constant && initializerOpt != null && !localDiagnostics.HasAnyResolvedErrors()) { var constantValueDiagnostics = localSymbol.GetConstantValueDiagnostics(initializerOpt); diagnostics.AddRange(constantValueDiagnostics, allowMismatchInDependencyAccumulation: true); hasErrors = constantValueDiagnostics.Diagnostics.HasAnyErrors(); } diagnostics.AddRangeAndFree(localDiagnostics); BoundTypeExpression boundDeclType = null; if (includeBoundType) { var invalidDimensions = ArrayBuilder<BoundExpression>.GetInstance(); typeSyntax.VisitRankSpecifiers((rankSpecifier, args) => { bool _ = false; foreach (var expressionSyntax in rankSpecifier.Sizes) { var size = args.binder.BindArrayDimension(expressionSyntax, args.diagnostics, ref _); if (size != null) { args.invalidDimensions.Add(size); } } }, (binder: this, invalidDimensions: invalidDimensions, diagnostics: diagnostics)); boundDeclType = new BoundTypeExpression(typeSyntax, aliasOpt, dimensionsOpt: invalidDimensions.ToImmutableAndFree(), typeWithAnnotations: declTypeOpt); } return new BoundLocalDeclaration( syntax: associatedSyntaxNode, localSymbol: localSymbol, declaredTypeOpt: boundDeclType, initializerOpt: hasErrors ? BindToTypeForErrorRecovery(initializerOpt)?.WithHasErrors() : initializerOpt, argumentsOpt: arguments, inferredType: isVar, hasErrors: hasErrors | nameConflict); } protected bool CheckRefLocalInAsyncOrIteratorMethod(SyntaxToken identifierToken, BindingDiagnosticBag diagnostics) { if (IsInAsyncMethod()) { Error(diagnostics, ErrorCode.ERR_BadAsyncLocalType, identifierToken); return true; } else if (IsDirectlyInIterator) { Error(diagnostics, ErrorCode.ERR_BadIteratorLocalType, identifierToken); return true; } return false; } internal ImmutableArray<BoundExpression> BindDeclaratorArguments(VariableDeclaratorSyntax declarator, BindingDiagnosticBag diagnostics) { // It is possible that we have a bracketed argument list, like "int x[];" or "int x[123];" // in a non-fixed-size-array declaration . This is a common error made by C++ programmers. // We have already given a good error at parse time telling the user to either make it "fixed" // or to move the brackets to the type. However, we should still do semantic analysis of // the arguments, so that errors in them are discovered, hovering over them in the IDE // gives good results, and so on. var arguments = default(ImmutableArray<BoundExpression>); if (declarator.ArgumentList != null) { AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance(); BindArgumentsAndNames(declarator.ArgumentList, diagnostics, analyzedArguments); arguments = BuildArgumentsForErrorRecovery(analyzedArguments); analyzedArguments.Free(); } return arguments; } private SourceLocalSymbol LocateDeclaredVariableSymbol(VariableDeclaratorSyntax declarator, TypeSyntax typeSyntax, LocalDeclarationKind outerKind) { LocalDeclarationKind kind = outerKind == LocalDeclarationKind.UsingVariable ? LocalDeclarationKind.UsingVariable : LocalDeclarationKind.RegularVariable; return LocateDeclaredVariableSymbol(declarator.Identifier, typeSyntax, declarator.Initializer, kind); } private SourceLocalSymbol LocateDeclaredVariableSymbol(SyntaxToken identifier, TypeSyntax typeSyntax, EqualsValueClauseSyntax equalsValue, LocalDeclarationKind kind) { SourceLocalSymbol localSymbol = this.LookupLocal(identifier); // In error scenarios with misplaced code, it is possible we can't bind the local declaration. // This occurs through the semantic model. In that case concoct a plausible result. if ((object)localSymbol == null) { localSymbol = SourceLocalSymbol.MakeLocal( ContainingMemberOrLambda, this, false, // do not allow ref typeSyntax, identifier, kind, equalsValue); } return localSymbol; } private bool IsValidFixedVariableInitializer(TypeSymbol declType, SourceLocalSymbol localSymbol, ref BoundExpression initializerOpt, BindingDiagnosticBag diagnostics) { Debug.Assert(!ReferenceEquals(declType, null)); Debug.Assert(declType.IsPointerType()); if (initializerOpt?.HasAnyErrors != false) { return false; } TypeSymbol initializerType = initializerOpt.Type; SyntaxNode initializerSyntax = initializerOpt.Syntax; if ((object)initializerType == null) { Error(diagnostics, ErrorCode.ERR_ExprCannotBeFixed, initializerSyntax); return false; } TypeSymbol elementType; bool hasErrors = false; MethodSymbol fixedPatternMethod = null; switch (initializerOpt.Kind) { case BoundKind.AddressOfOperator: elementType = ((BoundAddressOfOperator)initializerOpt).Operand.Type; break; case BoundKind.FieldAccess: var fa = (BoundFieldAccess)initializerOpt; if (fa.FieldSymbol.IsFixedSizeBuffer) { elementType = ((PointerTypeSymbol)fa.Type).PointedAtType; break; } goto default; default: // fixed (T* variable = <expr>) ... // check for arrays if (initializerType.IsArray()) { // See ExpressionBinder::BindPtrToArray (though most of that functionality is now in LocalRewriter). elementType = ((ArrayTypeSymbol)initializerType).ElementType; break; } // check for a special ref-returning method var additionalDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); fixedPatternMethod = GetFixedPatternMethodOpt(initializerOpt, additionalDiagnostics); // check for String // NOTE: We will allow the pattern method to take precedence, but only if it is an instance member of System.String if (initializerType.SpecialType == SpecialType.System_String && ((object)fixedPatternMethod == null || fixedPatternMethod.ContainingType.SpecialType != SpecialType.System_String)) { fixedPatternMethod = null; elementType = this.GetSpecialType(SpecialType.System_Char, diagnostics, initializerSyntax); additionalDiagnostics.Free(); break; } // if the feature was enabled, but something went wrong with the method, report that, otherwise don't. // If feature is not enabled, additional errors would be just noise. bool extensibleFixedEnabled = ((CSharpParseOptions)initializerOpt.SyntaxTree.Options)?.IsFeatureEnabled(MessageID.IDS_FeatureExtensibleFixedStatement) != false; if (extensibleFixedEnabled) { diagnostics.AddRange(additionalDiagnostics); } additionalDiagnostics.Free(); if ((object)fixedPatternMethod != null) { elementType = fixedPatternMethod.ReturnType; CheckFeatureAvailability(initializerOpt.Syntax, MessageID.IDS_FeatureExtensibleFixedStatement, diagnostics); break; } else { Error(diagnostics, ErrorCode.ERR_ExprCannotBeFixed, initializerSyntax); return false; } } if (CheckManagedAddr(Compilation, elementType, initializerSyntax.Location, diagnostics)) { hasErrors = true; } initializerOpt = BindToNaturalType(initializerOpt, diagnostics, reportNoTargetType: false); initializerOpt = GetFixedLocalCollectionInitializer(initializerOpt, elementType, declType, fixedPatternMethod, hasErrors, diagnostics); return true; } private MethodSymbol GetFixedPatternMethodOpt(BoundExpression initializer, BindingDiagnosticBag additionalDiagnostics) { if (initializer.Type.IsVoidType()) { return null; } const string methodName = "GetPinnableReference"; var result = PerformPatternMethodLookup(initializer, methodName, initializer.Syntax, additionalDiagnostics, out var patternMethodSymbol); if (patternMethodSymbol is null) { return null; } if (HasOptionalOrVariableParameters(patternMethodSymbol) || patternMethodSymbol.ReturnsVoid || !patternMethodSymbol.RefKind.IsManagedReference() || !(patternMethodSymbol.ParameterCount == 0 || patternMethodSymbol.IsStatic && patternMethodSymbol.ParameterCount == 1)) { // the method does not fit the pattern additionalDiagnostics.Add(ErrorCode.WRN_PatternBadSignature, initializer.Syntax.Location, initializer.Type, "fixed", patternMethodSymbol); return null; } return patternMethodSymbol; } /// <summary> /// Wrap the initializer in a BoundFixedLocalCollectionInitializer so that the rewriter will have the /// information it needs (e.g. conversions, helper methods). /// </summary> private BoundExpression GetFixedLocalCollectionInitializer( BoundExpression initializer, TypeSymbol elementType, TypeSymbol declType, MethodSymbol patternMethodOpt, bool hasErrors, BindingDiagnosticBag diagnostics) { Debug.Assert(initializer != null); SyntaxNode initializerSyntax = initializer.Syntax; TypeSymbol pointerType = new PointerTypeSymbol(TypeWithAnnotations.Create(elementType)); CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); Conversion elementConversion = this.Conversions.ClassifyConversionFromType(pointerType, declType, ref useSiteInfo); diagnostics.Add(initializerSyntax, useSiteInfo); if (!elementConversion.IsValid || !elementConversion.IsImplicit) { GenerateImplicitConversionError(diagnostics, this.Compilation, initializerSyntax, elementConversion, pointerType, declType); hasErrors = true; } return new BoundFixedLocalCollectionInitializer( initializerSyntax, pointerType, elementConversion, initializer, patternMethodOpt, declType, hasErrors); } private BoundExpression BindAssignment(AssignmentExpressionSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); Debug.Assert(node.Left != null); Debug.Assert(node.Right != null); node.Left.CheckDeconstructionCompatibleArgument(diagnostics); if (node.Left.Kind() == SyntaxKind.TupleExpression || node.Left.Kind() == SyntaxKind.DeclarationExpression) { return BindDeconstruction(node, diagnostics); } BindValueKind lhsKind; BindValueKind rhsKind; ExpressionSyntax rhsExpr; bool isRef = false; if (node.Right.Kind() == SyntaxKind.RefExpression) { isRef = true; lhsKind = BindValueKind.RefAssignable; rhsKind = BindValueKind.RefersToLocation; rhsExpr = ((RefExpressionSyntax)node.Right).Expression; } else { lhsKind = BindValueKind.Assignable; rhsKind = BindValueKind.RValue; rhsExpr = node.Right; } var op1 = BindValue(node.Left, diagnostics, lhsKind); ReportSuppressionIfNeeded(op1, diagnostics); var lhsRefKind = RefKind.None; // If the LHS is a ref (not ref-readonly), the rhs // must also be value-assignable if (lhsKind == BindValueKind.RefAssignable && !op1.HasErrors) { // We should now know that op1 is a valid lvalue lhsRefKind = op1.GetRefKind(); if (lhsRefKind == RefKind.Ref || lhsRefKind == RefKind.Out) { rhsKind |= BindValueKind.Assignable; } } var op2 = BindValue(rhsExpr, diagnostics, rhsKind); if (op1.Kind == BoundKind.DiscardExpression) { op2 = BindToNaturalType(op2, diagnostics); op1 = InferTypeForDiscardAssignment((BoundDiscardExpression)op1, op2, diagnostics); } return BindAssignment(node, op1, op2, isRef, diagnostics); } private BoundExpression InferTypeForDiscardAssignment(BoundDiscardExpression op1, BoundExpression op2, BindingDiagnosticBag diagnostics) { var inferredType = op2.Type; if ((object)inferredType == null) { return op1.FailInference(this, diagnostics); } if (inferredType.IsVoidType()) { diagnostics.Add(ErrorCode.ERR_VoidAssignment, op1.Syntax.Location); } return op1.SetInferredTypeWithAnnotations(TypeWithAnnotations.Create(inferredType)); } private BoundAssignmentOperator BindAssignment( SyntaxNode node, BoundExpression op1, BoundExpression op2, bool isRef, BindingDiagnosticBag diagnostics) { Debug.Assert(op1 != null); Debug.Assert(op2 != null); bool hasErrors = op1.HasAnyErrors || op2.HasAnyErrors; if (!op1.HasAnyErrors) { // Build bound conversion. The node might not be used if this is a dynamic conversion // but diagnostics should be reported anyways. var conversion = GenerateConversionForAssignment(op1.Type, op2, diagnostics, isRefAssignment: isRef); // If the result is a dynamic assignment operation (SetMember or SetIndex), // don't generate the boxing conversion to the dynamic type. // Leave the values as they are, and deal with the conversions at runtime. if (op1.Kind != BoundKind.DynamicIndexerAccess && op1.Kind != BoundKind.DynamicMemberAccess && op1.Kind != BoundKind.DynamicObjectInitializerMember) { op2 = conversion; } else { op2 = BindToNaturalType(op2, diagnostics); } if (isRef) { var leftEscape = GetRefEscape(op1, LocalScopeDepth); var rightEscape = GetRefEscape(op2, LocalScopeDepth); if (leftEscape < rightEscape) { Error(diagnostics, ErrorCode.ERR_RefAssignNarrower, node, op1.ExpressionSymbol.Name, op2.Syntax); op2 = ToBadExpression(op2); } } if (op1.Type.IsRefLikeType) { var leftEscape = GetValEscape(op1, LocalScopeDepth); op2 = ValidateEscape(op2, leftEscape, isByRef: false, diagnostics); } } else { op2 = BindToTypeForErrorRecovery(op2); } TypeSymbol type; if ((op1.Kind == BoundKind.EventAccess) && ((BoundEventAccess)op1).EventSymbol.IsWindowsRuntimeEvent) { // Event assignment is a call to void WindowsRuntimeMarshal.AddEventHandler<T>(). type = this.GetSpecialType(SpecialType.System_Void, diagnostics, node); } else { type = op1.Type; } return new BoundAssignmentOperator(node, op1, op2, isRef, type, hasErrors); } private static PropertySymbol GetPropertySymbol(BoundExpression expr, out BoundExpression receiver, out SyntaxNode propertySyntax) { PropertySymbol propertySymbol; switch (expr.Kind) { case BoundKind.PropertyAccess: { var propertyAccess = (BoundPropertyAccess)expr; receiver = propertyAccess.ReceiverOpt; propertySymbol = propertyAccess.PropertySymbol; } break; case BoundKind.IndexerAccess: { var indexerAccess = (BoundIndexerAccess)expr; receiver = indexerAccess.ReceiverOpt; propertySymbol = indexerAccess.Indexer; } break; case BoundKind.IndexOrRangePatternIndexerAccess: { var patternIndexer = (BoundIndexOrRangePatternIndexerAccess)expr; receiver = patternIndexer.Receiver; propertySymbol = (PropertySymbol)patternIndexer.PatternSymbol; } break; default: receiver = null; propertySymbol = null; propertySyntax = null; return null; } var syntax = expr.Syntax; switch (syntax.Kind()) { case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: propertySyntax = ((MemberAccessExpressionSyntax)syntax).Name; break; case SyntaxKind.IdentifierName: propertySyntax = syntax; break; case SyntaxKind.ElementAccessExpression: propertySyntax = ((ElementAccessExpressionSyntax)syntax).ArgumentList; break; default: // Other syntax types, such as QualifiedName, // might occur in invalid code. propertySyntax = syntax; break; } return propertySymbol; } private static SyntaxNode GetEventName(BoundEventAccess expr) { SyntaxNode syntax = expr.Syntax; switch (syntax.Kind()) { case SyntaxKind.SimpleMemberAccessExpression: case SyntaxKind.PointerMemberAccessExpression: return ((MemberAccessExpressionSyntax)syntax).Name; case SyntaxKind.QualifiedName: // This case is reachable only through SemanticModel return ((QualifiedNameSyntax)syntax).Right; case SyntaxKind.IdentifierName: return syntax; case SyntaxKind.MemberBindingExpression: return ((MemberBindingExpressionSyntax)syntax).Name; default: throw ExceptionUtilities.UnexpectedValue(syntax.Kind()); } } /// <summary> /// There are two BadEventUsage error codes and this method decides which one should /// be used for a given event. /// </summary> private DiagnosticInfo GetBadEventUsageDiagnosticInfo(EventSymbol eventSymbol) { var leastOverridden = (EventSymbol)eventSymbol.GetLeastOverriddenMember(this.ContainingType); return leastOverridden.HasAssociatedField ? new CSDiagnosticInfo(ErrorCode.ERR_BadEventUsage, leastOverridden, leastOverridden.ContainingType) : new CSDiagnosticInfo(ErrorCode.ERR_BadEventUsageNoField, leastOverridden); } internal static bool AccessingAutoPropertyFromConstructor(BoundPropertyAccess propertyAccess, Symbol fromMember) { return AccessingAutoPropertyFromConstructor(propertyAccess.ReceiverOpt, propertyAccess.PropertySymbol, fromMember); } private static bool AccessingAutoPropertyFromConstructor(BoundExpression receiver, PropertySymbol propertySymbol, Symbol fromMember) { if (!propertySymbol.IsDefinition && propertySymbol.ContainingType.Equals(propertySymbol.ContainingType.OriginalDefinition, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { propertySymbol = propertySymbol.OriginalDefinition; } var sourceProperty = propertySymbol as SourcePropertySymbolBase; var propertyIsStatic = propertySymbol.IsStatic; return (object)sourceProperty != null && sourceProperty.IsAutoPropertyWithGetAccessor && TypeSymbol.Equals(sourceProperty.ContainingType, fromMember.ContainingType, TypeCompareKind.ConsiderEverything2) && IsConstructorOrField(fromMember, isStatic: propertyIsStatic) && (propertyIsStatic || receiver.Kind == BoundKind.ThisReference); } private static bool IsConstructorOrField(Symbol member, bool isStatic) { return (member as MethodSymbol)?.MethodKind == (isStatic ? MethodKind.StaticConstructor : MethodKind.Constructor) || (member as FieldSymbol)?.IsStatic == isStatic; } private TypeSymbol GetAccessThroughType(BoundExpression receiver) { if (receiver == null) { return this.ContainingType; } else if (receiver.Kind == BoundKind.BaseReference) { // Allow protected access to members defined // in base classes. See spec section 3.5.3. return null; } else { Debug.Assert((object)receiver.Type != null); return receiver.Type; } } private BoundExpression BindPossibleArrayInitializer( ExpressionSyntax node, TypeSymbol destinationType, BindValueKind valueKind, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); if (node.Kind() != SyntaxKind.ArrayInitializerExpression) { return BindValue(node, diagnostics, valueKind); } BoundExpression result; if (destinationType.Kind == SymbolKind.ArrayType) { result = BindArrayCreationWithInitializer(diagnostics, null, (InitializerExpressionSyntax)node, (ArrayTypeSymbol)destinationType, ImmutableArray<BoundExpression>.Empty); } else { result = BindUnexpectedArrayInitializer((InitializerExpressionSyntax)node, diagnostics, ErrorCode.ERR_ArrayInitToNonArrayType); } return CheckValue(result, valueKind, diagnostics); } protected virtual SourceLocalSymbol LookupLocal(SyntaxToken nameToken) { return Next.LookupLocal(nameToken); } protected virtual LocalFunctionSymbol LookupLocalFunction(SyntaxToken nameToken) { return Next.LookupLocalFunction(nameToken); } /// <summary> /// Returns a value that tells how many local scopes are visible, including the current. /// I.E. outside of any method will be 0 /// immediately inside a method - 1 /// </summary> internal virtual uint LocalScopeDepth => Next.LocalScopeDepth; internal virtual BoundBlock BindEmbeddedBlock(BlockSyntax node, BindingDiagnosticBag diagnostics) { return BindBlock(node, diagnostics); } private BoundBlock BindBlock(BlockSyntax node, BindingDiagnosticBag diagnostics) { if (node.AttributeLists.Count > 0) { Error(diagnostics, ErrorCode.ERR_AttributesNotAllowed, node.AttributeLists[0]); } var binder = GetBinder(node); Debug.Assert(binder != null); return binder.BindBlockParts(node, diagnostics); } private BoundBlock BindBlockParts(BlockSyntax node, BindingDiagnosticBag diagnostics) { var syntaxStatements = node.Statements; int nStatements = syntaxStatements.Count; ArrayBuilder<BoundStatement> boundStatements = ArrayBuilder<BoundStatement>.GetInstance(nStatements); for (int i = 0; i < nStatements; i++) { var boundStatement = BindStatement(syntaxStatements[i], diagnostics); boundStatements.Add(boundStatement); } return FinishBindBlockParts(node, boundStatements.ToImmutableAndFree(), diagnostics); } private BoundBlock FinishBindBlockParts(CSharpSyntaxNode node, ImmutableArray<BoundStatement> boundStatements, BindingDiagnosticBag diagnostics) { ImmutableArray<LocalSymbol> locals = GetDeclaredLocalsForScope(node); if (IsDirectlyInIterator) { var method = ContainingMemberOrLambda as MethodSymbol; if ((object)method != null) { method.IteratorElementTypeWithAnnotations = GetIteratorElementType(); } else { Debug.Assert(diagnostics.DiagnosticBag is null || !diagnostics.DiagnosticBag.IsEmptyWithoutResolution); } } return new BoundBlock( node, locals, GetDeclaredLocalFunctionsForScope(node), boundStatements); } internal BoundExpression GenerateConversionForAssignment(TypeSymbol targetType, BoundExpression expression, BindingDiagnosticBag diagnostics, bool isDefaultParameter = false, bool isRefAssignment = false) { Debug.Assert((object)targetType != null); Debug.Assert(expression != null); // We wish to avoid "cascading" errors, so if the expression we are // attempting to convert to a type had errors, suppress additional // diagnostics. However, if the expression // with errors is an unbound lambda then the errors are almost certainly // syntax errors. For error recovery analysis purposes we wish to bind // error lambdas like "Action<int> f = x=>{ x. };" because IntelliSense // needs to know that x is of type int. if (expression.HasAnyErrors && expression.Kind != BoundKind.UnboundLambda) { diagnostics = BindingDiagnosticBag.Discarded; } CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var conversion = this.Conversions.ClassifyConversionFromExpression(expression, targetType, ref useSiteInfo); diagnostics.Add(expression.Syntax, useSiteInfo); if (isRefAssignment) { if (conversion.Kind != ConversionKind.Identity) { Error(diagnostics, ErrorCode.ERR_RefAssignmentMustHaveIdentityConversion, expression.Syntax, targetType); } else { return expression; } } else if (!conversion.IsImplicit || !conversion.IsValid) { // We suppress conversion errors on default parameters; eg, // if someone says "void M(string s = 123) {}". We will report // a special error in the default parameter binder. if (!isDefaultParameter) { GenerateImplicitConversionError(diagnostics, expression.Syntax, conversion, expression, targetType); } // Suppress any additional diagnostics diagnostics = BindingDiagnosticBag.Discarded; } return CreateConversion(expression.Syntax, expression, conversion, isCast: false, conversionGroupOpt: null, targetType, diagnostics); } #nullable enable internal void GenerateAnonymousFunctionConversionError(BindingDiagnosticBag diagnostics, SyntaxNode syntax, UnboundLambda anonymousFunction, TypeSymbol targetType) { Debug.Assert((object)targetType != null); Debug.Assert(anonymousFunction != null); // Is the target type simply bad? // If the target type is an error then we've already reported a diagnostic. Don't bother // reporting the conversion error. if (targetType.IsErrorType()) { return; } // CONSIDER: Instead of computing this again, cache the reason why the conversion failed in // CONSIDER: the Conversion result, and simply report that. var reason = Conversions.IsAnonymousFunctionCompatibleWithType(anonymousFunction, targetType); // It is possible that the conversion from lambda to delegate is just fine, and // that we ended up here because the target type, though itself is not an error // type, contains a type argument which is an error type. For example, converting // (Goo goo)=>{} to Action<Goo> is a perfectly legal conversion even if Goo is undefined! // In that case we have already reported an error that Goo is undefined, so just bail out. if (reason == LambdaConversionResult.Success) { return; } var id = anonymousFunction.MessageID.Localize(); if (reason == LambdaConversionResult.BadTargetType) { if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, targetType, node: syntax)) { return; } // Cannot convert {0} to type '{1}' because it is not a delegate type Error(diagnostics, ErrorCode.ERR_AnonMethToNonDel, syntax, id, targetType); return; } if (reason == LambdaConversionResult.ExpressionTreeMustHaveDelegateTypeArgument) { Debug.Assert(targetType.IsExpressionTree()); Error(diagnostics, ErrorCode.ERR_ExpressionTreeMustHaveDelegate, syntax, ((NamedTypeSymbol)targetType).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type); return; } if (reason == LambdaConversionResult.ExpressionTreeFromAnonymousMethod) { Debug.Assert(targetType.IsGenericOrNonGenericExpressionType(out _)); Error(diagnostics, ErrorCode.ERR_AnonymousMethodToExpressionTree, syntax); return; } if (reason == LambdaConversionResult.MismatchedReturnType) { Error(diagnostics, ErrorCode.ERR_CantConvAnonMethReturnType, syntax, id, targetType); return; } // At this point we know that we have either a delegate type or an expression type for the target. // The target type is a valid delegate or expression tree type. Is there something wrong with the // parameter list? // First off, is there a parameter list at all? if (reason == LambdaConversionResult.MissingSignatureWithOutParameter) { // COMPATIBILITY: The C# 4 compiler produces two errors for: // // delegate void D (out int x); // ... // D d = delegate {}; // // error CS1676: Parameter 1 must be declared with the 'out' keyword // error CS1688: Cannot convert anonymous method block without a parameter list // to delegate type 'D' because it has one or more out parameters // // This seems redundant, (because there is no "parameter 1" in the source code) // and unnecessary. I propose that we eliminate the first error. Error(diagnostics, ErrorCode.ERR_CantConvAnonMethNoParams, syntax, targetType); return; } var delegateType = targetType.GetDelegateType(); Debug.Assert(delegateType is not null); // There is a parameter list. Does it have the right number of elements? if (reason == LambdaConversionResult.BadParameterCount) { // Delegate '{0}' does not take {1} arguments Error(diagnostics, ErrorCode.ERR_BadDelArgCount, syntax, delegateType, anonymousFunction.ParameterCount); return; } // The parameter list exists and had the right number of parameters. Were any of its types bad? // If any parameter type of the lambda is an error type then suppress // further errors. We've already reported errors on the bad type. if (anonymousFunction.HasExplicitlyTypedParameterList) { for (int i = 0; i < anonymousFunction.ParameterCount; ++i) { if (anonymousFunction.ParameterType(i).IsErrorType()) { return; } } } // The parameter list exists and had the right number of parameters. Were any of its types // mismatched with the delegate parameter types? // The simplest possible case is (x, y, z)=>whatever where the target type has a ref or out parameter. var delegateParameters = delegateType.DelegateParameters(); if (reason == LambdaConversionResult.RefInImplicitlyTypedLambda) { for (int i = 0; i < anonymousFunction.ParameterCount; ++i) { var delegateRefKind = delegateParameters[i].RefKind; if (delegateRefKind != RefKind.None) { // Parameter {0} must be declared with the '{1}' keyword Error(diagnostics, ErrorCode.ERR_BadParamRef, anonymousFunction.ParameterLocation(i), i + 1, delegateRefKind.ToParameterDisplayString()); } } return; } // See the comments in IsAnonymousFunctionCompatibleWithDelegate for an explanation of this one. if (reason == LambdaConversionResult.StaticTypeInImplicitlyTypedLambda) { for (int i = 0; i < anonymousFunction.ParameterCount; ++i) { if (delegateParameters[i].TypeWithAnnotations.IsStatic) { // {0}: Static types cannot be used as parameter Error(diagnostics, ErrorFacts.GetStaticClassParameterCode(useWarning: false), anonymousFunction.ParameterLocation(i), delegateParameters[i].Type); } } return; } // Otherwise, there might be a more complex reason why the parameter types are mismatched. if (reason == LambdaConversionResult.MismatchedParameterType) { // Cannot convert {0} to type '{1}' because the parameter types do not match the delegate parameter types Error(diagnostics, ErrorCode.ERR_CantConvAnonMethParams, syntax, id, targetType); Debug.Assert(anonymousFunction.ParameterCount == delegateParameters.Length); for (int i = 0; i < anonymousFunction.ParameterCount; ++i) { var lambdaParameterType = anonymousFunction.ParameterType(i); if (lambdaParameterType.IsErrorType()) { continue; } var lambdaParameterLocation = anonymousFunction.ParameterLocation(i); var lambdaRefKind = anonymousFunction.RefKind(i); var delegateParameterType = delegateParameters[i].Type; var delegateRefKind = delegateParameters[i].RefKind; if (!lambdaParameterType.Equals(delegateParameterType, TypeCompareKind.AllIgnoreOptions)) { SymbolDistinguisher distinguisher = new SymbolDistinguisher(this.Compilation, lambdaParameterType, delegateParameterType); // Parameter {0} is declared as type '{1}{2}' but should be '{3}{4}' Error(diagnostics, ErrorCode.ERR_BadParamType, lambdaParameterLocation, i + 1, lambdaRefKind.ToParameterPrefix(), distinguisher.First, delegateRefKind.ToParameterPrefix(), distinguisher.Second); } else if (lambdaRefKind != delegateRefKind) { if (delegateRefKind == RefKind.None) { // Parameter {0} should not be declared with the '{1}' keyword Error(diagnostics, ErrorCode.ERR_BadParamExtraRef, lambdaParameterLocation, i + 1, lambdaRefKind.ToParameterDisplayString()); } else { // Parameter {0} must be declared with the '{1}' keyword Error(diagnostics, ErrorCode.ERR_BadParamRef, lambdaParameterLocation, i + 1, delegateRefKind.ToParameterDisplayString()); } } } return; } if (reason == LambdaConversionResult.BindingFailed) { var bindingResult = anonymousFunction.Bind(delegateType, isExpressionTree: false); Debug.Assert(ErrorFacts.PreventsSuccessfulDelegateConversion(bindingResult.Diagnostics.Diagnostics)); diagnostics.AddRange(bindingResult.Diagnostics); return; } // UNDONE: LambdaConversionResult.VoidExpressionLambdaMustBeStatementExpression: Debug.Assert(false, "Missing case in lambda conversion error reporting"); diagnostics.Add(ErrorCode.ERR_InternalError, syntax.Location); } #nullable disable protected static void GenerateImplicitConversionError(BindingDiagnosticBag diagnostics, CSharpCompilation compilation, SyntaxNode syntax, Conversion conversion, TypeSymbol sourceType, TypeSymbol targetType, ConstantValue sourceConstantValueOpt = null) { Debug.Assert(!conversion.IsImplicit || !conversion.IsValid); // If the either type is an error then an error has already been reported // for some aspect of the analysis of this expression. (For example, something like // "garbage g = null; short s = g;" -- we don't want to report that g is not // convertible to short because we've already reported that g does not have a good type. if (!sourceType.IsErrorType() && !targetType.IsErrorType()) { if (conversion.IsExplicit) { if (sourceType.SpecialType == SpecialType.System_Double && syntax.Kind() == SyntaxKind.NumericLiteralExpression && (targetType.SpecialType == SpecialType.System_Single || targetType.SpecialType == SpecialType.System_Decimal)) { Error(diagnostics, ErrorCode.ERR_LiteralDoubleCast, syntax, (targetType.SpecialType == SpecialType.System_Single) ? "F" : "M", targetType); } else if (conversion.Kind == ConversionKind.ExplicitNumeric && sourceConstantValueOpt != null && sourceConstantValueOpt != ConstantValue.Bad && ConversionsBase.HasImplicitConstantExpressionConversion(new BoundLiteral(syntax, ConstantValue.Bad, sourceType), targetType)) { // CLEVERNESS: By passing ConstantValue.Bad, we tell HasImplicitConstantExpressionConversion to ignore the constant // value and only consider the types. // If there would be an implicit constant conversion for a different constant of the same type // (i.e. one that's not out of range), then it's more helpful to report the range check failure // than to suggest inserting a cast. Error(diagnostics, ErrorCode.ERR_ConstOutOfRange, syntax, sourceConstantValueOpt.Value, targetType); } else { SymbolDistinguisher distinguisher = new SymbolDistinguisher(compilation, sourceType, targetType); Error(diagnostics, ErrorCode.ERR_NoImplicitConvCast, syntax, distinguisher.First, distinguisher.Second); } } else if (conversion.ResultKind == LookupResultKind.OverloadResolutionFailure) { Debug.Assert(conversion.IsUserDefined); ImmutableArray<MethodSymbol> originalUserDefinedConversions = conversion.OriginalUserDefinedConversions; if (originalUserDefinedConversions.Length > 1) { Error(diagnostics, ErrorCode.ERR_AmbigUDConv, syntax, originalUserDefinedConversions[0], originalUserDefinedConversions[1], sourceType, targetType); } else { Debug.Assert(originalUserDefinedConversions.Length == 0, "How can there be exactly one applicable user-defined conversion if the conversion doesn't exist?"); SymbolDistinguisher distinguisher = new SymbolDistinguisher(compilation, sourceType, targetType); Error(diagnostics, ErrorCode.ERR_NoImplicitConv, syntax, distinguisher.First, distinguisher.Second); } } else if (TypeSymbol.Equals(sourceType, targetType, TypeCompareKind.ConsiderEverything2)) { // This occurs for `void`, which cannot even convert to itself. Since SymbolDistinguisher // requires two distinct types, we preempt its use here. The diagnostic is strange, but correct. // Though this diagnostic tends to be a cascaded one, we cannot suppress it until // we have proven that it is always so. Error(diagnostics, ErrorCode.ERR_NoImplicitConv, syntax, sourceType, targetType); } else { SymbolDistinguisher distinguisher = new SymbolDistinguisher(compilation, sourceType, targetType); Error(diagnostics, ErrorCode.ERR_NoImplicitConv, syntax, distinguisher.First, distinguisher.Second); } } } protected void GenerateImplicitConversionError( BindingDiagnosticBag diagnostics, SyntaxNode syntax, Conversion conversion, BoundExpression operand, TypeSymbol targetType) { Debug.Assert(operand != null); Debug.Assert((object)targetType != null); if (targetType.TypeKind == TypeKind.Error) { return; } if (targetType.IsVoidType()) { Error(diagnostics, ErrorCode.ERR_NoImplicitConv, syntax, operand.Display, targetType); return; } switch (operand.Kind) { case BoundKind.BadExpression: { return; } case BoundKind.UnboundLambda: { GenerateAnonymousFunctionConversionError(diagnostics, syntax, (UnboundLambda)operand, targetType); return; } case BoundKind.TupleLiteral: { var tuple = (BoundTupleLiteral)operand; var targetElementTypes = default(ImmutableArray<TypeWithAnnotations>); // If target is a tuple or compatible type with the same number of elements, // report errors for tuple arguments that failed to convert, which would be more useful. if (targetType.TryGetElementTypesWithAnnotationsIfTupleType(out targetElementTypes) && targetElementTypes.Length == tuple.Arguments.Length) { GenerateImplicitConversionErrorsForTupleLiteralArguments(diagnostics, tuple.Arguments, targetElementTypes); return; } // target is not compatible with source and source does not have a type if ((object)tuple.Type == null) { Error(diagnostics, ErrorCode.ERR_ConversionNotTupleCompatible, syntax, tuple.Arguments.Length, targetType); return; } // Otherwise it is just a regular conversion failure from T1 to T2. break; } case BoundKind.MethodGroup: { reportMethodGroupErrors((BoundMethodGroup)operand, fromAddressOf: false); return; } case BoundKind.UnconvertedAddressOfOperator: { reportMethodGroupErrors(((BoundUnconvertedAddressOfOperator)operand).Operand, fromAddressOf: true); return; } case BoundKind.Literal: { if (operand.IsLiteralNull()) { if (targetType.TypeKind == TypeKind.TypeParameter) { Error(diagnostics, ErrorCode.ERR_TypeVarCantBeNull, syntax, targetType); return; } if (targetType.IsValueType) { Error(diagnostics, ErrorCode.ERR_ValueCantBeNull, syntax, targetType); return; } } break; } case BoundKind.StackAllocArrayCreation: { var stackAllocExpression = (BoundStackAllocArrayCreation)operand; Error(diagnostics, ErrorCode.ERR_StackAllocConversionNotPossible, syntax, stackAllocExpression.ElementType, targetType); return; } case BoundKind.UnconvertedSwitchExpression: { var switchExpression = (BoundUnconvertedSwitchExpression)operand; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; bool reportedError = false; foreach (var arm in switchExpression.SwitchArms) { tryConversion(arm.Value, ref reportedError, ref discardedUseSiteInfo); } Debug.Assert(reportedError); return; } case BoundKind.AddressOfOperator when targetType.IsFunctionPointer(): { Error(diagnostics, ErrorCode.ERR_InvalidAddrOp, ((BoundAddressOfOperator)operand).Operand.Syntax); return; } case BoundKind.UnconvertedConditionalOperator: { var conditionalOperator = (BoundUnconvertedConditionalOperator)operand; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; bool reportedError = false; tryConversion(conditionalOperator.Consequence, ref reportedError, ref discardedUseSiteInfo); tryConversion(conditionalOperator.Alternative, ref reportedError, ref discardedUseSiteInfo); Debug.Assert(reportedError); return; } void tryConversion(BoundExpression expr, ref bool reportedError, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var conversion = this.Conversions.ClassifyImplicitConversionFromExpression(expr, targetType, ref useSiteInfo); if (!conversion.IsImplicit || !conversion.IsValid) { GenerateImplicitConversionError(diagnostics, expr.Syntax, conversion, expr, targetType); reportedError = true; } } } var sourceType = operand.Type; if ((object)sourceType != null) { GenerateImplicitConversionError(diagnostics, this.Compilation, syntax, conversion, sourceType, targetType, operand.ConstantValue); return; } Debug.Assert(operand.HasAnyErrors && operand.Kind != BoundKind.UnboundLambda, "Missing a case in implicit conversion error reporting"); void reportMethodGroupErrors(BoundMethodGroup methodGroup, bool fromAddressOf) { if (!Conversions.ReportDelegateOrFunctionPointerMethodGroupDiagnostics(this, methodGroup, targetType, diagnostics)) { var nodeForError = syntax; while (nodeForError.Kind() == SyntaxKind.ParenthesizedExpression) { nodeForError = ((ParenthesizedExpressionSyntax)nodeForError).Expression; } if (nodeForError.Kind() == SyntaxKind.SimpleMemberAccessExpression || nodeForError.Kind() == SyntaxKind.PointerMemberAccessExpression) { nodeForError = ((MemberAccessExpressionSyntax)nodeForError).Name; } var location = nodeForError.Location; if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, targetType, location)) { return; } ErrorCode errorCode; switch (targetType.TypeKind) { case TypeKind.FunctionPointer when fromAddressOf: errorCode = ErrorCode.ERR_MethFuncPtrMismatch; break; case TypeKind.FunctionPointer: Error(diagnostics, ErrorCode.ERR_MissingAddressOf, location); return; case TypeKind.Delegate when fromAddressOf: errorCode = ErrorCode.ERR_CannotConvertAddressOfToDelegate; break; case TypeKind.Delegate: errorCode = ErrorCode.ERR_MethDelegateMismatch; break; default: if (fromAddressOf) { errorCode = ErrorCode.ERR_AddressOfToNonFunctionPointer; } else if (targetType.SpecialType == SpecialType.System_Delegate) { Error(diagnostics, ErrorCode.ERR_CannotInferDelegateType, location); return; } else { errorCode = ErrorCode.ERR_MethGrpToNonDel; } break; } Error(diagnostics, errorCode, location, methodGroup.Name, targetType); } } } private void GenerateImplicitConversionErrorsForTupleLiteralArguments( BindingDiagnosticBag diagnostics, ImmutableArray<BoundExpression> tupleArguments, ImmutableArray<TypeWithAnnotations> targetElementTypes) { var argLength = tupleArguments.Length; // report all leaf elements of the tuple literal that failed to convert // NOTE: we are not responsible for reporting use site errors here, just the failed leaf conversions. // By the time we get here we have done analysis and know we have failed the cast in general, and diagnostics collected in the process is already in the bag. // The only thing left is to form a diagnostics about the actually failing conversion(s). // This whole method does not itself collect any usesite diagnostics. Its only purpose is to produce an error better than "conversion failed here" var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; for (int i = 0; i < targetElementTypes.Length; i++) { var argument = tupleArguments[i]; var targetElementType = targetElementTypes[i].Type; var elementConversion = Conversions.ClassifyImplicitConversionFromExpression(argument, targetElementType, ref discardedUseSiteInfo); if (!elementConversion.IsValid) { GenerateImplicitConversionError(diagnostics, argument.Syntax, elementConversion, argument, targetElementType); } } } private BoundStatement BindIfStatement(IfStatementSyntax node, BindingDiagnosticBag diagnostics) { var condition = BindBooleanExpression(node.Condition, diagnostics); var consequence = BindPossibleEmbeddedStatement(node.Statement, diagnostics); BoundStatement alternative = (node.Else == null) ? null : BindPossibleEmbeddedStatement(node.Else.Statement, diagnostics); BoundStatement result = new BoundIfStatement(node, condition, consequence, alternative); return result; } internal BoundExpression BindBooleanExpression(ExpressionSyntax node, BindingDiagnosticBag diagnostics) { // SPEC: // A boolean-expression is an expression that yields a result of type bool; // either directly or through application of operator true in certain // contexts as specified in the following. // // The controlling conditional expression of an if-statement, while-statement, // do-statement, or for-statement is a boolean-expression. The controlling // conditional expression of the ?: operator follows the same rules as a // boolean-expression, but for reasons of operator precedence is classified // as a conditional-or-expression. // // A boolean-expression is required to be implicitly convertible to bool // or of a type that implements operator true. If neither requirement // is satisfied, a binding-time error occurs. // // When a boolean expression cannot be implicitly converted to bool but does // implement operator true, then following evaluation of the expression, // the operator true implementation provided by that type is invoked // to produce a bool value. // // SPEC ERROR: The third paragraph above is obviously not correct; we need // SPEC ERROR: to do more than just check to see whether the type implements // SPEC ERROR: operator true. First off, the type could implement the operator // SPEC ERROR: several times: if it is a struct then it could implement it // SPEC ERROR: twice, to take both nullable and non-nullable arguments, and // SPEC ERROR: if it is a class or type parameter then it could have several // SPEC ERROR: implementations on its base classes or effective base classes. // SPEC ERROR: Second, the type of the argument could be S? where S implements // SPEC ERROR: operator true(S?); we want to look at S, not S?, when looking // SPEC ERROR: for applicable candidates. // // SPEC ERROR: Basically, the spec should say "use unary operator overload resolution // SPEC ERROR: to find the candidate set and choose a unique best operator true". var expr = BindValue(node, diagnostics, BindValueKind.RValue); var boolean = GetSpecialType(SpecialType.System_Boolean, diagnostics, node); if (expr.HasAnyErrors) { // The expression could not be bound. Insert a fake conversion // around it to bool and keep on going. // NOTE: no user-defined conversion candidates. return BoundConversion.Synthesized(node, BindToTypeForErrorRecovery(expr), Conversion.NoConversion, false, explicitCastInCode: false, conversionGroupOpt: null, ConstantValue.NotAvailable, boolean, hasErrors: true); } // Oddly enough, "if(dyn)" is bound not as a dynamic conversion to bool, but as a dynamic // invocation of operator true. if (expr.HasDynamicType()) { return new BoundUnaryOperator( node, UnaryOperatorKind.DynamicTrue, BindToNaturalType(expr, diagnostics), ConstantValue.NotAvailable, methodOpt: null, constrainedToTypeOpt: null, LookupResultKind.Viable, boolean) { WasCompilerGenerated = true }; } // Is the operand implicitly convertible to bool? CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); var conversion = this.Conversions.ClassifyConversionFromExpression(expr, boolean, ref useSiteInfo); diagnostics.Add(expr.Syntax, useSiteInfo); if (conversion.IsImplicit) { if (conversion.Kind == ConversionKind.Identity) { // Check to see if we're assigning a boolean literal in a place where an // equality check would be more conventional. // NOTE: Don't do this check unless the expression will be returned // without being wrapped in another bound node (i.e. identity conversion). if (expr.Kind == BoundKind.AssignmentOperator) { var assignment = (BoundAssignmentOperator)expr; if (assignment.Right.Kind == BoundKind.Literal && assignment.Right.ConstantValue.Discriminator == ConstantValueTypeDiscriminator.Boolean) { Error(diagnostics, ErrorCode.WRN_IncorrectBooleanAssg, assignment.Syntax); } } } return CreateConversion( syntax: expr.Syntax, source: expr, conversion: conversion, isCast: false, conversionGroupOpt: null, wasCompilerGenerated: true, destination: boolean, diagnostics: diagnostics); } // It was not. Does it implement operator true? expr = BindToNaturalType(expr, diagnostics); var best = this.UnaryOperatorOverloadResolution(UnaryOperatorKind.True, expr, node, diagnostics, out LookupResultKind resultKind, out ImmutableArray<MethodSymbol> originalUserDefinedOperators); if (!best.HasValue) { // No. Give a "not convertible to bool" error. Debug.Assert(resultKind == LookupResultKind.Empty, "How could overload resolution fail if a user-defined true operator was found?"); Debug.Assert(originalUserDefinedOperators.IsEmpty, "How could overload resolution fail if a user-defined true operator was found?"); GenerateImplicitConversionError(diagnostics, node, conversion, expr, boolean); return BoundConversion.Synthesized(node, expr, Conversion.NoConversion, false, explicitCastInCode: false, conversionGroupOpt: null, ConstantValue.NotAvailable, boolean, hasErrors: true); } UnaryOperatorSignature signature = best.Signature; BoundExpression resultOperand = CreateConversion( node, expr, best.Conversion, isCast: false, conversionGroupOpt: null, destination: best.Signature.OperandType, diagnostics: diagnostics); CheckConstraintLanguageVersionAndRuntimeSupportForOperator(node, signature.Method, signature.ConstrainedToTypeOpt, diagnostics); // Consider op_true to be compiler-generated so that it doesn't appear in the semantic model. // UNDONE: If we decide to expose the operator in the semantic model, we'll have to remove the // WasCompilerGenerated flag (and possibly suppress the symbol in specific APIs). return new BoundUnaryOperator(node, signature.Kind, resultOperand, ConstantValue.NotAvailable, signature.Method, signature.ConstrainedToTypeOpt, resultKind, originalUserDefinedOperators, signature.ReturnType) { WasCompilerGenerated = true }; } private BoundStatement BindSwitchStatement(SwitchStatementSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); Binder switchBinder = this.GetBinder(node); return switchBinder.BindSwitchStatementCore(node, switchBinder, diagnostics); } internal virtual BoundStatement BindSwitchStatementCore(SwitchStatementSyntax node, Binder originalBinder, BindingDiagnosticBag diagnostics) { return this.Next.BindSwitchStatementCore(node, originalBinder, diagnostics); } internal virtual void BindPatternSwitchLabelForInference(CasePatternSwitchLabelSyntax node, BindingDiagnosticBag diagnostics) { this.Next.BindPatternSwitchLabelForInference(node, diagnostics); } private BoundStatement BindWhile(WhileStatementSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); var loopBinder = this.GetBinder(node); Debug.Assert(loopBinder != null); return loopBinder.BindWhileParts(diagnostics, loopBinder); } internal virtual BoundWhileStatement BindWhileParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindWhileParts(diagnostics, originalBinder); } private BoundStatement BindDo(DoStatementSyntax node, BindingDiagnosticBag diagnostics) { var loopBinder = this.GetBinder(node); Debug.Assert(loopBinder != null); return loopBinder.BindDoParts(diagnostics, loopBinder); } internal virtual BoundDoStatement BindDoParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindDoParts(diagnostics, originalBinder); } internal BoundForStatement BindFor(ForStatementSyntax node, BindingDiagnosticBag diagnostics) { var loopBinder = this.GetBinder(node); Debug.Assert(loopBinder != null); return loopBinder.BindForParts(diagnostics, loopBinder); } internal virtual BoundForStatement BindForParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindForParts(diagnostics, originalBinder); } internal BoundStatement BindForOrUsingOrFixedDeclarations(VariableDeclarationSyntax nodeOpt, LocalDeclarationKind localKind, BindingDiagnosticBag diagnostics, out ImmutableArray<BoundLocalDeclaration> declarations) { if (nodeOpt == null) { declarations = ImmutableArray<BoundLocalDeclaration>.Empty; return null; } var typeSyntax = nodeOpt.Type; // Fixed and using variables are not allowed to be ref-like, but regular variables are if (localKind == LocalDeclarationKind.RegularVariable) { typeSyntax = typeSyntax.SkipRef(out _); } AliasSymbol alias; bool isVar; TypeWithAnnotations declType = BindTypeOrVarKeyword(typeSyntax, diagnostics, out isVar, out alias); Debug.Assert(declType.HasType || isVar); var variables = nodeOpt.Variables; int count = variables.Count; Debug.Assert(count > 0); if (isVar && count > 1) { // There are a number of ways in which a var decl can be illegal, but in these // cases we should report an error and then keep right on going with the inference. Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedVariableMultipleDeclarator, nodeOpt); } var declarationArray = new BoundLocalDeclaration[count]; for (int i = 0; i < count; i++) { var variableDeclarator = variables[i]; bool includeBoundType = i == 0; //To avoid duplicated expressions, only the first declaration should contain the bound type. var declaration = BindVariableDeclaration(localKind, isVar, variableDeclarator, typeSyntax, declType, alias, diagnostics, includeBoundType); declarationArray[i] = declaration; } declarations = declarationArray.AsImmutableOrNull(); return (count == 1) ? (BoundStatement)declarations[0] : new BoundMultipleLocalDeclarations(nodeOpt, declarations); } internal BoundStatement BindStatementExpressionList(SeparatedSyntaxList<ExpressionSyntax> statements, BindingDiagnosticBag diagnostics) { int count = statements.Count; if (count == 0) { return null; } else if (count == 1) { var syntax = statements[0]; return BindExpressionStatement(syntax, syntax, false, diagnostics); } else { var statementBuilder = ArrayBuilder<BoundStatement>.GetInstance(); for (int i = 0; i < count; i++) { var syntax = statements[i]; var statement = BindExpressionStatement(syntax, syntax, false, diagnostics); statementBuilder.Add(statement); } return BoundStatementList.Synthesized(statements.Node, statementBuilder.ToImmutableAndFree()); } } private BoundStatement BindForEach(CommonForEachStatementSyntax node, BindingDiagnosticBag diagnostics) { Binder loopBinder = this.GetBinder(node); return this.GetBinder(node.Expression).WrapWithVariablesIfAny(node.Expression, loopBinder.BindForEachParts(diagnostics, loopBinder)); } internal virtual BoundStatement BindForEachParts(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindForEachParts(diagnostics, originalBinder); } /// <summary> /// Like BindForEachParts, but only bind the deconstruction part of the foreach, for purpose of inferring the types of the declared locals. /// </summary> internal virtual BoundStatement BindForEachDeconstruction(BindingDiagnosticBag diagnostics, Binder originalBinder) { return this.Next.BindForEachDeconstruction(diagnostics, originalBinder); } private BoundStatement BindBreak(BreakStatementSyntax node, BindingDiagnosticBag diagnostics) { var target = this.BreakLabel; if ((object)target == null) { Error(diagnostics, ErrorCode.ERR_NoBreakOrCont, node); return new BoundBadStatement(node, ImmutableArray<BoundNode>.Empty, hasErrors: true); } return new BoundBreakStatement(node, target); } private BoundStatement BindContinue(ContinueStatementSyntax node, BindingDiagnosticBag diagnostics) { var target = this.ContinueLabel; if ((object)target == null) { Error(diagnostics, ErrorCode.ERR_NoBreakOrCont, node); return new BoundBadStatement(node, ImmutableArray<BoundNode>.Empty, hasErrors: true); } return new BoundContinueStatement(node, target); } private static SwitchBinder GetSwitchBinder(Binder binder) { SwitchBinder switchBinder = binder as SwitchBinder; while (binder != null && switchBinder == null) { binder = binder.Next; switchBinder = binder as SwitchBinder; } return switchBinder; } protected static bool IsInAsyncMethod(MethodSymbol method) { return (object)method != null && method.IsAsync; } protected bool IsInAsyncMethod() { return IsInAsyncMethod(this.ContainingMemberOrLambda as MethodSymbol); } protected bool IsEffectivelyTaskReturningAsyncMethod() { var symbol = this.ContainingMemberOrLambda; return symbol?.Kind == SymbolKind.Method && ((MethodSymbol)symbol).IsAsyncEffectivelyReturningTask(this.Compilation); } protected bool IsEffectivelyGenericTaskReturningAsyncMethod() { var symbol = this.ContainingMemberOrLambda; return symbol?.Kind == SymbolKind.Method && ((MethodSymbol)symbol).IsAsyncEffectivelyReturningGenericTask(this.Compilation); } protected bool IsIAsyncEnumerableOrIAsyncEnumeratorReturningAsyncMethod() { var symbol = this.ContainingMemberOrLambda; if (symbol?.Kind == SymbolKind.Method) { var method = (MethodSymbol)symbol; return method.IsAsyncReturningIAsyncEnumerable(this.Compilation) || method.IsAsyncReturningIAsyncEnumerator(this.Compilation); } return false; } protected virtual TypeSymbol GetCurrentReturnType(out RefKind refKind) { var symbol = this.ContainingMemberOrLambda as MethodSymbol; if ((object)symbol != null) { refKind = symbol.RefKind; TypeSymbol returnType = symbol.ReturnType; if ((object)returnType == LambdaSymbol.ReturnTypeIsBeingInferred) { return null; } return returnType; } refKind = RefKind.None; return null; } private BoundStatement BindReturn(ReturnStatementSyntax syntax, BindingDiagnosticBag diagnostics) { var refKind = RefKind.None; var expressionSyntax = syntax.Expression?.CheckAndUnwrapRefExpression(diagnostics, out refKind); BoundExpression arg = null; if (expressionSyntax != null) { BindValueKind requiredValueKind = GetRequiredReturnValueKind(refKind); arg = BindValue(expressionSyntax, diagnostics, requiredValueKind); } else { // If this is a void return statement in a script, return default(T). var interactiveInitializerMethod = this.ContainingMemberOrLambda as SynthesizedInteractiveInitializerMethod; if (interactiveInitializerMethod != null) { arg = new BoundDefaultExpression(interactiveInitializerMethod.GetNonNullSyntaxNode(), interactiveInitializerMethod.ResultType); } } RefKind sigRefKind; TypeSymbol retType = GetCurrentReturnType(out sigRefKind); bool hasErrors = false; if (IsDirectlyInIterator) { diagnostics.Add(ErrorCode.ERR_ReturnInIterator, syntax.ReturnKeyword.GetLocation()); hasErrors = true; } else if (IsInAsyncMethod()) { if (refKind != RefKind.None) { // This can happen if we are binding an async anonymous method to a delegate type. diagnostics.Add(ErrorCode.ERR_MustNotHaveRefReturn, syntax.ReturnKeyword.GetLocation()); hasErrors = true; } else if (IsIAsyncEnumerableOrIAsyncEnumeratorReturningAsyncMethod()) { diagnostics.Add(ErrorCode.ERR_ReturnInIterator, syntax.ReturnKeyword.GetLocation()); hasErrors = true; } } else if ((object)retType != null && (refKind != RefKind.None) != (sigRefKind != RefKind.None)) { var errorCode = refKind != RefKind.None ? ErrorCode.ERR_MustNotHaveRefReturn : ErrorCode.ERR_MustHaveRefReturn; diagnostics.Add(errorCode, syntax.ReturnKeyword.GetLocation()); hasErrors = true; } if (arg != null) { hasErrors |= arg.HasErrors || ((object)arg.Type != null && arg.Type.IsErrorType()); } if (hasErrors) { return new BoundReturnStatement(syntax, refKind, BindToTypeForErrorRecovery(arg), hasErrors: true); } // The return type could be null; we might be attempting to infer the return type either // because of method type inference, or because we are attempting to do error analysis // on a lambda expression of unknown return type. if ((object)retType != null) { if (retType.IsVoidType() || IsEffectivelyTaskReturningAsyncMethod()) { if (arg != null) { var container = this.ContainingMemberOrLambda; var lambda = container as LambdaSymbol; if ((object)lambda != null) { // Error case: void-returning or async task-returning method or lambda with "return x;" var errorCode = retType.IsVoidType() ? ErrorCode.ERR_RetNoObjectRequiredLambda : ErrorCode.ERR_TaskRetNoObjectRequiredLambda; // Anonymous function converted to a void returning delegate cannot return a value Error(diagnostics, errorCode, syntax.ReturnKeyword); hasErrors = true; // COMPATIBILITY: The native compiler also produced an error // COMPATIBILITY: "Cannot convert lambda expression to delegate type 'Action' because some of the // COMPATIBILITY: return types in the block are not implicitly convertible to the delegate return type" // COMPATIBILITY: This error doesn't make sense in the "void" case because the whole idea of // COMPATIBILITY: "conversion to void" is a bit unusual, and we've already given a good error. } else { // Error case: void-returning or async task-returning method or lambda with "return x;" var errorCode = retType.IsVoidType() ? ErrorCode.ERR_RetNoObjectRequired : ErrorCode.ERR_TaskRetNoObjectRequired; Error(diagnostics, errorCode, syntax.ReturnKeyword, container); hasErrors = true; } } } else { if (arg == null) { // Error case: non-void-returning or Task<T>-returning method or lambda but just have "return;" var requiredType = IsEffectivelyGenericTaskReturningAsyncMethod() ? retType.GetMemberTypeArgumentsNoUseSiteDiagnostics().Single() : retType; Error(diagnostics, ErrorCode.ERR_RetObjectRequired, syntax.ReturnKeyword, requiredType); hasErrors = true; } else { arg = CreateReturnConversion(syntax, diagnostics, arg, sigRefKind, retType); arg = ValidateEscape(arg, Binder.ExternalScope, refKind != RefKind.None, diagnostics); } } } else { // Check that the returned expression is not void. if ((object)arg?.Type != null && arg.Type.IsVoidType()) { Error(diagnostics, ErrorCode.ERR_CantReturnVoid, expressionSyntax); hasErrors = true; } } return new BoundReturnStatement(syntax, refKind, hasErrors ? BindToTypeForErrorRecovery(arg) : arg, hasErrors); } internal BoundExpression CreateReturnConversion( SyntaxNode syntax, BindingDiagnosticBag diagnostics, BoundExpression argument, RefKind returnRefKind, TypeSymbol returnType) { // If the return type is not void then the expression must be implicitly convertible. Conversion conversion; bool badAsyncReturnAlreadyReported = false; CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if (IsInAsyncMethod()) { Debug.Assert(returnRefKind == RefKind.None); if (!IsEffectivelyGenericTaskReturningAsyncMethod()) { conversion = Conversion.NoConversion; badAsyncReturnAlreadyReported = true; } else { returnType = returnType.GetMemberTypeArgumentsNoUseSiteDiagnostics().Single(); conversion = this.Conversions.ClassifyConversionFromExpression(argument, returnType, ref useSiteInfo); } } else { conversion = this.Conversions.ClassifyConversionFromExpression(argument, returnType, ref useSiteInfo); } diagnostics.Add(syntax, useSiteInfo); if (!argument.HasAnyErrors) { if (returnRefKind != RefKind.None) { if (conversion.Kind != ConversionKind.Identity) { Error(diagnostics, ErrorCode.ERR_RefReturnMustHaveIdentityConversion, argument.Syntax, returnType); argument = argument.WithHasErrors(); } else { return BindToNaturalType(argument, diagnostics); } } else if (!conversion.IsImplicit || !conversion.IsValid) { if (!badAsyncReturnAlreadyReported) { RefKind unusedRefKind; if (IsEffectivelyGenericTaskReturningAsyncMethod() && TypeSymbol.Equals(argument.Type, this.GetCurrentReturnType(out unusedRefKind), TypeCompareKind.ConsiderEverything2)) { // Since this is an async method, the return expression must be of type '{0}' rather than 'Task<{0}>' Error(diagnostics, ErrorCode.ERR_BadAsyncReturnExpression, argument.Syntax, returnType); } else { GenerateImplicitConversionError(diagnostics, argument.Syntax, conversion, argument, returnType); if (this.ContainingMemberOrLambda is LambdaSymbol) { ReportCantConvertLambdaReturn(argument.Syntax, diagnostics); } } } } } return CreateConversion(argument.Syntax, argument, conversion, isCast: false, conversionGroupOpt: null, returnType, diagnostics); } private BoundTryStatement BindTryStatement(TryStatementSyntax node, BindingDiagnosticBag diagnostics) { Debug.Assert(node != null); var tryBlock = BindEmbeddedBlock(node.Block, diagnostics); var catchBlocks = BindCatchBlocks(node.Catches, diagnostics); var finallyBlockOpt = (node.Finally != null) ? BindEmbeddedBlock(node.Finally.Block, diagnostics) : null; return new BoundTryStatement(node, tryBlock, catchBlocks, finallyBlockOpt); } private ImmutableArray<BoundCatchBlock> BindCatchBlocks(SyntaxList<CatchClauseSyntax> catchClauses, BindingDiagnosticBag diagnostics) { int n = catchClauses.Count; if (n == 0) { return ImmutableArray<BoundCatchBlock>.Empty; } var catchBlocks = ArrayBuilder<BoundCatchBlock>.GetInstance(n); var hasCatchAll = false; foreach (var catchSyntax in catchClauses) { if (hasCatchAll) { diagnostics.Add(ErrorCode.ERR_TooManyCatches, catchSyntax.CatchKeyword.GetLocation()); } var catchBinder = this.GetBinder(catchSyntax); var catchBlock = catchBinder.BindCatchBlock(catchSyntax, catchBlocks, diagnostics); catchBlocks.Add(catchBlock); hasCatchAll |= catchSyntax.Declaration == null && catchSyntax.Filter == null; } return catchBlocks.ToImmutableAndFree(); } private BoundCatchBlock BindCatchBlock(CatchClauseSyntax node, ArrayBuilder<BoundCatchBlock> previousBlocks, BindingDiagnosticBag diagnostics) { bool hasError = false; TypeSymbol type = null; BoundExpression boundFilter = null; var declaration = node.Declaration; if (declaration != null) { // Note: The type is being bound twice: here and in LocalSymbol.Type. Currently, // LocalSymbol.Type ignores diagnostics so it seems cleaner to bind the type here // as well. However, if LocalSymbol.Type is changed to report diagnostics, we'll // need to avoid binding here since that will result in duplicate diagnostics. type = this.BindType(declaration.Type, diagnostics).Type; Debug.Assert((object)type != null); if (type.IsErrorType()) { hasError = true; } else { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); TypeSymbol effectiveType = type.EffectiveType(ref useSiteInfo); if (!Compilation.IsExceptionType(effectiveType, ref useSiteInfo)) { // "The type caught or thrown must be derived from System.Exception" Error(diagnostics, ErrorCode.ERR_BadExceptionType, declaration.Type); hasError = true; diagnostics.Add(declaration.Type, useSiteInfo); } else { diagnostics.AddDependencies(useSiteInfo); } } } var filter = node.Filter; if (filter != null) { var filterBinder = this.GetBinder(filter); boundFilter = filterBinder.BindCatchFilter(filter, diagnostics); hasError |= boundFilter.HasAnyErrors; } if (!hasError) { // TODO: Loop is O(n), caller is O(n^2). Perhaps we could iterate in reverse order (since it's easier to find // base types than to find derived types). Debug.Assert(((object)type == null) || !type.IsErrorType()); foreach (var previousBlock in previousBlocks) { var previousType = previousBlock.ExceptionTypeOpt; // If the previous type is a generic parameter we don't know what exception types it's gonna catch exactly. // If it is a class-type we know it's gonna catch all exception types of its type and types that are derived from it. // So if the current type is a class-type (or an effective base type of a generic parameter) // that derives from the previous type the current catch is unreachable. if (previousBlock.ExceptionFilterOpt == null && (object)previousType != null && !previousType.IsErrorType()) { if ((object)type != null) { CompoundUseSiteInfo<AssemblySymbol> useSiteInfo = GetNewCompoundUseSiteInfo(diagnostics); if (Conversions.HasIdentityOrImplicitReferenceConversion(type, previousType, ref useSiteInfo)) { // "A previous catch clause already catches all exceptions of this or of a super type ('{0}')" Error(diagnostics, ErrorCode.ERR_UnreachableCatch, declaration.Type, previousType); diagnostics.Add(declaration.Type, useSiteInfo); hasError = true; break; } diagnostics.Add(declaration.Type, useSiteInfo); } else if (TypeSymbol.Equals(previousType, Compilation.GetWellKnownType(WellKnownType.System_Exception), TypeCompareKind.ConsiderEverything2) && Compilation.SourceAssembly.RuntimeCompatibilityWrapNonExceptionThrows) { // If the RuntimeCompatibility(WrapNonExceptionThrows = false) is applied on the source assembly or any referenced netmodule. // an empty catch may catch exceptions that don't derive from System.Exception. // "A previous catch clause already catches all exceptions..." Error(diagnostics, ErrorCode.WRN_UnreachableGeneralCatch, node.CatchKeyword); break; } } } } var binder = GetBinder(node); Debug.Assert(binder != null); ImmutableArray<LocalSymbol> locals = binder.GetDeclaredLocalsForScope(node); BoundExpression exceptionSource = null; LocalSymbol local = locals.FirstOrDefault(); if (local?.DeclarationKind == LocalDeclarationKind.CatchVariable) { Debug.Assert(local.Type.IsErrorType() || (TypeSymbol.Equals(local.Type, type, TypeCompareKind.ConsiderEverything2))); // Check for local variable conflicts in the *enclosing* binder, not the *current* binder; // obviously we will find a local of the given name in the current binder. hasError |= this.ValidateDeclarationNameConflictsInScope(local, diagnostics); exceptionSource = new BoundLocal(declaration, local, ConstantValue.NotAvailable, local.Type); } var block = BindEmbeddedBlock(node.Block, diagnostics); return new BoundCatchBlock(node, locals, exceptionSource, type, exceptionFilterPrologueOpt: null, boundFilter, block, hasError); } private BoundExpression BindCatchFilter(CatchFilterClauseSyntax filter, BindingDiagnosticBag diagnostics) { BoundExpression boundFilter = this.BindBooleanExpression(filter.FilterExpression, diagnostics); if (boundFilter.ConstantValue != ConstantValue.NotAvailable) { // Depending on whether the filter constant is true or false, and whether there are other catch clauses, // we suggest different actions var errorCode = boundFilter.ConstantValue.BooleanValue ? ErrorCode.WRN_FilterIsConstantTrue : (filter.Parent.Parent is TryStatementSyntax s && s.Catches.Count == 1 && s.Finally == null) ? ErrorCode.WRN_FilterIsConstantFalseRedundantTryCatch : ErrorCode.WRN_FilterIsConstantFalse; // Since the expression is a constant, the name can be retrieved from the first token Error(diagnostics, errorCode, filter.FilterExpression); } return boundFilter; } // Report an extra error on the return if we are in a lambda conversion. private void ReportCantConvertLambdaReturn(SyntaxNode syntax, BindingDiagnosticBag diagnostics) { // Suppress this error if the lambda is a result of a query rewrite. if (syntax.Parent is QueryClauseSyntax || syntax.Parent is SelectOrGroupClauseSyntax) return; var lambda = this.ContainingMemberOrLambda as LambdaSymbol; if ((object)lambda != null) { Location location = GetLocationForDiagnostics(syntax); if (IsInAsyncMethod()) { // Cannot convert async {0} to intended delegate type. An async {0} may return void, Task or Task<T>, none of which are convertible to '{1}'. Error(diagnostics, ErrorCode.ERR_CantConvAsyncAnonFuncReturns, location, lambda.MessageID.Localize(), lambda.ReturnType); } else { // 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 Error(diagnostics, ErrorCode.ERR_CantConvAnonMethReturns, location, lambda.MessageID.Localize()); } } } private static Location GetLocationForDiagnostics(SyntaxNode node) { switch (node) { case LambdaExpressionSyntax lambdaSyntax: return Location.Create(lambdaSyntax.SyntaxTree, Text.TextSpan.FromBounds(lambdaSyntax.SpanStart, lambdaSyntax.ArrowToken.Span.End)); case AnonymousMethodExpressionSyntax anonymousMethodSyntax: return Location.Create(anonymousMethodSyntax.SyntaxTree, Text.TextSpan.FromBounds(anonymousMethodSyntax.SpanStart, anonymousMethodSyntax.ParameterList?.Span.End ?? anonymousMethodSyntax.DelegateKeyword.Span.End)); } return node.Location; } private static bool IsValidStatementExpression(SyntaxNode syntax, BoundExpression expression) { bool syntacticallyValid = SyntaxFacts.IsStatementExpression(syntax); if (!syntacticallyValid) { return false; } if (expression.IsSuppressed) { return false; } // It is possible that an expression is syntactically valid but semantic analysis // reveals it to be illegal in a statement expression: "new MyDelegate(M)" for example // is not legal because it is a delegate-creation-expression and not an // object-creation-expression, but of course we don't know that syntactically. if (expression.Kind == BoundKind.DelegateCreationExpression || expression.Kind == BoundKind.NameOfOperator) { return false; } return true; } /// <summary> /// Wrap a given expression e into a block as either { e; } or { return e; } /// Shared between lambda and expression-bodied method binding. /// </summary> internal BoundBlock CreateBlockFromExpression(CSharpSyntaxNode node, ImmutableArray<LocalSymbol> locals, RefKind refKind, BoundExpression expression, ExpressionSyntax expressionSyntax, BindingDiagnosticBag diagnostics) { RefKind returnRefKind; var returnType = GetCurrentReturnType(out returnRefKind); var syntax = expressionSyntax ?? expression.Syntax; BoundStatement statement; if (IsInAsyncMethod() && refKind != RefKind.None) { // This can happen if we are binding an async anonymous method to a delegate type. Error(diagnostics, ErrorCode.ERR_MustNotHaveRefReturn, syntax); expression = BindToTypeForErrorRecovery(expression); statement = new BoundReturnStatement(syntax, refKind, expression) { WasCompilerGenerated = true }; } else if ((object)returnType != null) { if ((refKind != RefKind.None) != (returnRefKind != RefKind.None) && expression.Kind != BoundKind.ThrowExpression) { var errorCode = refKind != RefKind.None ? ErrorCode.ERR_MustNotHaveRefReturn : ErrorCode.ERR_MustHaveRefReturn; Error(diagnostics, errorCode, syntax); expression = BindToTypeForErrorRecovery(expression); statement = new BoundReturnStatement(syntax, RefKind.None, expression) { WasCompilerGenerated = true }; } else if (returnType.IsVoidType() || IsEffectivelyTaskReturningAsyncMethod()) { // If the return type is void then the expression is required to be a legal // statement expression. Debug.Assert(expressionSyntax != null || !IsValidExpressionBody(expressionSyntax, expression)); bool errors = false; if (expressionSyntax == null || !IsValidExpressionBody(expressionSyntax, expression)) { expression = BindToTypeForErrorRecovery(expression); Error(diagnostics, ErrorCode.ERR_IllegalStatement, syntax); errors = true; } else { expression = BindToNaturalType(expression, diagnostics); } // Don't mark compiler generated so that the rewriter generates sequence points var expressionStatement = new BoundExpressionStatement(syntax, expression, errors); CheckForUnobservedAwaitable(expression, diagnostics); statement = expressionStatement; } else if (IsIAsyncEnumerableOrIAsyncEnumeratorReturningAsyncMethod()) { Error(diagnostics, ErrorCode.ERR_ReturnInIterator, syntax); expression = BindToTypeForErrorRecovery(expression); statement = new BoundReturnStatement(syntax, returnRefKind, expression) { WasCompilerGenerated = true }; } else { expression = returnType.IsErrorType() ? BindToTypeForErrorRecovery(expression) : CreateReturnConversion(syntax, diagnostics, expression, refKind, returnType); statement = new BoundReturnStatement(syntax, returnRefKind, expression) { WasCompilerGenerated = true }; } } else if (expression.Type?.SpecialType == SpecialType.System_Void) { expression = BindToNaturalType(expression, diagnostics); statement = new BoundExpressionStatement(syntax, expression) { WasCompilerGenerated = true }; } else { // When binding for purpose of inferring the return type of a lambda, we do not require returned expressions (such as `default` or switch expressions) to have a natural type var inferringLambda = this.ContainingMemberOrLambda is MethodSymbol method && (object)method.ReturnType == LambdaSymbol.ReturnTypeIsBeingInferred; if (!inferringLambda) { expression = BindToNaturalType(expression, diagnostics); } statement = new BoundReturnStatement(syntax, refKind, expression) { WasCompilerGenerated = true }; } // Need to attach the tree for when we generate sequence points. return new BoundBlock(node, locals, ImmutableArray.Create(statement)) { WasCompilerGenerated = node.Kind() != SyntaxKind.ArrowExpressionClause }; } private static bool IsValidExpressionBody(SyntaxNode expressionSyntax, BoundExpression expression) { return IsValidStatementExpression(expressionSyntax, expression) || expressionSyntax.Kind() == SyntaxKind.ThrowExpression; } /// <summary> /// Binds an expression-bodied member with expression e as either { return e; } or { e; }. /// </summary> internal virtual BoundBlock BindExpressionBodyAsBlock(ArrowExpressionClauseSyntax expressionBody, BindingDiagnosticBag diagnostics) { Binder bodyBinder = this.GetBinder(expressionBody); Debug.Assert(bodyBinder != null); return bindExpressionBodyAsBlockInternal(expressionBody, bodyBinder, diagnostics); // Use static local function to prevent accidentally calling instance methods on `this` instead of `bodyBinder` static BoundBlock bindExpressionBodyAsBlockInternal(ArrowExpressionClauseSyntax expressionBody, Binder bodyBinder, BindingDiagnosticBag diagnostics) { RefKind refKind; ExpressionSyntax expressionSyntax = expressionBody.Expression.CheckAndUnwrapRefExpression(diagnostics, out refKind); BindValueKind requiredValueKind = bodyBinder.GetRequiredReturnValueKind(refKind); BoundExpression expression = bodyBinder.BindValue(expressionSyntax, diagnostics, requiredValueKind); expression = bodyBinder.ValidateEscape(expression, Binder.ExternalScope, refKind != RefKind.None, diagnostics); return bodyBinder.CreateBlockFromExpression(expressionBody, bodyBinder.GetDeclaredLocalsForScope(expressionBody), refKind, expression, expressionSyntax, diagnostics); } } /// <summary> /// Binds a lambda with expression e as either { return e; } or { e; }. /// </summary> public BoundBlock BindLambdaExpressionAsBlock(ExpressionSyntax body, BindingDiagnosticBag diagnostics) { Binder bodyBinder = this.GetBinder(body); Debug.Assert(bodyBinder != null); RefKind refKind; var expressionSyntax = body.CheckAndUnwrapRefExpression(diagnostics, out refKind); BindValueKind requiredValueKind = GetRequiredReturnValueKind(refKind); BoundExpression expression = bodyBinder.BindValue(expressionSyntax, diagnostics, requiredValueKind); expression = ValidateEscape(expression, Binder.ExternalScope, refKind != RefKind.None, diagnostics); return bodyBinder.CreateBlockFromExpression(body, bodyBinder.GetDeclaredLocalsForScope(body), refKind, expression, expressionSyntax, diagnostics); } public BoundBlock CreateBlockFromExpression(ExpressionSyntax body, BoundExpression expression, BindingDiagnosticBag diagnostics) { Binder bodyBinder = this.GetBinder(body); Debug.Assert(bodyBinder != null); Debug.Assert(body.Kind() != SyntaxKind.RefExpression); return bodyBinder.CreateBlockFromExpression(body, bodyBinder.GetDeclaredLocalsForScope(body), RefKind.None, expression, body, diagnostics); } private BindValueKind GetRequiredReturnValueKind(RefKind refKind) { BindValueKind requiredValueKind = BindValueKind.RValue; if (refKind != RefKind.None) { GetCurrentReturnType(out var sigRefKind); requiredValueKind = sigRefKind == RefKind.Ref ? BindValueKind.RefReturn : BindValueKind.ReadonlyRef; } return requiredValueKind; } public virtual BoundNode BindMethodBody(CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics, bool includesFieldInitializers = false) { switch (syntax) { case RecordDeclarationSyntax recordDecl: return BindRecordConstructorBody(recordDecl, diagnostics); case BaseMethodDeclarationSyntax method: if (method.Kind() == SyntaxKind.ConstructorDeclaration) { return BindConstructorBody((ConstructorDeclarationSyntax)method, diagnostics, includesFieldInitializers); } return BindMethodBody(method, method.Body, method.ExpressionBody, diagnostics); case AccessorDeclarationSyntax accessor: return BindMethodBody(accessor, accessor.Body, accessor.ExpressionBody, diagnostics); case ArrowExpressionClauseSyntax arrowExpression: return BindExpressionBodyAsBlock(arrowExpression, diagnostics); case CompilationUnitSyntax compilationUnit: return BindSimpleProgram(compilationUnit, diagnostics); default: throw ExceptionUtilities.UnexpectedValue(syntax.Kind()); } } private BoundNode BindSimpleProgram(CompilationUnitSyntax compilationUnit, BindingDiagnosticBag diagnostics) { var simpleProgram = (SynthesizedSimpleProgramEntryPointSymbol)ContainingMemberOrLambda; return GetBinder(compilationUnit).BindSimpleProgramCompilationUnit(compilationUnit, simpleProgram, diagnostics); } private BoundNode BindSimpleProgramCompilationUnit(CompilationUnitSyntax compilationUnit, SynthesizedSimpleProgramEntryPointSymbol simpleProgram, BindingDiagnosticBag diagnostics) { ArrayBuilder<BoundStatement> boundStatements = ArrayBuilder<BoundStatement>.GetInstance(); foreach (var statement in compilationUnit.Members) { if (statement is GlobalStatementSyntax topLevelStatement) { var boundStatement = BindStatement(topLevelStatement.Statement, diagnostics); boundStatements.Add(boundStatement); } } return new BoundNonConstructorMethodBody(compilationUnit, FinishBindBlockParts(compilationUnit, boundStatements.ToImmutableAndFree(), diagnostics).MakeCompilerGenerated(), expressionBody: null); } private BoundNode BindRecordConstructorBody(RecordDeclarationSyntax recordDecl, BindingDiagnosticBag diagnostics) { Debug.Assert(recordDecl.ParameterList is object); Debug.Assert(recordDecl.IsKind(SyntaxKind.RecordDeclaration)); Binder bodyBinder = this.GetBinder(recordDecl); Debug.Assert(bodyBinder != null); BoundExpressionStatement initializer = null; if (recordDecl.PrimaryConstructorBaseTypeIfClass is PrimaryConstructorBaseTypeSyntax baseWithArguments) { initializer = bodyBinder.BindConstructorInitializer(baseWithArguments, diagnostics); } return new BoundConstructorMethodBody(recordDecl, bodyBinder.GetDeclaredLocalsForScope(recordDecl), initializer, blockBody: new BoundBlock(recordDecl, ImmutableArray<LocalSymbol>.Empty, ImmutableArray<BoundStatement>.Empty).MakeCompilerGenerated(), expressionBody: null); } internal virtual BoundExpressionStatement BindConstructorInitializer(PrimaryConstructorBaseTypeSyntax initializer, BindingDiagnosticBag diagnostics) { BoundExpression initializerInvocation = GetBinder(initializer).BindConstructorInitializer(initializer.ArgumentList, (MethodSymbol)this.ContainingMember(), diagnostics); var constructorInitializer = new BoundExpressionStatement(initializer, initializerInvocation); Debug.Assert(initializerInvocation.HasAnyErrors || constructorInitializer.IsConstructorInitializer(), "Please keep this bound node in sync with BoundNodeExtensions.IsConstructorInitializer."); return constructorInitializer; } private BoundNode BindConstructorBody(ConstructorDeclarationSyntax constructor, BindingDiagnosticBag diagnostics, bool includesFieldInitializers) { ConstructorInitializerSyntax initializer = constructor.Initializer; if (initializer == null && constructor.Body == null && constructor.ExpressionBody == null) { return null; } Binder bodyBinder = this.GetBinder(constructor); Debug.Assert(bodyBinder != null); bool thisInitializer = initializer?.IsKind(SyntaxKind.ThisConstructorInitializer) == true; if (!thisInitializer && ContainingType.GetMembersUnordered().OfType<SynthesizedRecordConstructor>().Any()) { var constructorSymbol = (MethodSymbol)this.ContainingMember(); if (!constructorSymbol.IsStatic && !SynthesizedRecordCopyCtor.IsCopyConstructor(constructorSymbol)) { // Note: we check the constructor initializer of copy constructors elsewhere Error(diagnostics, ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, initializer?.ThisOrBaseKeyword ?? constructor.Identifier); } } // The `: this()` initializer is ignored when it is a default value type constructor // and we need to include field initializers into the constructor. bool skipInitializer = includesFieldInitializers && thisInitializer && ContainingType.IsDefaultValueTypeConstructor(initializer); // Using BindStatement to bind block to make sure we are reusing results of partial binding in SemanticModel return new BoundConstructorMethodBody(constructor, bodyBinder.GetDeclaredLocalsForScope(constructor), skipInitializer ? new BoundNoOpStatement(constructor, NoOpStatementFlavor.Default) : initializer == null ? null : bodyBinder.BindConstructorInitializer(initializer, diagnostics), constructor.Body == null ? null : (BoundBlock)bodyBinder.BindStatement(constructor.Body, diagnostics), constructor.ExpressionBody == null ? null : bodyBinder.BindExpressionBodyAsBlock(constructor.ExpressionBody, constructor.Body == null ? diagnostics : BindingDiagnosticBag.Discarded)); } internal virtual BoundExpressionStatement BindConstructorInitializer(ConstructorInitializerSyntax initializer, BindingDiagnosticBag diagnostics) { BoundExpression initializerInvocation = GetBinder(initializer).BindConstructorInitializer(initializer.ArgumentList, (MethodSymbol)this.ContainingMember(), diagnostics); // Base WasCompilerGenerated state off of whether constructor is implicitly declared, this will ensure proper instrumentation. Debug.Assert(!this.ContainingMember().IsImplicitlyDeclared); var constructorInitializer = new BoundExpressionStatement(initializer, initializerInvocation); Debug.Assert(initializerInvocation.HasAnyErrors || constructorInitializer.IsConstructorInitializer(), "Please keep this bound node in sync with BoundNodeExtensions.IsConstructorInitializer."); return constructorInitializer; } private BoundNode BindMethodBody(CSharpSyntaxNode declaration, BlockSyntax blockBody, ArrowExpressionClauseSyntax expressionBody, BindingDiagnosticBag diagnostics) { if (blockBody == null && expressionBody == null) { return null; } // Using BindStatement to bind block to make sure we are reusing results of partial binding in SemanticModel return new BoundNonConstructorMethodBody(declaration, blockBody == null ? null : (BoundBlock)BindStatement(blockBody, diagnostics), expressionBody == null ? null : BindExpressionBodyAsBlock(expressionBody, blockBody == null ? diagnostics : BindingDiagnosticBag.Discarded)); } internal virtual ImmutableArray<LocalSymbol> Locals { get { return ImmutableArray<LocalSymbol>.Empty; } } internal virtual ImmutableArray<LocalFunctionSymbol> LocalFunctions { get { return ImmutableArray<LocalFunctionSymbol>.Empty; } } internal virtual ImmutableArray<LabelSymbol> Labels { get { return ImmutableArray<LabelSymbol>.Empty; } } /// <summary> /// If this binder owns the scope that can declare extern aliases, a set of declared aliases should be returned (even if empty). /// Otherwise, a default instance should be returned. /// </summary> internal virtual ImmutableArray<AliasAndExternAliasDirective> ExternAliases { get { return default; } } /// <summary> /// If this binder owns the scope that can declare using aliases, a set of declared aliases should be returned (even if empty). /// Otherwise, a default instance should be returned. /// Note, only aliases syntactically declared within the enclosing declaration are included. For example, global aliases /// declared in a different compilation units are not included. /// </summary> internal virtual ImmutableArray<AliasAndUsingDirective> UsingAliases { get { return default; } } /// <summary> /// Perform a lookup for the specified method on the specified expression by attempting to invoke it /// </summary> /// <param name="receiver">The expression to perform pattern lookup on</param> /// <param name="methodName">Method to search for.</param> /// <param name="syntaxNode">The expression for which lookup is being performed</param> /// <param name="diagnostics">Populated with binding diagnostics.</param> /// <param name="result">The method symbol that was looked up, or null</param> /// <returns>A <see cref="PatternLookupResult"/> value with the outcome of the lookup</returns> internal PatternLookupResult PerformPatternMethodLookup(BoundExpression receiver, string methodName, SyntaxNode syntaxNode, BindingDiagnosticBag diagnostics, out MethodSymbol result) { var bindingDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); try { result = null; var boundAccess = BindInstanceMemberAccess( syntaxNode, syntaxNode, receiver, methodName, rightArity: 0, typeArgumentsSyntax: default, typeArgumentsWithAnnotations: default, invoked: true, indexed: false, bindingDiagnostics); if (boundAccess.Kind != BoundKind.MethodGroup) { // the thing is not a method return PatternLookupResult.NotAMethod; } // NOTE: Because we're calling this method with no arguments and we // explicitly ignore default values for params parameters // (see ParameterSymbol.IsOptional) we know that no ParameterArray // containing method can be invoked in normal form which allows // us to skip some work during the lookup. var analyzedArguments = AnalyzedArguments.GetInstance(); var patternMethodCall = BindMethodGroupInvocation( syntaxNode, syntaxNode, methodName, (BoundMethodGroup)boundAccess, analyzedArguments, bindingDiagnostics, queryClause: null, allowUnexpandedForm: false, anyApplicableCandidates: out _); analyzedArguments.Free(); if (patternMethodCall.Kind != BoundKind.Call) { return PatternLookupResult.NotCallable; } var call = (BoundCall)patternMethodCall; if (call.ResultKind == LookupResultKind.Empty) { return PatternLookupResult.NoResults; } // we have succeeded or almost succeeded to bind the method // report additional binding diagnostics that we have seen so far diagnostics.AddRange(bindingDiagnostics); var patternMethodSymbol = call.Method; if (patternMethodSymbol is ErrorMethodSymbol || patternMethodCall.HasAnyErrors) { return PatternLookupResult.ResultHasErrors; } // Success! result = patternMethodSymbol; return PatternLookupResult.Success; } finally { bindingDiagnostics.Free(); } } } }
1
dotnet/roslyn
55,125
Don't use DefaultInterpolatedStringHandler in expression trees
Introduces a binder flag to track whether we are currently in an expression tree or not. Fixes https://github.com/dotnet/roslyn/issues/55114.
333fred
2021-07-26T22:08:39Z
2021-07-27T19:33:24Z
5840335153dcca42570a853cdacd06d660fe9596
cfc12ce93ce377c4b9581ccf88403e6740d63977
Don't use DefaultInterpolatedStringHandler in expression trees. Introduces a binder flag to track whether we are currently in an expression tree or not. Fixes https://github.com/dotnet/roslyn/issues/55114.
./src/Compilers/CSharp/Portable/Binder/Semantics/Conversions/ConversionsBase.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal abstract partial class ConversionsBase { private const int MaximumRecursionDepth = 50; protected readonly AssemblySymbol corLibrary; protected readonly int currentRecursionDepth; internal readonly bool IncludeNullability; /// <summary> /// An optional clone of this instance with distinct IncludeNullability. /// Used to avoid unnecessary allocations when calling WithNullability() repeatedly. /// </summary> private ConversionsBase _lazyOtherNullability; protected ConversionsBase(AssemblySymbol corLibrary, int currentRecursionDepth, bool includeNullability, ConversionsBase otherNullabilityOpt) { Debug.Assert((object)corLibrary != null); Debug.Assert(otherNullabilityOpt == null || includeNullability != otherNullabilityOpt.IncludeNullability); Debug.Assert(otherNullabilityOpt == null || currentRecursionDepth == otherNullabilityOpt.currentRecursionDepth); this.corLibrary = corLibrary; this.currentRecursionDepth = currentRecursionDepth; IncludeNullability = includeNullability; _lazyOtherNullability = otherNullabilityOpt; } /// <summary> /// Returns this instance if includeNullability is correct, and returns a /// cached clone of this instance with distinct IncludeNullability otherwise. /// </summary> internal ConversionsBase WithNullability(bool includeNullability) { if (IncludeNullability == includeNullability) { return this; } if (_lazyOtherNullability == null) { Interlocked.CompareExchange(ref _lazyOtherNullability, WithNullabilityCore(includeNullability), null); } Debug.Assert(_lazyOtherNullability.IncludeNullability == includeNullability); Debug.Assert(_lazyOtherNullability._lazyOtherNullability == this); return _lazyOtherNullability; } protected abstract ConversionsBase WithNullabilityCore(bool includeNullability); public abstract Conversion GetMethodGroupDelegateConversion(BoundMethodGroup source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); public abstract Conversion GetMethodGroupFunctionPointerConversion(BoundMethodGroup source, FunctionPointerTypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); public abstract Conversion GetStackAllocConversion(BoundStackAllocArrayCreation sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); protected abstract ConversionsBase CreateInstance(int currentRecursionDepth); protected abstract Conversion GetInterpolatedStringConversion(BoundUnconvertedInterpolatedString source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); internal AssemblySymbol CorLibrary { get { return corLibrary; } } /// <summary> /// Determines if the source expression is convertible to the destination type via /// any built-in or user-defined implicit conversion. /// </summary> public Conversion ClassifyImplicitConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null); Debug.Assert((object)destination != null); var sourceType = sourceExpression.Type; //PERF: identity conversion is by far the most common implicit conversion, check for that first if ((object)sourceType != null && HasIdentityConversionInternal(sourceType, destination)) { return Conversion.Identity; } Conversion conversion = ClassifyImplicitBuiltInConversionFromExpression(sourceExpression, sourceType, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } if ((object)sourceType != null) { // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(sourceType, destination); if (fastConversion.Exists) { if (fastConversion.IsImplicit) { return fastConversion; } } else { conversion = ClassifyImplicitBuiltInConversionSlow(sourceType, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } } } conversion = GetImplicitUserDefinedConversion(sourceExpression, sourceType, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } // The switch expression conversion is "lowest priority", so that if there is a conversion from the expression's // type it will be preferred over the switch expression conversion. Technically, we would want the language // specification to say that the switch expression conversion only "exists" if there is no implicit conversion // from the type, and we accomplish that by making it lowest priority. The same is true for the conditional // expression conversion. conversion = GetSwitchExpressionConversion(sourceExpression, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } return GetConditionalExpressionConversion(sourceExpression, destination, ref useSiteInfo); } /// <summary> /// Determines if the source type is convertible to the destination type via /// any built-in or user-defined implicit conversion. /// </summary> public Conversion ClassifyImplicitConversionFromType(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); //PERF: identity conversions are very common, check for that first. if (HasIdentityConversionInternal(source, destination)) { return Conversion.Identity; } // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion.IsImplicit ? fastConversion : Conversion.NoConversion; } else { Conversion conversion = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } } return GetImplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); } /// <summary> /// Determines if the source expression of given type is convertible to the destination type via /// any built-in or user-defined conversion. /// /// This helper is used in rare cases involving synthesized expressions where we know the type of an expression, but do not have the actual expression. /// The reason for this helper (as opposed to ClassifyConversionFromType) is that conversions from expressions could be different /// from conversions from type. For example expressions of dynamic type are implicitly convertable to any type, while dynamic type itself is not. /// </summary> public Conversion ClassifyConversionFromExpressionType(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // since we are converting from expression, we may have implicit dynamic conversion if (HasImplicitDynamicConversionFromExpression(source, destination)) { return Conversion.ImplicitDynamic; } return ClassifyConversionFromType(source, destination, ref useSiteInfo); } private static bool TryGetVoidConversion(TypeSymbol source, TypeSymbol destination, out Conversion conversion) { var sourceIsVoid = source?.SpecialType == SpecialType.System_Void; var destIsVoid = destination.SpecialType == SpecialType.System_Void; // 'void' is not supposed to be able to convert to or from anything, but in practice, // a lot of code depends on checking whether an expression of type 'void' is convertible to 'void'. // (e.g. for an expression lambda which returns void). // Therefore we allow an identity conversion between 'void' and 'void'. if (sourceIsVoid && destIsVoid) { conversion = Conversion.Identity; return true; } // If exactly one of source or destination is of type 'void' then no conversion may exist. if (sourceIsVoid || destIsVoid) { conversion = Conversion.NoConversion; return true; } conversion = default; return false; } /// <summary> /// Determines if the source expression is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source expression to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the implicit conversion or explicit depending on "forCast" /// </remarks> public Conversion ClassifyConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast = false) { Debug.Assert(sourceExpression != null); Debug.Assert((object)destination != null); if (TryGetVoidConversion(sourceExpression.Type, destination, out var conversion)) { return conversion; } if (forCast) { return ClassifyConversionFromExpressionForCast(sourceExpression, destination, ref useSiteInfo); } var result = ClassifyImplicitConversionFromExpression(sourceExpression, destination, ref useSiteInfo); if (result.Exists) { return result; } return ClassifyExplicitOnlyConversionFromExpression(sourceExpression, destination, ref useSiteInfo, forCast: false); } /// <summary> /// Determines if the source type is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source type to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the implicit conversion or explicit depending on "forCast" /// </remarks> public Conversion ClassifyConversionFromType(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast = false) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (TryGetVoidConversion(source, destination, out var voidConversion)) { return voidConversion; } if (forCast) { return ClassifyConversionFromTypeForCast(source, destination, ref useSiteInfo); } // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion; } else { Conversion conversion1 = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (conversion1.Exists) { return conversion1; } } Conversion conversion = GetImplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } conversion = ClassifyExplicitBuiltInOnlyConversion(source, destination, ref useSiteInfo, forCast: false); if (conversion.Exists) { return conversion; } return GetExplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); } /// <summary> /// Determines if the source expression is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source expression to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the built-in conversion. /// /// An implicit conversion exists from an expression of a dynamic type to any type. /// An explicit conversion exists from a dynamic type to any type. /// When casting we prefer the explicit conversion. /// </remarks> private Conversion ClassifyConversionFromExpressionForCast(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert((object)destination != null); Conversion implicitConversion = ClassifyImplicitConversionFromExpression(source, destination, ref useSiteInfo); if (implicitConversion.Exists && !ExplicitConversionMayDifferFromImplicit(implicitConversion)) { return implicitConversion; } Conversion explicitConversion = ClassifyExplicitOnlyConversionFromExpression(source, destination, ref useSiteInfo, forCast: true); if (explicitConversion.Exists) { return explicitConversion; } // It is possible for a user-defined conversion to be unambiguous when considered as // an implicit conversion and ambiguous when considered as an explicit conversion. // The native compiler does not check to see if a cast could be successfully bound as // an unambiguous user-defined implicit conversion; it goes right to the ambiguous // user-defined explicit conversion and produces an error. This means that in // C# 5 it is possible to have: // // Y y = new Y(); // Z z1 = y; // // succeed but // // Z z2 = (Z)y; // // fail. // // However, there is another interesting wrinkle. It is possible for both // an implicit user-defined conversion and an explicit user-defined conversion // to exist and be unambiguous. For example, if there is an implicit conversion // double-->C and an explicit conversion from int-->C, and the user casts a short // to C, then both the implicit and explicit conversions are applicable and // unambiguous. The native compiler in this case prefers the explicit conversion, // and for backwards compatibility, we match it. return implicitConversion; } /// <summary> /// Determines if the source type is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source type to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the built-in conversion. /// </remarks> private Conversion ClassifyConversionFromTypeForCast(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion; } Conversion implicitBuiltInConversion = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (implicitBuiltInConversion.Exists && !ExplicitConversionMayDifferFromImplicit(implicitBuiltInConversion)) { return implicitBuiltInConversion; } Conversion explicitBuiltInConversion = ClassifyExplicitBuiltInOnlyConversion(source, destination, ref useSiteInfo, forCast: true); if (explicitBuiltInConversion.Exists) { return explicitBuiltInConversion; } if (implicitBuiltInConversion.Exists) { return implicitBuiltInConversion; } // It is possible for a user-defined conversion to be unambiguous when considered as // an implicit conversion and ambiguous when considered as an explicit conversion. // The native compiler does not check to see if a cast could be successfully bound as // an unambiguous user-defined implicit conversion; it goes right to the ambiguous // user-defined explicit conversion and produces an error. This means that in // C# 5 it is possible to have: // // Y y = new Y(); // Z z1 = y; // // succeed but // // Z z2 = (Z)y; // // fail. var conversion = GetExplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } return GetImplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); } /// <summary> /// Attempt a quick classification of builtin conversions. As result of "no conversion" /// means that there is no built-in conversion, though there still may be a user-defined /// conversion if compiling against a custom mscorlib. /// </summary> public static Conversion FastClassifyConversion(TypeSymbol source, TypeSymbol target) { ConversionKind convKind = ConversionEasyOut.ClassifyConversion(source, target); if (convKind != ConversionKind.ImplicitNullable && convKind != ConversionKind.ExplicitNullable) { return Conversion.GetTrivialConversion(convKind); } return Conversion.MakeNullableConversion(convKind, FastClassifyConversion(source.StrippedType(), target.StrippedType())); } public Conversion ClassifyBuiltInConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion; } else { Conversion conversion = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } } return ClassifyExplicitBuiltInOnlyConversion(source, destination, ref useSiteInfo, forCast: false); } /// <summary> /// Determines if the source type is convertible to the destination type via /// any standard implicit or standard explicit conversion. /// </summary> /// <remarks> /// Not all built-in explicit conversions are standard explicit conversions. /// </remarks> public Conversion ClassifyStandardConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert((object)destination != null); // Note that the definition of explicit standard conversion does not include all explicit // reference conversions! There is a standard implicit reference conversion from // Action<Object> to Action<Exception>, thanks to contravariance. There is a standard // implicit reference conversion from Action<Object> to Action<String> for the same reason. // Therefore there is an explicit reference conversion from Action<Exception> to // Action<String>; a given Action<Exception> might be an Action<Object>, and hence // convertible to Action<String>. However, this is not a *standard* explicit conversion. The // standard explicit conversions are all the standard implicit conversions and their // opposites. Therefore Action<Object>-->Action<String> and Action<String>-->Action<Object> // are both standard conversions. But Action<String>-->Action<Exception> is not a standard // explicit conversion because neither it nor its opposite is a standard implicit // conversion. // // Similarly, there is no standard explicit conversion from double to decimal, because // there is no standard implicit conversion between the two types. // SPEC: The standard explicit conversions are all standard implicit conversions plus // SPEC: the subset of the explicit conversions for which an opposite standard implicit // SPEC: conversion exists. In other words, if a standard implicit conversion exists from // SPEC: a type A to a type B, then a standard explicit conversion exists from type A to // SPEC: type B and from type B to type A. Conversion conversion = ClassifyStandardImplicitConversion(sourceExpression, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } if ((object)source != null) { return DeriveStandardExplicitFromOppositeStandardImplicitConversion(source, destination, ref useSiteInfo); } return Conversion.NoConversion; } private Conversion ClassifyStandardImplicitConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert(sourceExpression == null || (object)sourceExpression.Type == (object)source); Debug.Assert((object)destination != null); // SPEC: The following implicit conversions are classified as standard implicit conversions: // SPEC: Identity conversions // SPEC: Implicit numeric conversions // SPEC: Implicit nullable conversions // SPEC: Implicit reference conversions // SPEC: Boxing conversions // SPEC: Implicit constant expression conversions // SPEC: Implicit conversions involving type parameters // // and in unsafe code: // // SPEC: From any pointer type to void* // // SPEC ERROR: // The specification does not say to take into account the conversion from // the *expression*, only its *type*. But the expression may not have a type // (because it is null, a method group, or a lambda), or the expression might // be convertible to the destination type via a constant numeric conversion. // For example, the native compiler allows "C c = 1;" to work if C is a class which // has an implicit conversion from byte to C, despite the fact that there is // obviously no standard implicit conversion from *int* to *byte*. // Similarly, if a struct S has an implicit conversion from string to S, then // "S s = null;" should be allowed. // // We extend the definition of standard implicit conversions to include // all of the implicit conversions that are allowed based on an expression, // with the exception of the switch expression conversion. Conversion conversion = ClassifyImplicitBuiltInConversionFromExpression(sourceExpression, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } if ((object)source != null) { return ClassifyStandardImplicitConversion(source, destination, ref useSiteInfo); } return Conversion.NoConversion; } private Conversion ClassifyStandardImplicitConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return Conversion.Identity; } if (HasImplicitNumericConversion(source, destination)) { return Conversion.ImplicitNumeric; } var nullableConversion = ClassifyImplicitNullableConversion(source, destination, ref useSiteInfo); if (nullableConversion.Exists) { return nullableConversion; } if (HasImplicitReferenceConversion(source, destination, ref useSiteInfo)) { return Conversion.ImplicitReference; } if (HasBoxingConversion(source, destination, ref useSiteInfo)) { return Conversion.Boxing; } if (HasImplicitPointerToVoidConversion(source, destination)) { return Conversion.PointerToVoid; } if (HasImplicitPointerConversion(source, destination, ref useSiteInfo)) { return Conversion.ImplicitPointer; } var tupleConversion = ClassifyImplicitTupleConversion(source, destination, ref useSiteInfo); if (tupleConversion.Exists) { return tupleConversion; } return Conversion.NoConversion; } private Conversion ClassifyImplicitBuiltInConversionSlow(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsVoidType() || destination.IsVoidType()) { return Conversion.NoConversion; } Conversion conversion = ClassifyStandardImplicitConversion(source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } return Conversion.NoConversion; } private Conversion GetImplicitUserDefinedConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var conversionResult = AnalyzeImplicitUserDefinedConversions(sourceExpression, source, destination, ref useSiteInfo); return new Conversion(conversionResult, isImplicit: true); } private Conversion ClassifyExplicitBuiltInOnlyConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsVoidType() || destination.IsVoidType()) { return Conversion.NoConversion; } // The call to HasExplicitNumericConversion isn't necessary, because it is always tested // already by the "FastConversion" code. Debug.Assert(!HasExplicitNumericConversion(source, destination)); //if (HasExplicitNumericConversion(source, specialTypeSource, destination, specialTypeDest)) //{ // return Conversion.ExplicitNumeric; //} if (HasSpecialIntPtrConversion(source, destination)) { return Conversion.IntPtr; } if (HasExplicitEnumerationConversion(source, destination)) { return Conversion.ExplicitEnumeration; } var nullableConversion = ClassifyExplicitNullableConversion(source, destination, ref useSiteInfo, forCast); if (nullableConversion.Exists) { return nullableConversion; } if (HasExplicitReferenceConversion(source, destination, ref useSiteInfo)) { return (source.Kind == SymbolKind.DynamicType) ? Conversion.ExplicitDynamic : Conversion.ExplicitReference; } if (HasUnboxingConversion(source, destination, ref useSiteInfo)) { return Conversion.Unboxing; } var tupleConversion = ClassifyExplicitTupleConversion(source, destination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return tupleConversion; } if (HasPointerToPointerConversion(source, destination)) { return Conversion.PointerToPointer; } if (HasPointerToIntegerConversion(source, destination)) { return Conversion.PointerToInteger; } if (HasIntegerToPointerConversion(source, destination)) { return Conversion.IntegerToPointer; } if (HasExplicitDynamicConversion(source, destination)) { return Conversion.ExplicitDynamic; } return Conversion.NoConversion; } private Conversion GetExplicitUserDefinedConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { UserDefinedConversionResult conversionResult = AnalyzeExplicitUserDefinedConversions(sourceExpression, source, destination, ref useSiteInfo); return new Conversion(conversionResult, isImplicit: false); } private Conversion DeriveStandardExplicitFromOppositeStandardImplicitConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var oppositeConversion = ClassifyStandardImplicitConversion(destination, source, ref useSiteInfo); Conversion impliedExplicitConversion; switch (oppositeConversion.Kind) { case ConversionKind.Identity: impliedExplicitConversion = Conversion.Identity; break; case ConversionKind.ImplicitNumeric: impliedExplicitConversion = Conversion.ExplicitNumeric; break; case ConversionKind.ImplicitReference: impliedExplicitConversion = Conversion.ExplicitReference; break; case ConversionKind.Boxing: impliedExplicitConversion = Conversion.Unboxing; break; case ConversionKind.NoConversion: impliedExplicitConversion = Conversion.NoConversion; break; case ConversionKind.ImplicitPointerToVoid: impliedExplicitConversion = Conversion.PointerToPointer; break; case ConversionKind.ImplicitTuple: // only implicit tuple conversions are standard conversions, // having implicit conversion in the other direction does not help here. impliedExplicitConversion = Conversion.NoConversion; break; case ConversionKind.ImplicitNullable: var strippedSource = source.StrippedType(); var strippedDestination = destination.StrippedType(); var underlyingConversion = DeriveStandardExplicitFromOppositeStandardImplicitConversion(strippedSource, strippedDestination, ref useSiteInfo); // the opposite underlying conversion may not exist // for example if underlying conversion is implicit tuple impliedExplicitConversion = underlyingConversion.Exists ? Conversion.MakeNullableConversion(ConversionKind.ExplicitNullable, underlyingConversion) : Conversion.NoConversion; break; default: throw ExceptionUtilities.UnexpectedValue(oppositeConversion.Kind); } return impliedExplicitConversion; } /// <summary> /// IsBaseInterface returns true if baseType is on the base interface list of derivedType or /// any base class of derivedType. It may be on the base interface list either directly or /// indirectly. /// * baseType must be an interface. /// * type parameters do not have base interfaces. (They have an "effective interface list".) /// * an interface is not a base of itself. /// * this does not check for variance conversions; if a type inherits from /// IEnumerable&lt;string> then IEnumerable&lt;object> is not a base interface. /// </summary> public bool IsBaseInterface(TypeSymbol baseType, TypeSymbol derivedType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)baseType != null); Debug.Assert((object)derivedType != null); if (!baseType.IsInterfaceType()) { return false; } var d = derivedType as NamedTypeSymbol; if ((object)d == null) { return false; } foreach (var iface in d.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(iface, baseType)) { return true; } } return false; } // IsBaseClass returns true if and only if baseType is a base class of derivedType, period. // // * interfaces do not have base classes. (Structs, enums and classes other than object do.) // * a class is not a base class of itself // * type parameters do not have base classes. (They have "effective base classes".) // * all base classes must be classes // * dynamics are removed; if we have class D : B<dynamic> then B<object> is a // base class of D. However, dynamic is never a base class of anything. public bool IsBaseClass(TypeSymbol derivedType, TypeSymbol baseType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)derivedType != null); Debug.Assert((object)baseType != null); // A base class has got to be a class. The derived type might be a struct, enum, or delegate. if (!baseType.IsClassType()) { return false; } for (TypeSymbol b = derivedType.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); (object)b != null; b = b.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(b, baseType)) { return true; } } return false; } /// <summary> /// returns true when implicit conversion is not necessarily the same as explicit conversion /// </summary> private static bool ExplicitConversionMayDifferFromImplicit(Conversion implicitConversion) { switch (implicitConversion.Kind) { case ConversionKind.ImplicitUserDefined: case ConversionKind.ImplicitDynamic: case ConversionKind.ImplicitTuple: case ConversionKind.ImplicitTupleLiteral: case ConversionKind.ImplicitNullable: case ConversionKind.ConditionalExpression: return true; default: return false; } } private Conversion ClassifyImplicitBuiltInConversionFromExpression(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert(sourceExpression == null || (object)sourceExpression.Type == (object)source); Debug.Assert((object)destination != null); if (HasImplicitDynamicConversionFromExpression(source, destination)) { return Conversion.ImplicitDynamic; } // The following conversions only exist for certain form of expressions, // if we have no expression none if them is applicable. if (sourceExpression == null) { return Conversion.NoConversion; } if (HasImplicitEnumerationConversion(sourceExpression, destination)) { return Conversion.ImplicitEnumeration; } var constantConversion = ClassifyImplicitConstantExpressionConversion(sourceExpression, destination); if (constantConversion.Exists) { return constantConversion; } switch (sourceExpression.Kind) { case BoundKind.Literal: var nullLiteralConversion = ClassifyNullLiteralConversion(sourceExpression, destination); if (nullLiteralConversion.Exists) { return nullLiteralConversion; } break; case BoundKind.DefaultLiteral: return Conversion.DefaultLiteral; case BoundKind.ExpressionWithNullability: { var innerExpression = ((BoundExpressionWithNullability)sourceExpression).Expression; var innerConversion = ClassifyImplicitBuiltInConversionFromExpression(innerExpression, innerExpression.Type, destination, ref useSiteInfo); if (innerConversion.Exists) { return innerConversion; } break; } case BoundKind.TupleLiteral: var tupleConversion = ClassifyImplicitTupleLiteralConversion((BoundTupleLiteral)sourceExpression, destination, ref useSiteInfo); if (tupleConversion.Exists) { return tupleConversion; } break; case BoundKind.UnboundLambda: if (HasAnonymousFunctionConversion(sourceExpression, destination)) { return Conversion.AnonymousFunction; } break; case BoundKind.MethodGroup: Conversion methodGroupConversion = GetMethodGroupDelegateConversion((BoundMethodGroup)sourceExpression, destination, ref useSiteInfo); if (methodGroupConversion.Exists) { return methodGroupConversion; } break; case BoundKind.UnconvertedInterpolatedString: Conversion interpolatedStringConversion = GetInterpolatedStringConversion((BoundUnconvertedInterpolatedString)sourceExpression, destination, ref useSiteInfo); if (interpolatedStringConversion.Exists) { return interpolatedStringConversion; } break; case BoundKind.StackAllocArrayCreation: var stackAllocConversion = GetStackAllocConversion((BoundStackAllocArrayCreation)sourceExpression, destination, ref useSiteInfo); if (stackAllocConversion.Exists) { return stackAllocConversion; } break; case BoundKind.UnconvertedAddressOfOperator when destination is FunctionPointerTypeSymbol funcPtrType: var addressOfConversion = GetMethodGroupFunctionPointerConversion(((BoundUnconvertedAddressOfOperator)sourceExpression).Operand, funcPtrType, ref useSiteInfo); if (addressOfConversion.Exists) { return addressOfConversion; } break; case BoundKind.ThrowExpression: return Conversion.ImplicitThrow; case BoundKind.UnconvertedObjectCreationExpression: return Conversion.ObjectCreation; } return Conversion.NoConversion; } private Conversion GetSwitchExpressionConversion(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { switch (source) { case BoundConvertedSwitchExpression _: // It has already been subjected to a switch expression conversion. return Conversion.NoConversion; case BoundUnconvertedSwitchExpression switchExpression: var innerConversions = ArrayBuilder<Conversion>.GetInstance(switchExpression.SwitchArms.Length); foreach (var arm in switchExpression.SwitchArms) { var nestedConversion = this.ClassifyImplicitConversionFromExpression(arm.Value, destination, ref useSiteInfo); if (!nestedConversion.Exists) { innerConversions.Free(); return Conversion.NoConversion; } innerConversions.Add(nestedConversion); } return Conversion.MakeSwitchExpression(innerConversions.ToImmutableAndFree()); default: return Conversion.NoConversion; } } private Conversion GetConditionalExpressionConversion(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!(source is BoundUnconvertedConditionalOperator conditionalOperator)) return Conversion.NoConversion; var trueConversion = this.ClassifyImplicitConversionFromExpression(conditionalOperator.Consequence, destination, ref useSiteInfo); if (!trueConversion.Exists) return Conversion.NoConversion; var falseConversion = this.ClassifyImplicitConversionFromExpression(conditionalOperator.Alternative, destination, ref useSiteInfo); if (!falseConversion.Exists) return Conversion.NoConversion; return Conversion.MakeConditionalExpression(ImmutableArray.Create(trueConversion, falseConversion)); } private static Conversion ClassifyNullLiteralConversion(BoundExpression source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!source.IsLiteralNull()) { return Conversion.NoConversion; } // SPEC: An implicit conversion exists from the null literal to any nullable type. if (destination.IsNullableType()) { // The spec defines a "null literal conversion" specifically as a conversion from // null to nullable type. return Conversion.NullLiteral; } // SPEC: An implicit conversion exists from the null literal to any reference type. // SPEC: An implicit conversion exists from the null literal to type parameter T, // SPEC: provided T is known to be a reference type. [...] The conversion [is] classified // SPEC: as implicit reference conversion. if (destination.IsReferenceType) { return Conversion.ImplicitReference; } // SPEC: The set of implicit conversions is extended to include... // SPEC: ... from the null literal to any pointer type. if (destination.IsPointerOrFunctionPointer()) { return Conversion.NullToPointer; } return Conversion.NoConversion; } private static Conversion ClassifyImplicitConstantExpressionConversion(BoundExpression source, TypeSymbol destination) { if (HasImplicitConstantExpressionConversion(source, destination)) { return Conversion.ImplicitConstant; } // strip nullable from the destination // // the following should work and it is an ImplicitNullable conversion // int? x = 1; if (destination.Kind == SymbolKind.NamedType) { var nt = (NamedTypeSymbol)destination; if (nt.OriginalDefinition.GetSpecialTypeSafe() == SpecialType.System_Nullable_T && HasImplicitConstantExpressionConversion(source, nt.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type)) { return new Conversion(ConversionKind.ImplicitNullable, Conversion.ImplicitConstantUnderlying); } } return Conversion.NoConversion; } private Conversion ClassifyImplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var tupleConversion = GetImplicitTupleLiteralConversion(source, destination, ref useSiteInfo); if (tupleConversion.Exists) { return tupleConversion; } // strip nullable from the destination // // the following should work and it is an ImplicitNullable conversion // (int, double)? x = (1,2); if (destination.Kind == SymbolKind.NamedType) { var nt = (NamedTypeSymbol)destination; if (nt.OriginalDefinition.GetSpecialTypeSafe() == SpecialType.System_Nullable_T) { var underlyingTupleConversion = GetImplicitTupleLiteralConversion(source, nt.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type, ref useSiteInfo); if (underlyingTupleConversion.Exists) { return new Conversion(ConversionKind.ImplicitNullable, ImmutableArray.Create(underlyingTupleConversion)); } } } return Conversion.NoConversion; } private Conversion ClassifyExplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { var tupleConversion = GetExplicitTupleLiteralConversion(source, destination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return tupleConversion; } // strip nullable from the destination // // the following should work and it is an ExplicitNullable conversion // var x = ((byte, string)?)(1,null); if (destination.Kind == SymbolKind.NamedType) { var nt = (NamedTypeSymbol)destination; if (nt.OriginalDefinition.GetSpecialTypeSafe() == SpecialType.System_Nullable_T) { var underlyingTupleConversion = GetExplicitTupleLiteralConversion(source, nt.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type, ref useSiteInfo, forCast); if (underlyingTupleConversion.Exists) { return new Conversion(ConversionKind.ExplicitNullable, ImmutableArray.Create(underlyingTupleConversion)); } } } return Conversion.NoConversion; } internal static bool HasImplicitConstantExpressionConversion(BoundExpression source, TypeSymbol destination) { var constantValue = source.ConstantValue; if (constantValue == null || (object)source.Type == null) { return false; } // An implicit constant expression conversion permits the following conversions: // A constant-expression of type int can be converted to type sbyte, byte, short, // ushort, uint, or ulong, provided the value of the constant-expression is within the // range of the destination type. var specialSource = source.Type.GetSpecialTypeSafe(); if (specialSource == SpecialType.System_Int32) { //if the constant value could not be computed, be generous and assume the conversion will work int value = constantValue.IsBad ? 0 : constantValue.Int32Value; switch (destination.GetSpecialTypeSafe()) { case SpecialType.System_Byte: return byte.MinValue <= value && value <= byte.MaxValue; case SpecialType.System_SByte: return sbyte.MinValue <= value && value <= sbyte.MaxValue; case SpecialType.System_Int16: return short.MinValue <= value && value <= short.MaxValue; case SpecialType.System_IntPtr when destination.IsNativeIntegerType: return true; case SpecialType.System_UInt32: case SpecialType.System_UIntPtr when destination.IsNativeIntegerType: return uint.MinValue <= value; case SpecialType.System_UInt64: return (int)ulong.MinValue <= value; case SpecialType.System_UInt16: return ushort.MinValue <= value && value <= ushort.MaxValue; default: return false; } } else if (specialSource == SpecialType.System_Int64 && destination.GetSpecialTypeSafe() == SpecialType.System_UInt64 && (constantValue.IsBad || 0 <= constantValue.Int64Value)) { // A constant-expression of type long can be converted to type ulong, provided the // value of the constant-expression is not negative. return true; } return false; } private Conversion ClassifyExplicitOnlyConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { Debug.Assert(sourceExpression != null); Debug.Assert((object)destination != null); var sourceType = sourceExpression.Type; // NB: need to check for explicit tuple literal conversion before checking for explicit conversion from type // The same literal may have both explicit tuple conversion and explicit tuple literal conversion to the target type. // They are, however, observably different conversions via the order of argument evaluations and element-wise conversions if (sourceExpression.Kind == BoundKind.TupleLiteral) { Conversion tupleConversion = ClassifyExplicitTupleLiteralConversion((BoundTupleLiteral)sourceExpression, destination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return tupleConversion; } } if ((object)sourceType != null) { // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(sourceType, destination); if (fastConversion.Exists) { return fastConversion; } else { var conversion = ClassifyExplicitBuiltInOnlyConversion(sourceType, destination, ref useSiteInfo, forCast); if (conversion.Exists) { return conversion; } } } return GetExplicitUserDefinedConversion(sourceExpression, sourceType, destination, ref useSiteInfo); } #nullable enable private static bool HasImplicitEnumerationConversion(BoundExpression source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: An implicit enumeration conversion permits the decimal-integer-literal 0 to be converted to any enum-type // SPEC: and to any nullable-type whose underlying type is an enum-type. // // For historical reasons we actually allow a conversion from any *numeric constant // zero* to be converted to any enum type, not just the literal integer zero. bool validType = destination.IsEnumType() || destination.IsNullableType() && destination.GetNullableUnderlyingType().IsEnumType(); if (!validType) { return false; } var sourceConstantValue = source.ConstantValue; return sourceConstantValue != null && source.Type is object && IsNumericType(source.Type) && IsConstantNumericZero(sourceConstantValue); } private static LambdaConversionResult IsAnonymousFunctionCompatibleWithDelegate(UnboundLambda anonymousFunction, TypeSymbol type) { Debug.Assert((object)anonymousFunction != null); Debug.Assert((object)type != null); // SPEC: An anonymous-method-expression or lambda-expression is classified as an anonymous function. // SPEC: The expression does not have a type but can be implicitly converted to a compatible delegate // SPEC: type or expression tree type. Specifically, a delegate type D is compatible with an // SPEC: anonymous function F provided: var delegateType = (NamedTypeSymbol)type; var invokeMethod = delegateType.DelegateInvokeMethod; if ((object)invokeMethod == null || invokeMethod.HasUseSiteError) { return LambdaConversionResult.BadTargetType; } if (anonymousFunction.HasExplicitReturnType(out var refKind, out var returnType)) { if (invokeMethod.RefKind != refKind || !invokeMethod.ReturnType.Equals(returnType.Type, TypeCompareKind.AllIgnoreOptions)) { return LambdaConversionResult.MismatchedReturnType; } } var delegateParameters = invokeMethod.Parameters; // SPEC: If F contains an anonymous-function-signature, then D and F have the same number of parameters. // SPEC: If F does not contain an anonymous-function-signature, then D may have zero or more parameters // SPEC: of any type, as long as no parameter of D has the out parameter modifier. if (anonymousFunction.HasSignature) { if (anonymousFunction.ParameterCount != invokeMethod.ParameterCount) { return LambdaConversionResult.BadParameterCount; } // SPEC: If F has an explicitly typed parameter list, each parameter in D has the same type // SPEC: and modifiers as the corresponding parameter in F. // SPEC: If F has an implicitly typed parameter list, D has no ref or out parameters. if (anonymousFunction.HasExplicitlyTypedParameterList) { for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].RefKind != anonymousFunction.RefKind(p) || !delegateParameters[p].Type.Equals(anonymousFunction.ParameterType(p), TypeCompareKind.AllIgnoreOptions)) { return LambdaConversionResult.MismatchedParameterType; } } } else { for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].RefKind != RefKind.None) { return LambdaConversionResult.RefInImplicitlyTypedLambda; } } // In C# it is not possible to make a delegate type // such that one of its parameter types is a static type. But static types are // in metadata just sealed abstract types; there is nothing stopping someone in // another language from creating a delegate with a static type for a parameter, // though the only argument you could pass for that parameter is null. // // In the native compiler we forbid conversion of an anonymous function that has // an implicitly-typed parameter list to a delegate type that has a static type // for a formal parameter type. However, we do *not* forbid it for an explicitly- // typed lambda (because we already require that the explicitly typed parameter not // be static) and we do not forbid it for an anonymous method with the entire // parameter list missing (because the body cannot possibly have a parameter that // is of static type, even though this means that we will be generating a hidden // method with a parameter of static type.) // // We also allow more exotic situations to work in the native compiler. For example, // though it is not possible to convert x=>{} to Action<GC>, it is possible to convert // it to Action<List<GC>> should there be a language that allows you to construct // a variable of that type. // // We might consider beefing up this rule to disallow a conversion of *any* anonymous // function to *any* delegate that has a static type *anywhere* in the parameter list. for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].TypeWithAnnotations.IsStatic) { return LambdaConversionResult.StaticTypeInImplicitlyTypedLambda; } } } } else { for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].RefKind == RefKind.Out) { return LambdaConversionResult.MissingSignatureWithOutParameter; } } } // Ensure the body can be converted to that delegate type var bound = anonymousFunction.Bind(delegateType); if (ErrorFacts.PreventsSuccessfulDelegateConversion(bound.Diagnostics.Diagnostics)) { return LambdaConversionResult.BindingFailed; } return LambdaConversionResult.Success; } private static LambdaConversionResult IsAnonymousFunctionCompatibleWithExpressionTree(UnboundLambda anonymousFunction, NamedTypeSymbol type) { Debug.Assert((object)anonymousFunction != null); Debug.Assert((object)type != null); Debug.Assert(type.IsGenericOrNonGenericExpressionType(out _)); // SPEC OMISSION: // // The C# 3 spec said that anonymous methods and statement lambdas are *convertible* to expression tree // types if the anonymous method/statement lambda is convertible to its delegate type; however, actually // *using* such a conversion is an error. However, that is not what we implemented. In C# 3 we implemented // that an anonymous method is *not convertible* to an expression tree type, period. (Statement lambdas // used the rule described in the spec.) // // This appears to be a spec omission; the intention is to make old-style anonymous methods not // convertible to expression trees. var delegateType = type.Arity == 0 ? null : type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type; if (delegateType is { } && !delegateType.IsDelegateType()) { return LambdaConversionResult.ExpressionTreeMustHaveDelegateTypeArgument; } if (anonymousFunction.Syntax.Kind() == SyntaxKind.AnonymousMethodExpression) { return LambdaConversionResult.ExpressionTreeFromAnonymousMethod; } if (delegateType is null) { return LambdaConversionResult.Success; } return IsAnonymousFunctionCompatibleWithDelegate(anonymousFunction, delegateType); } public static LambdaConversionResult IsAnonymousFunctionCompatibleWithType(UnboundLambda anonymousFunction, TypeSymbol type) { Debug.Assert((object)anonymousFunction != null); Debug.Assert((object)type != null); if (type.SpecialType == SpecialType.System_Delegate) { return LambdaConversionResult.Success; } else if (type.IsDelegateType()) { return IsAnonymousFunctionCompatibleWithDelegate(anonymousFunction, type); } else if (type.IsGenericOrNonGenericExpressionType(out bool _)) { return IsAnonymousFunctionCompatibleWithExpressionTree(anonymousFunction, (NamedTypeSymbol)type); } return LambdaConversionResult.BadTargetType; } private static bool HasAnonymousFunctionConversion(BoundExpression source, TypeSymbol destination) { Debug.Assert(source != null); Debug.Assert((object)destination != null); if (source.Kind != BoundKind.UnboundLambda) { return false; } return IsAnonymousFunctionCompatibleWithType((UnboundLambda)source, destination) == LambdaConversionResult.Success; } #nullable disable internal Conversion ClassifyImplicitUserDefinedConversionForV6SwitchGoverningType(TypeSymbol sourceType, out TypeSymbol switchGoverningType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The governing type of a switch statement is established by the switch expression. // SPEC: 1) If the type of the switch expression is sbyte, byte, short, ushort, int, uint, // SPEC: long, ulong, bool, char, string, or an enum-type, or if it is the nullable type // SPEC: corresponding to one of these types, then that is the governing type of the switch statement. // SPEC: 2) Otherwise, exactly one user-defined implicit conversion (§6.4) must exist from the // SPEC: type of the switch expression to one of the following possible governing types: // SPEC: sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or, a nullable type // SPEC: corresponding to one of those types // NOTE: We should be called only if (1) is false for source type. Debug.Assert((object)sourceType != null); Debug.Assert(!sourceType.IsValidV6SwitchGoverningType()); UserDefinedConversionResult result = AnalyzeImplicitUserDefinedConversionForV6SwitchGoverningType(sourceType, ref useSiteInfo); if (result.Kind == UserDefinedConversionResultKind.Valid) { UserDefinedConversionAnalysis analysis = result.Results[result.Best]; switchGoverningType = analysis.ToType; Debug.Assert(switchGoverningType.IsValidV6SwitchGoverningType(isTargetTypeOfUserDefinedOp: true)); } else { switchGoverningType = null; } return new Conversion(result, isImplicit: true); } internal Conversion GetCallerLineNumberConversion(TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var greenNode = new Syntax.InternalSyntax.LiteralExpressionSyntax(SyntaxKind.NumericLiteralExpression, new Syntax.InternalSyntax.SyntaxToken(SyntaxKind.NumericLiteralToken)); var syntaxNode = new LiteralExpressionSyntax(greenNode, null, 0); TypeSymbol expectedAttributeType = corLibrary.GetSpecialType(SpecialType.System_Int32); BoundLiteral intMaxValueLiteral = new BoundLiteral(syntaxNode, ConstantValue.Create(int.MaxValue), expectedAttributeType); return ClassifyStandardImplicitConversion(intMaxValueLiteral, expectedAttributeType, destination, ref useSiteInfo); } internal bool HasCallerLineNumberConversion(TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return GetCallerLineNumberConversion(destination, ref useSiteInfo).Exists; } internal bool HasCallerInfoStringConversion(TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { TypeSymbol expectedAttributeType = corLibrary.GetSpecialType(SpecialType.System_String); Conversion conversion = ClassifyStandardImplicitConversion(expectedAttributeType, destination, ref useSiteInfo); return conversion.Exists; } public static bool HasIdentityConversion(TypeSymbol type1, TypeSymbol type2) { return HasIdentityConversionInternal(type1, type2, includeNullability: false); } private static bool HasIdentityConversionInternal(TypeSymbol type1, TypeSymbol type2, bool includeNullability) { // Spec (6.1.1): // An identity conversion converts from any type to the same type. This conversion exists // such that an entity that already has a required type can be said to be convertible to // that type. // // Because object and dynamic are considered equivalent there is an identity conversion // between object and dynamic, and between constructed types that are the same when replacing // all occurrences of dynamic with object. Debug.Assert((object)type1 != null); Debug.Assert((object)type2 != null); // Note, when we are paying attention to nullability, we ignore oblivious mismatch. // See TypeCompareKind.ObliviousNullableModifierMatchesAny var compareKind = includeNullability ? TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes : TypeCompareKind.AllIgnoreOptions; return type1.Equals(type2, compareKind); } private bool HasIdentityConversionInternal(TypeSymbol type1, TypeSymbol type2) { return HasIdentityConversionInternal(type1, type2, IncludeNullability); } /// <summary> /// Returns true if: /// - Either type has no nullability information (oblivious). /// - Both types cannot have different nullability at the same time, /// including the case of type parameters that by themselves can represent nullable and not nullable reference types. /// </summary> internal bool HasTopLevelNullabilityIdentityConversion(TypeWithAnnotations source, TypeWithAnnotations destination) { if (!IncludeNullability) { return true; } if (source.NullableAnnotation.IsOblivious() || destination.NullableAnnotation.IsOblivious()) { return true; } var sourceIsPossiblyNullableTypeParameter = IsPossiblyNullableTypeTypeParameter(source); var destinationIsPossiblyNullableTypeParameter = IsPossiblyNullableTypeTypeParameter(destination); if (sourceIsPossiblyNullableTypeParameter && !destinationIsPossiblyNullableTypeParameter) { return destination.NullableAnnotation.IsAnnotated(); } if (destinationIsPossiblyNullableTypeParameter && !sourceIsPossiblyNullableTypeParameter) { return source.NullableAnnotation.IsAnnotated(); } return source.NullableAnnotation.IsAnnotated() == destination.NullableAnnotation.IsAnnotated(); } /// <summary> /// Returns false if source type can be nullable at the same time when destination type can be not nullable, /// including the case of type parameters that by themselves can represent nullable and not nullable reference types. /// When either type has no nullability information (oblivious), this method returns true. /// </summary> internal bool HasTopLevelNullabilityImplicitConversion(TypeWithAnnotations source, TypeWithAnnotations destination) { if (!IncludeNullability) { return true; } if (source.NullableAnnotation.IsOblivious() || destination.NullableAnnotation.IsOblivious() || destination.NullableAnnotation.IsAnnotated()) { return true; } if (IsPossiblyNullableTypeTypeParameter(source) && !IsPossiblyNullableTypeTypeParameter(destination)) { return false; } return !source.NullableAnnotation.IsAnnotated(); } private static bool IsPossiblyNullableTypeTypeParameter(in TypeWithAnnotations typeWithAnnotations) { var type = typeWithAnnotations.Type; return type is object && (type.IsPossiblyNullableReferenceTypeTypeParameter() || type.IsNullableTypeOrTypeParameter()); } /// <summary> /// Returns false if the source does not have an implicit conversion to the destination /// because of either incompatible top level or nested nullability. /// </summary> public bool HasAnyNullabilityImplicitConversion(TypeWithAnnotations source, TypeWithAnnotations destination) { Debug.Assert(IncludeNullability); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return HasTopLevelNullabilityImplicitConversion(source, destination) && ClassifyImplicitConversionFromType(source.Type, destination.Type, ref discardedUseSiteInfo).Kind != ConversionKind.NoConversion; } public static bool HasIdentityConversionToAny<T>(T type, ArrayBuilder<T> targetTypes) where T : TypeSymbol { foreach (var targetType in targetTypes) { if (HasIdentityConversionInternal(type, targetType, includeNullability: false)) { return true; } } return false; } public Conversion ConvertExtensionMethodThisArg(TypeSymbol parameterType, TypeSymbol thisType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)thisType != null); var conversion = this.ClassifyImplicitExtensionMethodThisArgConversion(null, thisType, parameterType, ref useSiteInfo); return IsValidExtensionMethodThisArgConversion(conversion) ? conversion : Conversion.NoConversion; } // Spec 7.6.5.2: "An extension method ... is eligible if ... [an] implicit identity, reference, // or boxing conversion exists from expr to the type of the first parameter" public Conversion ClassifyImplicitExtensionMethodThisArgConversion(BoundExpression sourceExpressionOpt, TypeSymbol sourceType, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpressionOpt == null || (object)sourceExpressionOpt.Type == sourceType); Debug.Assert((object)destination != null); if ((object)sourceType != null) { if (HasIdentityConversionInternal(sourceType, destination)) { return Conversion.Identity; } if (HasBoxingConversion(sourceType, destination, ref useSiteInfo)) { return Conversion.Boxing; } if (HasImplicitReferenceConversion(sourceType, destination, ref useSiteInfo)) { return Conversion.ImplicitReference; } } if (sourceExpressionOpt?.Kind == BoundKind.TupleLiteral) { // GetTupleLiteralConversion is not used with IncludeNullability currently. // If that changes, the delegate below will need to consider top-level nullability. Debug.Assert(!IncludeNullability); var tupleConversion = GetTupleLiteralConversion( (BoundTupleLiteral)sourceExpressionOpt, destination, ref useSiteInfo, ConversionKind.ImplicitTupleLiteral, (ConversionsBase conversions, BoundExpression s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => conversions.ClassifyImplicitExtensionMethodThisArgConversion(s, s.Type, d.Type, ref u), arg: false); if (tupleConversion.Exists) { return tupleConversion; } } if ((object)sourceType != null) { var tupleConversion = ClassifyTupleConversion( sourceType, destination, ref useSiteInfo, ConversionKind.ImplicitTuple, (ConversionsBase conversions, TypeWithAnnotations s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => { if (!conversions.HasTopLevelNullabilityImplicitConversion(s, d)) { return Conversion.NoConversion; } return conversions.ClassifyImplicitExtensionMethodThisArgConversion(null, s.Type, d.Type, ref u); }, arg: false); if (tupleConversion.Exists) { return tupleConversion; } } return Conversion.NoConversion; } // It should be possible to remove IsValidExtensionMethodThisArgConversion // since ClassifyImplicitExtensionMethodThisArgConversion should only // return valid conversions. https://github.com/dotnet/roslyn/issues/19622 // Spec 7.6.5.2: "An extension method ... is eligible if ... [an] implicit identity, reference, // or boxing conversion exists from expr to the type of the first parameter" public static bool IsValidExtensionMethodThisArgConversion(Conversion conversion) { switch (conversion.Kind) { case ConversionKind.Identity: case ConversionKind.Boxing: case ConversionKind.ImplicitReference: return true; case ConversionKind.ImplicitTuple: case ConversionKind.ImplicitTupleLiteral: // check if all element conversions satisfy the requirement foreach (var elementConversion in conversion.UnderlyingConversions) { if (!IsValidExtensionMethodThisArgConversion(elementConversion)) { return false; } } return true; default: // Caller should have not have calculated another conversion. Debug.Assert(conversion.Kind == ConversionKind.NoConversion); return false; } } private const bool F = false; private const bool T = true; // Notice that there is no implicit numeric conversion from a type to itself. That's an // identity conversion. private static readonly bool[,] s_implicitNumericConversions = { // to sb b s us i ui l ul c f d m // from /* sb */ { F, F, T, F, T, F, T, F, F, T, T, T }, /* b */ { F, F, T, T, T, T, T, T, F, T, T, T }, /* s */ { F, F, F, F, T, F, T, F, F, T, T, T }, /* us */ { F, F, F, F, T, T, T, T, F, T, T, T }, /* i */ { F, F, F, F, F, F, T, F, F, T, T, T }, /* ui */ { F, F, F, F, F, F, T, T, F, T, T, T }, /* l */ { F, F, F, F, F, F, F, F, F, T, T, T }, /* ul */ { F, F, F, F, F, F, F, F, F, T, T, T }, /* c */ { F, F, F, T, T, T, T, T, F, T, T, T }, /* f */ { F, F, F, F, F, F, F, F, F, F, T, F }, /* d */ { F, F, F, F, F, F, F, F, F, F, F, F }, /* m */ { F, F, F, F, F, F, F, F, F, F, F, F } }; private static readonly bool[,] s_explicitNumericConversions = { // to sb b s us i ui l ul c f d m // from /* sb */ { F, T, F, T, F, T, F, T, T, F, F, F }, /* b */ { T, F, F, F, F, F, F, F, T, F, F, F }, /* s */ { T, T, F, T, F, T, F, T, T, F, F, F }, /* us */ { T, T, T, F, F, F, F, F, T, F, F, F }, /* i */ { T, T, T, T, F, T, F, T, T, F, F, F }, /* ui */ { T, T, T, T, T, F, F, F, T, F, F, F }, /* l */ { T, T, T, T, T, T, F, T, T, F, F, F }, /* ul */ { T, T, T, T, T, T, T, F, T, F, F, F }, /* c */ { T, T, T, F, F, F, F, F, F, F, F, F }, /* f */ { T, T, T, T, T, T, T, T, T, F, F, T }, /* d */ { T, T, T, T, T, T, T, T, T, T, F, T }, /* m */ { T, T, T, T, T, T, T, T, T, T, T, F } }; private static int GetNumericTypeIndex(SpecialType specialType) { switch (specialType) { case SpecialType.System_SByte: return 0; case SpecialType.System_Byte: return 1; case SpecialType.System_Int16: return 2; case SpecialType.System_UInt16: return 3; case SpecialType.System_Int32: return 4; case SpecialType.System_UInt32: return 5; case SpecialType.System_Int64: return 6; case SpecialType.System_UInt64: return 7; case SpecialType.System_Char: return 8; case SpecialType.System_Single: return 9; case SpecialType.System_Double: return 10; case SpecialType.System_Decimal: return 11; default: return -1; } } #nullable enable private static bool HasImplicitNumericConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); int sourceIndex = GetNumericTypeIndex(source.SpecialType); if (sourceIndex < 0) { return false; } int destinationIndex = GetNumericTypeIndex(destination.SpecialType); if (destinationIndex < 0) { return false; } return s_implicitNumericConversions[sourceIndex, destinationIndex]; } private static bool HasExplicitNumericConversion(TypeSymbol source, TypeSymbol destination) { // SPEC: The explicit numeric conversions are the conversions from a numeric-type to another // SPEC: numeric-type for which an implicit numeric conversion does not already exist. Debug.Assert((object)source != null); Debug.Assert((object)destination != null); int sourceIndex = GetNumericTypeIndex(source.SpecialType); if (sourceIndex < 0) { return false; } int destinationIndex = GetNumericTypeIndex(destination.SpecialType); if (destinationIndex < 0) { return false; } return s_explicitNumericConversions[sourceIndex, destinationIndex]; } private static bool IsConstantNumericZero(ConstantValue value) { switch (value.Discriminator) { case ConstantValueTypeDiscriminator.SByte: return value.SByteValue == 0; case ConstantValueTypeDiscriminator.Byte: return value.ByteValue == 0; case ConstantValueTypeDiscriminator.Int16: return value.Int16Value == 0; case ConstantValueTypeDiscriminator.Int32: case ConstantValueTypeDiscriminator.NInt: return value.Int32Value == 0; case ConstantValueTypeDiscriminator.Int64: return value.Int64Value == 0; case ConstantValueTypeDiscriminator.UInt16: return value.UInt16Value == 0; case ConstantValueTypeDiscriminator.UInt32: case ConstantValueTypeDiscriminator.NUInt: return value.UInt32Value == 0; case ConstantValueTypeDiscriminator.UInt64: return value.UInt64Value == 0; case ConstantValueTypeDiscriminator.Single: case ConstantValueTypeDiscriminator.Double: return value.DoubleValue == 0; case ConstantValueTypeDiscriminator.Decimal: return value.DecimalValue == 0; } return false; } private static bool IsNumericType(TypeSymbol type) { switch (type.SpecialType) { case SpecialType.System_Char: case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: case SpecialType.System_IntPtr when type.IsNativeIntegerType: case SpecialType.System_UIntPtr when type.IsNativeIntegerType: return true; default: return false; } } private static bool HasSpecialIntPtrConversion(TypeSymbol source, TypeSymbol target) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); // There are only a total of twelve user-defined explicit conversions on IntPtr and UIntPtr: // // IntPtr <---> int // IntPtr <---> long // IntPtr <---> void* // UIntPtr <---> uint // UIntPtr <---> ulong // UIntPtr <---> void* // // The specification says that you can put any *standard* implicit or explicit conversion // on "either side" of a user-defined explicit conversion, so the specification allows, say, // UIntPtr --> byte because the conversion UIntPtr --> uint is user-defined and the // conversion uint --> byte is "standard". It is "standard" because the conversion // byte --> uint is an implicit numeric conversion. // This means that certain conversions should be illegal. For example, IntPtr --> ulong // should be illegal because none of int --> ulong, long --> ulong and void* --> ulong // are "standard" conversions. // Similarly, some conversions involving IntPtr should be illegal because they are // ambiguous. byte --> IntPtr?, for example, is ambiguous. (There are four possible // UD operators: int --> IntPtr and long --> IntPtr, and their lifted versions. The // best possible source type is int, the best possible target type is IntPtr?, and // there is an ambiguity between the unlifted int --> IntPtr, and the lifted // int? --> IntPtr? conversions.) // In practice, the native compiler, and hence, the Roslyn compiler, allows all // these conversions. Any conversion from a numeric type to IntPtr, or from an IntPtr // to a numeric type, is allowed. Also, any conversion from a pointer type to IntPtr // or vice versa is allowed. var s0 = source.StrippedType(); var t0 = target.StrippedType(); TypeSymbol otherType; if (isIntPtrOrUIntPtr(s0)) { otherType = t0; } else if (isIntPtrOrUIntPtr(t0)) { otherType = s0; } else { return false; } if (otherType.IsPointerOrFunctionPointer()) { return true; } if (otherType.TypeKind == TypeKind.Enum) { return true; } switch (otherType.SpecialType) { case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Char: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Double: case SpecialType.System_Single: case SpecialType.System_Decimal: return true; } return false; static bool isIntPtrOrUIntPtr(TypeSymbol type) => (type.SpecialType == SpecialType.System_IntPtr || type.SpecialType == SpecialType.System_UIntPtr) && !type.IsNativeIntegerType; } private static bool HasExplicitEnumerationConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: The explicit enumeration conversions are: // SPEC: From sbyte, byte, short, ushort, int, uint, long, ulong, nint, nuint, char, float, double, or decimal to any enum-type. // SPEC: From any enum-type to sbyte, byte, short, ushort, int, uint, long, ulong, nint, nuint, char, float, double, or decimal. // SPEC: From any enum-type to any other enum-type. if (IsNumericType(source) && destination.IsEnumType()) { return true; } if (IsNumericType(destination) && source.IsEnumType()) { return true; } if (source.IsEnumType() && destination.IsEnumType()) { return true; } return false; } #nullable disable private Conversion ClassifyImplicitNullableConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: Predefined implicit conversions that operate on non-nullable value types can also be used with // SPEC: nullable forms of those types. For each of the predefined implicit identity, numeric and tuple conversions // SPEC: that convert from a non-nullable value type S to a non-nullable value type T, the following implicit // SPEC: nullable conversions exist: // SPEC: * An implicit conversion from S? to T?. // SPEC: * An implicit conversion from S to T?. if (!destination.IsNullableType()) { return Conversion.NoConversion; } TypeSymbol unwrappedDestination = destination.GetNullableUnderlyingType(); TypeSymbol unwrappedSource = source.StrippedType(); if (!unwrappedSource.IsValueType) { return Conversion.NoConversion; } if (HasIdentityConversionInternal(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ImplicitNullable, Conversion.IdentityUnderlying); } if (HasImplicitNumericConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ImplicitNullable, Conversion.ImplicitNumericUnderlying); } var tupleConversion = ClassifyImplicitTupleConversion(unwrappedSource, unwrappedDestination, ref useSiteInfo); if (tupleConversion.Exists) { return new Conversion(ConversionKind.ImplicitNullable, ImmutableArray.Create(tupleConversion)); } return Conversion.NoConversion; } private delegate Conversion ClassifyConversionFromExpressionDelegate(ConversionsBase conversions, BoundExpression sourceExpression, TypeWithAnnotations destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool arg); private delegate Conversion ClassifyConversionFromTypeDelegate(ConversionsBase conversions, TypeWithAnnotations source, TypeWithAnnotations destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool arg); private Conversion GetImplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // GetTupleLiteralConversion is not used with IncludeNullability currently. // If that changes, the delegate below will need to consider top-level nullability. Debug.Assert(!IncludeNullability); return GetTupleLiteralConversion( source, destination, ref useSiteInfo, ConversionKind.ImplicitTupleLiteral, (ConversionsBase conversions, BoundExpression s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => conversions.ClassifyImplicitConversionFromExpression(s, d.Type, ref u), arg: false); } private Conversion GetExplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { // GetTupleLiteralConversion is not used with IncludeNullability currently. // If that changes, the delegate below will need to consider top-level nullability. Debug.Assert(!IncludeNullability); return GetTupleLiteralConversion( source, destination, ref useSiteInfo, ConversionKind.ExplicitTupleLiteral, (ConversionsBase conversions, BoundExpression s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => conversions.ClassifyConversionFromExpression(s, d.Type, ref u, a), forCast); } private Conversion GetTupleLiteralConversion( BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConversionKind kind, ClassifyConversionFromExpressionDelegate classifyConversion, bool arg) { var arguments = source.Arguments; // check if the type is actually compatible type for a tuple of given cardinality if (!destination.IsTupleTypeOfCardinality(arguments.Length)) { return Conversion.NoConversion; } var targetElementTypes = destination.TupleElementTypesWithAnnotations; Debug.Assert(arguments.Length == targetElementTypes.Length); // check arguments against flattened list of target element types var argumentConversions = ArrayBuilder<Conversion>.GetInstance(arguments.Length); for (int i = 0; i < arguments.Length; i++) { var argument = arguments[i]; var result = classifyConversion(this, argument, targetElementTypes[i], ref useSiteInfo, arg); if (!result.Exists) { argumentConversions.Free(); return Conversion.NoConversion; } argumentConversions.Add(result); } return new Conversion(kind, argumentConversions.ToImmutableAndFree()); } private Conversion ClassifyImplicitTupleConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ClassifyTupleConversion( source, destination, ref useSiteInfo, ConversionKind.ImplicitTuple, (ConversionsBase conversions, TypeWithAnnotations s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => { if (!conversions.HasTopLevelNullabilityImplicitConversion(s, d)) { return Conversion.NoConversion; } return conversions.ClassifyImplicitConversionFromType(s.Type, d.Type, ref u); }, arg: false); } private Conversion ClassifyExplicitTupleConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { return ClassifyTupleConversion( source, destination, ref useSiteInfo, ConversionKind.ExplicitTuple, (ConversionsBase conversions, TypeWithAnnotations s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => { if (!conversions.HasTopLevelNullabilityImplicitConversion(s, d)) { return Conversion.NoConversion; } return conversions.ClassifyConversionFromType(s.Type, d.Type, ref u, a); }, forCast); } private Conversion ClassifyTupleConversion( TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConversionKind kind, ClassifyConversionFromTypeDelegate classifyConversion, bool arg) { ImmutableArray<TypeWithAnnotations> sourceTypes; ImmutableArray<TypeWithAnnotations> destTypes; if (!source.TryGetElementTypesWithAnnotationsIfTupleType(out sourceTypes) || !destination.TryGetElementTypesWithAnnotationsIfTupleType(out destTypes) || sourceTypes.Length != destTypes.Length) { return Conversion.NoConversion; } var nestedConversions = ArrayBuilder<Conversion>.GetInstance(sourceTypes.Length); for (int i = 0; i < sourceTypes.Length; i++) { var conversion = classifyConversion(this, sourceTypes[i], destTypes[i], ref useSiteInfo, arg); if (!conversion.Exists) { nestedConversions.Free(); return Conversion.NoConversion; } nestedConversions.Add(conversion); } return new Conversion(kind, nestedConversions.ToImmutableAndFree()); } private Conversion ClassifyExplicitNullableConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: Explicit nullable conversions permit predefined explicit conversions that operate on // SPEC: non-nullable value types to also be used with nullable forms of those types. For // SPEC: each of the predefined explicit conversions that convert from a non-nullable value type // SPEC: S to a non-nullable value type T, the following nullable conversions exist: // SPEC: An explicit conversion from S? to T?. // SPEC: An explicit conversion from S to T?. // SPEC: An explicit conversion from S? to T. if (!source.IsNullableType() && !destination.IsNullableType()) { return Conversion.NoConversion; } TypeSymbol unwrappedSource = source.StrippedType(); TypeSymbol unwrappedDestination = destination.StrippedType(); if (HasIdentityConversionInternal(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.IdentityUnderlying); } if (HasImplicitNumericConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.ImplicitNumericUnderlying); } if (HasExplicitNumericConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.ExplicitNumericUnderlying); } var tupleConversion = ClassifyExplicitTupleConversion(unwrappedSource, unwrappedDestination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return new Conversion(ConversionKind.ExplicitNullable, ImmutableArray.Create(tupleConversion)); } if (HasExplicitEnumerationConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.ExplicitEnumerationUnderlying); } if (HasPointerToIntegerConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.PointerToIntegerUnderlying); } return Conversion.NoConversion; } private bool HasCovariantArrayConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); var s = source as ArrayTypeSymbol; var d = destination as ArrayTypeSymbol; if ((object)s == null || (object)d == null) { return false; } // * S and T differ only in element type. In other words, S and T have the same number of dimensions. if (!s.HasSameShapeAs(d)) { return false; } // * Both SE and TE are reference types. // * An implicit reference conversion exists from SE to TE. return HasImplicitReferenceConversion(s.ElementTypeWithAnnotations, d.ElementTypeWithAnnotations, ref useSiteInfo); } public bool HasIdentityOrImplicitReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return true; } return HasImplicitReferenceConversion(source, destination, ref useSiteInfo); } private static bool HasImplicitDynamicConversionFromExpression(TypeSymbol expressionType, TypeSymbol destination) { // Spec (§6.1.8) // An implicit dynamic conversion exists from an expression of type dynamic to any type T. Debug.Assert((object)destination != null); return expressionType?.Kind == SymbolKind.DynamicType && !destination.IsPointerOrFunctionPointer(); } private static bool HasExplicitDynamicConversion(TypeSymbol source, TypeSymbol destination) { // SPEC: An explicit dynamic conversion exists from an expression of [sic] type dynamic to any type T. // ISSUE: The "an expression of" part of the spec is probably an error; see https://github.com/dotnet/csharplang/issues/132 Debug.Assert((object)source != null); Debug.Assert((object)destination != null); return source.Kind == SymbolKind.DynamicType && !destination.IsPointerOrFunctionPointer(); } private bool HasArrayConversionToInterface(ArrayTypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!source.IsSZArray) { return false; } if (!destination.IsInterfaceType()) { return false; } // The specification says that there is a conversion: // * From a single-dimensional array type S[] to IList<T> and its base // interfaces, provided that there is an implicit identity or reference // conversion from S to T. // // Newer versions of the framework also have arrays be convertible to // IReadOnlyList<T> and IReadOnlyCollection<T>; we honor that as well. // // Therefore we must check for: // // IList<T> // ICollection<T> // IEnumerable<T> // IEnumerable // IReadOnlyList<T> // IReadOnlyCollection<T> if (destination.SpecialType == SpecialType.System_Collections_IEnumerable) { return true; } NamedTypeSymbol destinationAgg = (NamedTypeSymbol)destination; if (destinationAgg.AllTypeArgumentCount() != 1) { return false; } if (!destinationAgg.IsPossibleArrayGenericInterface()) { return false; } TypeWithAnnotations elementType = source.ElementTypeWithAnnotations; TypeWithAnnotations argument0 = destinationAgg.TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo); if (IncludeNullability && !HasTopLevelNullabilityImplicitConversion(elementType, argument0)) { return false; } return HasIdentityOrImplicitReferenceConversion(elementType.Type, argument0.Type, ref useSiteInfo); } private bool HasImplicitReferenceConversion(TypeWithAnnotations source, TypeWithAnnotations destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (IncludeNullability) { if (!HasTopLevelNullabilityImplicitConversion(source, destination)) { return false; } // Check for identity conversion of underlying types if the top-level nullability is distinct. // (An identity conversion where nullability matches is not considered an implicit reference conversion.) if (source.NullableAnnotation != destination.NullableAnnotation && HasIdentityConversionInternal(source.Type, destination.Type, includeNullability: true)) { return true; } } return HasImplicitReferenceConversion(source.Type, destination.Type, ref useSiteInfo); } internal bool HasImplicitReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsErrorType()) { return false; } if (!source.IsReferenceType) { return false; } // SPEC: The implicit reference conversions are: // SPEC: UNDONE: From any reference-type to a reference-type T if it has an implicit identity // SPEC: UNDONE: or reference conversion to a reference-type T0 and T0 has an identity conversion to T. // UNDONE: Is the right thing to do here to strip dynamic off and check for convertibility? // SPEC: From any reference type to object and dynamic. if (destination.SpecialType == SpecialType.System_Object || destination.Kind == SymbolKind.DynamicType) { return true; } switch (source.TypeKind) { case TypeKind.Class: // SPEC: From any class type S to any class type T provided S is derived from T. if (destination.IsClassType() && IsBaseClass(source, destination, ref useSiteInfo)) { return true; } return HasImplicitConversionToInterface(source, destination, ref useSiteInfo); case TypeKind.Interface: // SPEC: From any interface-type S to any interface-type T, provided S is derived from T. // NOTE: This handles variance conversions return HasImplicitConversionToInterface(source, destination, ref useSiteInfo); case TypeKind.Delegate: // SPEC: From any delegate-type to System.Delegate and the interfaces it implements. // NOTE: This handles variance conversions. return HasImplicitConversionFromDelegate(source, destination, ref useSiteInfo); case TypeKind.TypeParameter: return HasImplicitReferenceTypeParameterConversion((TypeParameterSymbol)source, destination, ref useSiteInfo); case TypeKind.Array: // SPEC: From an array-type S ... to an array-type T, provided ... // SPEC: From any array-type to System.Array and the interfaces it implements. // SPEC: From a single-dimensional array type S[] to IList<T>, provided ... return HasImplicitConversionFromArray(source, destination, ref useSiteInfo); } // UNDONE: Implicit conversions involving type parameters that are known to be reference types. return false; } private bool HasImplicitConversionToInterface(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!destination.IsInterfaceType()) { return false; } // * From any class type S to any interface type T provided S implements an interface // convertible to T. if (source.IsClassType()) { return HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo); } // * From any interface type S to any interface type T provided S implements an interface // convertible to T. // * From any interface type S to any interface type T provided S is not T and S is // an interface convertible to T. if (source.IsInterfaceType()) { if (HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo)) { return true; } if (!HasIdentityConversionInternal(source, destination) && HasInterfaceVarianceConversion(source, destination, ref useSiteInfo)) { return true; } } return false; } private bool HasImplicitConversionFromArray(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { ArrayTypeSymbol s = source as ArrayTypeSymbol; if ((object)s == null) { return false; } // * From an array type S with an element type SE to an array type T with element type TE // provided that all of the following are true: // * S and T differ only in element type. In other words, S and T have the same number of dimensions. // * Both SE and TE are reference types. // * An implicit reference conversion exists from SE to TE. if (HasCovariantArrayConversion(source, destination, ref useSiteInfo)) { return true; } // * From any array type to System.Array or any interface implemented by System.Array. if (destination.GetSpecialTypeSafe() == SpecialType.System_Array) { return true; } if (IsBaseInterface(destination, this.corLibrary.GetDeclaredSpecialType(SpecialType.System_Array), ref useSiteInfo)) { return true; } // * From a single-dimensional array type S[] to IList<T> and its base // interfaces, provided that there is an implicit identity or reference // conversion from S to T. if (HasArrayConversionToInterface(s, destination, ref useSiteInfo)) { return true; } return false; } private bool HasImplicitConversionFromDelegate(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!source.IsDelegateType()) { return false; } // * From any delegate type to System.Delegate // // SPEC OMISSION: // // The spec should actually say // // * From any delegate type to System.Delegate // * From any delegate type to System.MulticastDelegate // * From any delegate type to any interface implemented by System.MulticastDelegate var specialDestination = destination.GetSpecialTypeSafe(); if (specialDestination == SpecialType.System_MulticastDelegate || specialDestination == SpecialType.System_Delegate || IsBaseInterface(destination, this.corLibrary.GetDeclaredSpecialType(SpecialType.System_MulticastDelegate), ref useSiteInfo)) { return true; } // * From any delegate type S to a delegate type T provided S is not T and // S is a delegate convertible to T if (HasDelegateVarianceConversion(source, destination, ref useSiteInfo)) { return true; } return false; } public bool HasImplicitTypeParameterConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (HasImplicitReferenceTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } if (HasImplicitBoxingTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } if ((destination.TypeKind == TypeKind.TypeParameter) && source.DependsOn((TypeParameterSymbol)destination)) { return true; } return false; } private bool HasImplicitReferenceTypeParameterConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsValueType) { return false; // Not a reference conversion. } // The following implicit conversions exist for a given type parameter T: // // * From T to its effective base class C. // * From T to any base class of C. // * From T to any interface implemented by C (or any interface variance-compatible with such) if (HasImplicitEffectiveBaseConversion(source, destination, ref useSiteInfo)) { return true; } // * From T to any interface type I in T's effective interface set, and // from T to any base interface of I (or any interface variance-compatible with such) if (HasImplicitEffectiveInterfaceSetConversion(source, destination, ref useSiteInfo)) { return true; } // * From T to a type parameter U, provided T depends on U. if ((destination.TypeKind == TypeKind.TypeParameter) && source.DependsOn((TypeParameterSymbol)destination)) { return true; } return false; } // Spec 6.1.10: Implicit conversions involving type parameters private bool HasImplicitEffectiveBaseConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // * From T to its effective base class C. var effectiveBaseClass = source.EffectiveBaseClass(ref useSiteInfo); if (HasIdentityConversionInternal(effectiveBaseClass, destination)) { return true; } // * From T to any base class of C. if (IsBaseClass(effectiveBaseClass, destination, ref useSiteInfo)) { return true; } // * From T to any interface implemented by C (or any interface variance-compatible with such) if (HasAnyBaseInterfaceConversion(effectiveBaseClass, destination, ref useSiteInfo)) { return true; } return false; } private bool HasImplicitEffectiveInterfaceSetConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!destination.IsInterfaceType()) { return false; } // * From T to any interface type I in T's effective interface set, and // from T to any base interface of I (or any interface variance-compatible with such) foreach (var i in source.AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasInterfaceVarianceConversion(i, destination, ref useSiteInfo)) { return true; } } return false; } private bool HasAnyBaseInterfaceConversion(TypeSymbol derivedType, TypeSymbol baseType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)derivedType != null); Debug.Assert((object)baseType != null); if (!baseType.IsInterfaceType()) { return false; } var d = derivedType as NamedTypeSymbol; if ((object)d == null) { return false; } foreach (var i in d.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasInterfaceVarianceConversion(i, baseType, ref useSiteInfo)) { return true; } } return false; } //////////////////////////////////////////////////////////////////////////////// // The rules for variant interface and delegate conversions are the same: // // An interface/delegate type S is convertible to an interface/delegate type T // if and only if T is U<S1, ... Sn> and T is U<T1, ... Tn> such that for all // parameters of U: // // * if the ith parameter of U is invariant then Si is exactly equal to Ti. // * if the ith parameter of U is covariant then either Si is exactly equal // to Ti, or there is an implicit reference conversion from Si to Ti. // * if the ith parameter of U is contravariant then either Si is exactly // equal to Ti, or there is an implicit reference conversion from Ti to Si. private bool HasInterfaceVarianceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); NamedTypeSymbol s = source as NamedTypeSymbol; NamedTypeSymbol d = destination as NamedTypeSymbol; if ((object)s == null || (object)d == null) { return false; } if (!s.IsInterfaceType() || !d.IsInterfaceType()) { return false; } return HasVariantConversion(s, d, ref useSiteInfo); } private bool HasDelegateVarianceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); NamedTypeSymbol s = source as NamedTypeSymbol; NamedTypeSymbol d = destination as NamedTypeSymbol; if ((object)s == null || (object)d == null) { return false; } if (!s.IsDelegateType() || !d.IsDelegateType()) { return false; } return HasVariantConversion(s, d, ref useSiteInfo); } private bool HasVariantConversion(NamedTypeSymbol source, NamedTypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // We check for overflows in HasVariantConversion, because they are only an issue // in the presence of contravariant type parameters, which are not involved in // most conversions. // See VarianceTests for examples (e.g. TestVarianceConversionCycle, // TestVarianceConversionInfiniteExpansion). // // CONSIDER: A more rigorous solution would mimic the CLI approach, which uses // a combination of requiring finite instantiation closures (see section 9.2 of // the CLI spec) and records previous conversion steps to check for cycles. if (currentRecursionDepth >= MaximumRecursionDepth) { // NOTE: The spec doesn't really address what happens if there's an overflow // in our conversion check. It's sort of implied that the conversion "proof" // should be finite, so we'll just say that no conversion is possible. return false; } // Do a quick check up front to avoid instantiating a new Conversions object, // if possible. var quickResult = HasVariantConversionQuick(source, destination); if (quickResult.HasValue()) { return quickResult.Value(); } return this.CreateInstance(currentRecursionDepth + 1). HasVariantConversionNoCycleCheck(source, destination, ref useSiteInfo); } private ThreeState HasVariantConversionQuick(NamedTypeSymbol source, NamedTypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return ThreeState.True; } NamedTypeSymbol typeSymbol = source.OriginalDefinition; if (!TypeSymbol.Equals(typeSymbol, destination.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { return ThreeState.False; } return ThreeState.Unknown; } private bool HasVariantConversionNoCycleCheck(NamedTypeSymbol source, NamedTypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); var typeParameters = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var destinationTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); try { source.OriginalDefinition.GetAllTypeArguments(typeParameters, ref useSiteInfo); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); destination.GetAllTypeArguments(destinationTypeArguments, ref useSiteInfo); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, destination.OriginalDefinition, TypeCompareKind.AllIgnoreOptions)); Debug.Assert(typeParameters.Count == sourceTypeArguments.Count); Debug.Assert(typeParameters.Count == destinationTypeArguments.Count); for (int paramIndex = 0; paramIndex < typeParameters.Count; ++paramIndex) { var sourceTypeArgument = sourceTypeArguments[paramIndex]; var destinationTypeArgument = destinationTypeArguments[paramIndex]; // If they're identical then this one is automatically good, so skip it. if (HasIdentityConversionInternal(sourceTypeArgument.Type, destinationTypeArgument.Type) && HasTopLevelNullabilityIdentityConversion(sourceTypeArgument, destinationTypeArgument)) { continue; } TypeParameterSymbol typeParameterSymbol = (TypeParameterSymbol)typeParameters[paramIndex].Type; switch (typeParameterSymbol.Variance) { case VarianceKind.None: // System.IEquatable<T> is invariant for back compat reasons (dynamic type checks could start // to succeed where they previously failed, creating different runtime behavior), but the uses // require treatment specifically of nullability as contravariant, so we special case the // behavior here. Normally we use GetWellKnownType for these kinds of checks, but in this // case we don't want just the canonical IEquatable to be special-cased, we want all definitions // to be treated as contravariant, in case there are other definitions in metadata that were // compiled with that expectation. if (isTypeIEquatable(destination.OriginalDefinition) && TypeSymbol.Equals(destinationTypeArgument.Type, sourceTypeArgument.Type, TypeCompareKind.AllNullableIgnoreOptions) && HasAnyNullabilityImplicitConversion(destinationTypeArgument, sourceTypeArgument)) { return true; } return false; case VarianceKind.Out: if (!HasImplicitReferenceConversion(sourceTypeArgument, destinationTypeArgument, ref useSiteInfo)) { return false; } break; case VarianceKind.In: if (!HasImplicitReferenceConversion(destinationTypeArgument, sourceTypeArgument, ref useSiteInfo)) { return false; } break; default: throw ExceptionUtilities.UnexpectedValue(typeParameterSymbol.Variance); } } } finally { typeParameters.Free(); sourceTypeArguments.Free(); destinationTypeArguments.Free(); } return true; static bool isTypeIEquatable(NamedTypeSymbol type) { return type is { IsInterface: true, Name: "IEquatable", ContainingNamespace: { Name: "System", ContainingNamespace: { IsGlobalNamespace: true } }, ContainingSymbol: { Kind: SymbolKind.Namespace }, TypeParameters: { Length: 1 } }; } } // Spec 6.1.10 private bool HasImplicitBoxingTypeParameterConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsReferenceType) { return false; // Not a boxing conversion; both source and destination are references. } // The following implicit conversions exist for a given type parameter T: // // * From T to its effective base class C. // * From T to any base class of C. // * From T to any interface implemented by C (or any interface variance-compatible with such) if (HasImplicitEffectiveBaseConversion(source, destination, ref useSiteInfo)) { return true; } // * From T to any interface type I in T's effective interface set, and // from T to any base interface of I (or any interface variance-compatible with such) if (HasImplicitEffectiveInterfaceSetConversion(source, destination, ref useSiteInfo)) { return true; } // SPEC: From T to a type parameter U, provided T depends on U if ((destination.TypeKind == TypeKind.TypeParameter) && source.DependsOn((TypeParameterSymbol)destination)) { return true; } // SPEC: From T to a reference type I if it has an implicit conversion to a reference // SPEC: type S0 and S0 has an identity conversion to S. At run-time the conversion // SPEC: is executed the same way as the conversion to S0. // REVIEW: If T is not known to be a reference type then the only way this clause can // REVIEW: come into effect is if the target type is dynamic. Is that correct? if (destination.Kind == SymbolKind.DynamicType) { return true; } return false; } public bool HasBoxingConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // Certain type parameter conversions are classified as boxing conversions. if ((source.TypeKind == TypeKind.TypeParameter) && HasImplicitBoxingTypeParameterConversion((TypeParameterSymbol)source, destination, ref useSiteInfo)) { return true; } // The rest of the boxing conversions only operate when going from a value type to a // reference type. if (!source.IsValueType || !destination.IsReferenceType) { return false; } // A boxing conversion exists from a nullable type to a reference type if and only if a // boxing conversion exists from the underlying type. if (source.IsNullableType()) { return HasBoxingConversion(source.GetNullableUnderlyingType(), destination, ref useSiteInfo); } // A boxing conversion exists from any non-nullable value type to object and dynamic, to // System.ValueType, and to any interface type variance-compatible with one implemented // by the non-nullable value type. // Furthermore, an enum type can be converted to the type System.Enum. // We set the base class of the structs to System.ValueType, System.Enum, etc, so we can // just check here. // There are a couple of exceptions. The very special types ArgIterator, ArgumentHandle and // TypedReference are not boxable: if (source.IsRestrictedType()) { return false; } if (destination.Kind == SymbolKind.DynamicType) { return !source.IsPointerOrFunctionPointer(); } if (IsBaseClass(source, destination, ref useSiteInfo)) { return true; } if (HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo)) { return true; } return false; } internal static bool HasImplicitPointerToVoidConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: The set of implicit conversions is extended to include... // SPEC: ... from any pointer type to the type void*. return source.IsPointerOrFunctionPointer() && destination is PointerTypeSymbol { PointedAtType: { SpecialType: SpecialType.System_Void } }; } #nullable enable internal bool HasImplicitPointerConversion(TypeSymbol? source, TypeSymbol? destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!(source is FunctionPointerTypeSymbol { Signature: { } sourceSig }) || !(destination is FunctionPointerTypeSymbol { Signature: { } destinationSig })) { return false; } if (sourceSig.ParameterCount != destinationSig.ParameterCount || sourceSig.CallingConvention != destinationSig.CallingConvention) { return false; } if (sourceSig.CallingConvention == Cci.CallingConvention.Unmanaged && !sourceSig.GetCallingConventionModifiers().SetEquals(destinationSig.GetCallingConventionModifiers())) { return false; } for (int i = 0; i < sourceSig.ParameterCount; i++) { var sourceParam = sourceSig.Parameters[i]; var destinationParam = destinationSig.Parameters[i]; if (sourceParam.RefKind != destinationParam.RefKind) { return false; } if (!hasConversion(sourceParam.RefKind, destinationSig.Parameters[i].TypeWithAnnotations, sourceSig.Parameters[i].TypeWithAnnotations, ref useSiteInfo)) { return false; } } return sourceSig.RefKind == destinationSig.RefKind && hasConversion(sourceSig.RefKind, sourceSig.ReturnTypeWithAnnotations, destinationSig.ReturnTypeWithAnnotations, ref useSiteInfo); bool hasConversion(RefKind refKind, TypeWithAnnotations sourceType, TypeWithAnnotations destinationType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { switch (refKind) { case RefKind.None: return (!IncludeNullability || HasTopLevelNullabilityImplicitConversion(sourceType, destinationType)) && (HasIdentityOrImplicitReferenceConversion(sourceType.Type, destinationType.Type, ref useSiteInfo) || HasImplicitPointerToVoidConversion(sourceType.Type, destinationType.Type) || HasImplicitPointerConversion(sourceType.Type, destinationType.Type, ref useSiteInfo)); default: return (!IncludeNullability || HasTopLevelNullabilityIdentityConversion(sourceType, destinationType)) && HasIdentityConversion(sourceType.Type, destinationType.Type); } } } #nullable disable private bool HasIdentityOrReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return true; } if (HasImplicitReferenceConversion(source, destination, ref useSiteInfo)) { return true; } if (HasExplicitReferenceConversion(source, destination, ref useSiteInfo)) { return true; } return false; } private bool HasExplicitReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: The explicit reference conversions are: // SPEC: From object and dynamic to any other reference type. if (source.SpecialType == SpecialType.System_Object) { if (destination.IsReferenceType) { return true; } } else if (source.Kind == SymbolKind.DynamicType && destination.IsReferenceType) { return true; } // SPEC: From any class-type S to any class-type T, provided S is a base class of T. if (destination.IsClassType() && IsBaseClass(destination, source, ref useSiteInfo)) { return true; } // SPEC: From any class-type S to any interface-type T, provided S is not sealed and provided S does not implement T. // ISSUE: class C : IEnumerable<Mammal> { } converting this to IEnumerable<Animal> is not an explicit conversion, // ISSUE: it is an implicit conversion. if (source.IsClassType() && destination.IsInterfaceType() && !source.IsSealed && !HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo)) { return true; } // SPEC: From any interface-type S to any class-type T, provided T is not sealed or provided T implements S. // ISSUE: What if T is sealed and implements an interface variance-convertible to S? // ISSUE: eg, sealed class C : IEnum<Mammal> { ... } you should be able to cast an IEnum<Animal> to C. if (source.IsInterfaceType() && destination.IsClassType() && (!destination.IsSealed || HasAnyBaseInterfaceConversion(destination, source, ref useSiteInfo))) { return true; } // SPEC: From any interface-type S to any interface-type T, provided S is not derived from T. // ISSUE: This does not rule out identity conversions, which ought not to be classified as // ISSUE: explicit reference conversions. // ISSUE: IEnumerable<Mammal> and IEnumerable<Animal> do not derive from each other but this is // ISSUE: not an explicit reference conversion, this is an implicit reference conversion. if (source.IsInterfaceType() && destination.IsInterfaceType() && !HasImplicitConversionToInterface(source, destination, ref useSiteInfo)) { return true; } // SPEC: UNDONE: From a reference type to a reference type T if it has an explicit reference conversion to a reference type T0 and T0 has an identity conversion T. // SPEC: UNDONE: From a reference type to an interface or delegate type T if it has an explicit reference conversion to an interface or delegate type T0 and either T0 is variance-convertible to T or T is variance-convertible to T0 (§13.1.3.2). if (HasExplicitArrayConversion(source, destination, ref useSiteInfo)) { return true; } if (HasExplicitDelegateConversion(source, destination, ref useSiteInfo)) { return true; } if (HasExplicitReferenceTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } return false; } // Spec 6.2.7 Explicit conversions involving type parameters private bool HasExplicitReferenceTypeParameterConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); TypeParameterSymbol s = source as TypeParameterSymbol; TypeParameterSymbol t = destination as TypeParameterSymbol; // SPEC: The following explicit conversions exist for a given type parameter T: // SPEC: If T is known to be a reference type, the conversions are all classified as explicit reference conversions. // SPEC: If T is not known to be a reference type, the conversions are classified as unboxing conversions. // SPEC: From the effective base class C of T to T and from any base class of C to T. if ((object)t != null && t.IsReferenceType) { for (var type = t.EffectiveBaseClass(ref useSiteInfo); (object)type != null; type = type.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(type, source)) { return true; } } } // SPEC: From any interface type to T. if ((object)t != null && source.IsInterfaceType() && t.IsReferenceType) { return true; } // SPEC: From T to any interface-type I provided there is not already an implicit conversion from T to I. if ((object)s != null && s.IsReferenceType && destination.IsInterfaceType() && !HasImplicitReferenceTypeParameterConversion(s, destination, ref useSiteInfo)) { return true; } // SPEC: From a type parameter U to T, provided T depends on U (§10.1.5) if ((object)s != null && (object)t != null && t.IsReferenceType && t.DependsOn(s)) { return true; } return false; } // Spec 6.2.7 Explicit conversions involving type parameters private bool HasUnboxingTypeParameterConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); TypeParameterSymbol s = source as TypeParameterSymbol; TypeParameterSymbol t = destination as TypeParameterSymbol; // SPEC: The following explicit conversions exist for a given type parameter T: // SPEC: If T is known to be a reference type, the conversions are all classified as explicit reference conversions. // SPEC: If T is not known to be a reference type, the conversions are classified as unboxing conversions. // SPEC: From the effective base class C of T to T and from any base class of C to T. if ((object)t != null && !t.IsReferenceType) { for (var type = t.EffectiveBaseClass(ref useSiteInfo); (object)type != null; type = type.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (TypeSymbol.Equals(type, source, TypeCompareKind.ConsiderEverything2)) { return true; } } } // SPEC: From any interface type to T. if (source.IsInterfaceType() && (object)t != null && !t.IsReferenceType) { return true; } // SPEC: From T to any interface-type I provided there is not already an implicit conversion from T to I. if ((object)s != null && !s.IsReferenceType && destination.IsInterfaceType() && !HasImplicitReferenceTypeParameterConversion(s, destination, ref useSiteInfo)) { return true; } // SPEC: From a type parameter U to T, provided T depends on U (§10.1.5) if ((object)s != null && (object)t != null && !t.IsReferenceType && t.DependsOn(s)) { return true; } return false; } private bool HasExplicitDelegateConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: From System.Delegate and the interfaces it implements to any delegate-type. // We also support System.MulticastDelegate in the implementation, in spite of it not being mentioned in the spec. if (destination.IsDelegateType()) { if (source.SpecialType == SpecialType.System_Delegate || source.SpecialType == SpecialType.System_MulticastDelegate) { return true; } if (HasImplicitConversionToInterface(this.corLibrary.GetDeclaredSpecialType(SpecialType.System_Delegate), source, ref useSiteInfo)) { return true; } } // SPEC: From D<S1...Sn> to a D<T1...Tn> where D<X1...Xn> is a generic delegate type, D<S1...Sn> is not compatible with or identical to D<T1...Tn>, // SPEC: and for each type parameter Xi of D the following holds: // SPEC: If Xi is invariant, then Si is identical to Ti. // SPEC: If Xi is covariant, then there is an implicit or explicit identity or reference conversion from Si to Ti. // SPECL If Xi is contravariant, then Si and Ti are either identical or both reference types. if (!source.IsDelegateType() || !destination.IsDelegateType()) { return false; } if (!TypeSymbol.Equals(source.OriginalDefinition, destination.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { return false; } var sourceType = (NamedTypeSymbol)source; var destinationType = (NamedTypeSymbol)destination; var original = sourceType.OriginalDefinition; if (HasIdentityConversionInternal(source, destination)) { return false; } if (HasDelegateVarianceConversion(source, destination, ref useSiteInfo)) { return false; } var sourceTypeArguments = sourceType.TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteInfo); var destinationTypeArguments = destinationType.TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteInfo); for (int i = 0; i < sourceTypeArguments.Length; ++i) { var sourceArg = sourceTypeArguments[i].Type; var destinationArg = destinationTypeArguments[i].Type; switch (original.TypeParameters[i].Variance) { case VarianceKind.None: if (!HasIdentityConversionInternal(sourceArg, destinationArg)) { return false; } break; case VarianceKind.Out: if (!HasIdentityOrReferenceConversion(sourceArg, destinationArg, ref useSiteInfo)) { return false; } break; case VarianceKind.In: bool hasIdentityConversion = HasIdentityConversionInternal(sourceArg, destinationArg); bool bothAreReferenceTypes = sourceArg.IsReferenceType && destinationArg.IsReferenceType; if (!(hasIdentityConversion || bothAreReferenceTypes)) { return false; } break; } } return true; } private bool HasExplicitArrayConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); var sourceArray = source as ArrayTypeSymbol; var destinationArray = destination as ArrayTypeSymbol; // SPEC: From an array-type S with an element type SE to an array-type T with an element type TE, provided all of the following are true: // SPEC: S and T differ only in element type. (In other words, S and T have the same number of dimensions.) // SPEC: Both SE and TE are reference-types. // SPEC: An explicit reference conversion exists from SE to TE. if ((object)sourceArray != null && (object)destinationArray != null) { // HasExplicitReferenceConversion checks that SE and TE are reference types so // there's no need for that check here. Moreover, it's not as simple as checking // IsReferenceType, at least not in the case of type parameters, since SE will be // considered a reference type implicitly in the case of "where TE : class, SE" even // though SE.IsReferenceType may be false. Again, HasExplicitReferenceConversion // already handles these cases. return sourceArray.HasSameShapeAs(destinationArray) && HasExplicitReferenceConversion(sourceArray.ElementType, destinationArray.ElementType, ref useSiteInfo); } // SPEC: From System.Array and the interfaces it implements to any array-type. if ((object)destinationArray != null) { if (source.SpecialType == SpecialType.System_Array) { return true; } foreach (var iface in this.corLibrary.GetDeclaredSpecialType(SpecialType.System_Array).AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(iface, source)) { return true; } } } // SPEC: From a single-dimensional array type S[] to System.Collections.Generic.IList<T> and its base interfaces // SPEC: provided that there is an explicit reference conversion from S to T. // The framework now also allows arrays to be converted to IReadOnlyList<T> and IReadOnlyCollection<T>; we // honor that as well. if ((object)sourceArray != null && sourceArray.IsSZArray && destination.IsPossibleArrayGenericInterface()) { if (HasExplicitReferenceConversion(sourceArray.ElementType, ((NamedTypeSymbol)destination).TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo).Type, ref useSiteInfo)) { return true; } } // SPEC: From System.Collections.Generic.IList<S> and its base interfaces to a single-dimensional array type T[], // provided that there is an explicit identity or reference conversion from S to T. // Similarly, we honor IReadOnlyList<S> and IReadOnlyCollection<S> in the same way. if ((object)destinationArray != null && destinationArray.IsSZArray) { var specialDefinition = ((TypeSymbol)source.OriginalDefinition).SpecialType; if (specialDefinition == SpecialType.System_Collections_Generic_IList_T || specialDefinition == SpecialType.System_Collections_Generic_ICollection_T || specialDefinition == SpecialType.System_Collections_Generic_IEnumerable_T || specialDefinition == SpecialType.System_Collections_Generic_IReadOnlyList_T || specialDefinition == SpecialType.System_Collections_Generic_IReadOnlyCollection_T) { var sourceElement = ((NamedTypeSymbol)source).TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo).Type; var destinationElement = destinationArray.ElementType; if (HasIdentityConversionInternal(sourceElement, destinationElement)) { return true; } if (HasImplicitReferenceConversion(sourceElement, destinationElement, ref useSiteInfo)) { return true; } if (HasExplicitReferenceConversion(sourceElement, destinationElement, ref useSiteInfo)) { return true; } } } return false; } private bool HasUnboxingConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (destination.IsPointerOrFunctionPointer()) { return false; } // Ref-like types cannot be boxed or unboxed if (destination.IsRestrictedType()) { return false; } // SPEC: An unboxing conversion permits a reference type to be explicitly converted to a value-type. // SPEC: An unboxing conversion exists from the types object and System.ValueType to any non-nullable-value-type, var specialTypeSource = source.SpecialType; if (specialTypeSource == SpecialType.System_Object || specialTypeSource == SpecialType.System_ValueType) { if (destination.IsValueType && !destination.IsNullableType()) { return true; } } // SPEC: and from any interface-type to any non-nullable-value-type that implements the interface-type. if (source.IsInterfaceType() && destination.IsValueType && !destination.IsNullableType() && HasBoxingConversion(destination, source, ref useSiteInfo)) { return true; } // SPEC: Furthermore type System.Enum can be unboxed to any enum-type. if (source.SpecialType == SpecialType.System_Enum && destination.IsEnumType()) { return true; } // SPEC: An unboxing conversion exists from a reference type to a nullable-type if an unboxing // SPEC: conversion exists from the reference type to the underlying non-nullable-value-type // SPEC: of the nullable-type. if (source.IsReferenceType && destination.IsNullableType() && HasUnboxingConversion(source, destination.GetNullableUnderlyingType(), ref useSiteInfo)) { return true; } // SPEC: UNDONE A value type S has an unboxing conversion from an interface type I if it has an unboxing // SPEC: UNDONE conversion from an interface type I0 and I0 has an identity conversion to I. // SPEC: UNDONE A value type S has an unboxing conversion from an interface type I if it has an unboxing conversion // SPEC: UNDONE from an interface or delegate type I0 and either I0 is variance-convertible to I or I is variance-convertible to I0. if (HasUnboxingTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } return false; } private static bool HasPointerToPointerConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); return source.IsPointerOrFunctionPointer() && destination.IsPointerOrFunctionPointer(); } private static bool HasPointerToIntegerConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!source.IsPointerOrFunctionPointer()) { return false; } // SPEC OMISSION: // // The spec should state that any pointer type is convertible to // sbyte, byte, ... etc, or any corresponding nullable type. return IsIntegerTypeSupportingPointerConversions(destination.StrippedType()); } private static bool HasIntegerToPointerConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!destination.IsPointerOrFunctionPointer()) { return false; } // Note that void* is convertible to int?, but int? is not convertible to void*. return IsIntegerTypeSupportingPointerConversions(source); } private static bool IsIntegerTypeSupportingPointerConversions(TypeSymbol type) { switch (type.SpecialType) { case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: return true; case SpecialType.System_IntPtr: case SpecialType.System_UIntPtr: return type.IsNativeIntegerType; } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal abstract partial class ConversionsBase { private const int MaximumRecursionDepth = 50; protected readonly AssemblySymbol corLibrary; protected readonly int currentRecursionDepth; internal readonly bool IncludeNullability; /// <summary> /// An optional clone of this instance with distinct IncludeNullability. /// Used to avoid unnecessary allocations when calling WithNullability() repeatedly. /// </summary> private ConversionsBase _lazyOtherNullability; protected ConversionsBase(AssemblySymbol corLibrary, int currentRecursionDepth, bool includeNullability, ConversionsBase otherNullabilityOpt) { Debug.Assert((object)corLibrary != null); Debug.Assert(otherNullabilityOpt == null || includeNullability != otherNullabilityOpt.IncludeNullability); Debug.Assert(otherNullabilityOpt == null || currentRecursionDepth == otherNullabilityOpt.currentRecursionDepth); this.corLibrary = corLibrary; this.currentRecursionDepth = currentRecursionDepth; IncludeNullability = includeNullability; _lazyOtherNullability = otherNullabilityOpt; } /// <summary> /// Returns this instance if includeNullability is correct, and returns a /// cached clone of this instance with distinct IncludeNullability otherwise. /// </summary> internal ConversionsBase WithNullability(bool includeNullability) { if (IncludeNullability == includeNullability) { return this; } if (_lazyOtherNullability == null) { Interlocked.CompareExchange(ref _lazyOtherNullability, WithNullabilityCore(includeNullability), null); } Debug.Assert(_lazyOtherNullability.IncludeNullability == includeNullability); Debug.Assert(_lazyOtherNullability._lazyOtherNullability == this); return _lazyOtherNullability; } protected abstract ConversionsBase WithNullabilityCore(bool includeNullability); public abstract Conversion GetMethodGroupDelegateConversion(BoundMethodGroup source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); public abstract Conversion GetMethodGroupFunctionPointerConversion(BoundMethodGroup source, FunctionPointerTypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); public abstract Conversion GetStackAllocConversion(BoundStackAllocArrayCreation sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); protected abstract ConversionsBase CreateInstance(int currentRecursionDepth); protected abstract Conversion GetInterpolatedStringConversion(BoundUnconvertedInterpolatedString source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo); internal AssemblySymbol CorLibrary { get { return corLibrary; } } /// <summary> /// Determines if the source expression is convertible to the destination type via /// any built-in or user-defined implicit conversion. /// </summary> public Conversion ClassifyImplicitConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null); Debug.Assert((object)destination != null); var sourceType = sourceExpression.Type; //PERF: identity conversion is by far the most common implicit conversion, check for that first if ((object)sourceType != null && HasIdentityConversionInternal(sourceType, destination)) { return Conversion.Identity; } Conversion conversion = ClassifyImplicitBuiltInConversionFromExpression(sourceExpression, sourceType, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } if ((object)sourceType != null) { // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(sourceType, destination); if (fastConversion.Exists) { if (fastConversion.IsImplicit) { return fastConversion; } } else { conversion = ClassifyImplicitBuiltInConversionSlow(sourceType, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } } } conversion = GetImplicitUserDefinedConversion(sourceExpression, sourceType, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } // The switch expression conversion is "lowest priority", so that if there is a conversion from the expression's // type it will be preferred over the switch expression conversion. Technically, we would want the language // specification to say that the switch expression conversion only "exists" if there is no implicit conversion // from the type, and we accomplish that by making it lowest priority. The same is true for the conditional // expression conversion. conversion = GetSwitchExpressionConversion(sourceExpression, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } return GetConditionalExpressionConversion(sourceExpression, destination, ref useSiteInfo); } /// <summary> /// Determines if the source type is convertible to the destination type via /// any built-in or user-defined implicit conversion. /// </summary> public Conversion ClassifyImplicitConversionFromType(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); //PERF: identity conversions are very common, check for that first. if (HasIdentityConversionInternal(source, destination)) { return Conversion.Identity; } // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion.IsImplicit ? fastConversion : Conversion.NoConversion; } else { Conversion conversion = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } } return GetImplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); } /// <summary> /// Determines if the source expression of given type is convertible to the destination type via /// any built-in or user-defined conversion. /// /// This helper is used in rare cases involving synthesized expressions where we know the type of an expression, but do not have the actual expression. /// The reason for this helper (as opposed to ClassifyConversionFromType) is that conversions from expressions could be different /// from conversions from type. For example expressions of dynamic type are implicitly convertable to any type, while dynamic type itself is not. /// </summary> public Conversion ClassifyConversionFromExpressionType(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // since we are converting from expression, we may have implicit dynamic conversion if (HasImplicitDynamicConversionFromExpression(source, destination)) { return Conversion.ImplicitDynamic; } return ClassifyConversionFromType(source, destination, ref useSiteInfo); } private static bool TryGetVoidConversion(TypeSymbol source, TypeSymbol destination, out Conversion conversion) { var sourceIsVoid = source?.SpecialType == SpecialType.System_Void; var destIsVoid = destination.SpecialType == SpecialType.System_Void; // 'void' is not supposed to be able to convert to or from anything, but in practice, // a lot of code depends on checking whether an expression of type 'void' is convertible to 'void'. // (e.g. for an expression lambda which returns void). // Therefore we allow an identity conversion between 'void' and 'void'. if (sourceIsVoid && destIsVoid) { conversion = Conversion.Identity; return true; } // If exactly one of source or destination is of type 'void' then no conversion may exist. if (sourceIsVoid || destIsVoid) { conversion = Conversion.NoConversion; return true; } conversion = default; return false; } /// <summary> /// Determines if the source expression is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source expression to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the implicit conversion or explicit depending on "forCast" /// </remarks> public Conversion ClassifyConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast = false) { Debug.Assert(sourceExpression != null); Debug.Assert((object)destination != null); if (TryGetVoidConversion(sourceExpression.Type, destination, out var conversion)) { return conversion; } if (forCast) { return ClassifyConversionFromExpressionForCast(sourceExpression, destination, ref useSiteInfo); } var result = ClassifyImplicitConversionFromExpression(sourceExpression, destination, ref useSiteInfo); if (result.Exists) { return result; } return ClassifyExplicitOnlyConversionFromExpression(sourceExpression, destination, ref useSiteInfo, forCast: false); } /// <summary> /// Determines if the source type is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source type to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the implicit conversion or explicit depending on "forCast" /// </remarks> public Conversion ClassifyConversionFromType(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast = false) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (TryGetVoidConversion(source, destination, out var voidConversion)) { return voidConversion; } if (forCast) { return ClassifyConversionFromTypeForCast(source, destination, ref useSiteInfo); } // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion; } else { Conversion conversion1 = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (conversion1.Exists) { return conversion1; } } Conversion conversion = GetImplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } conversion = ClassifyExplicitBuiltInOnlyConversion(source, destination, ref useSiteInfo, forCast: false); if (conversion.Exists) { return conversion; } return GetExplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); } /// <summary> /// Determines if the source expression is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source expression to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the built-in conversion. /// /// An implicit conversion exists from an expression of a dynamic type to any type. /// An explicit conversion exists from a dynamic type to any type. /// When casting we prefer the explicit conversion. /// </remarks> private Conversion ClassifyConversionFromExpressionForCast(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert((object)destination != null); Conversion implicitConversion = ClassifyImplicitConversionFromExpression(source, destination, ref useSiteInfo); if (implicitConversion.Exists && !ExplicitConversionMayDifferFromImplicit(implicitConversion)) { return implicitConversion; } Conversion explicitConversion = ClassifyExplicitOnlyConversionFromExpression(source, destination, ref useSiteInfo, forCast: true); if (explicitConversion.Exists) { return explicitConversion; } // It is possible for a user-defined conversion to be unambiguous when considered as // an implicit conversion and ambiguous when considered as an explicit conversion. // The native compiler does not check to see if a cast could be successfully bound as // an unambiguous user-defined implicit conversion; it goes right to the ambiguous // user-defined explicit conversion and produces an error. This means that in // C# 5 it is possible to have: // // Y y = new Y(); // Z z1 = y; // // succeed but // // Z z2 = (Z)y; // // fail. // // However, there is another interesting wrinkle. It is possible for both // an implicit user-defined conversion and an explicit user-defined conversion // to exist and be unambiguous. For example, if there is an implicit conversion // double-->C and an explicit conversion from int-->C, and the user casts a short // to C, then both the implicit and explicit conversions are applicable and // unambiguous. The native compiler in this case prefers the explicit conversion, // and for backwards compatibility, we match it. return implicitConversion; } /// <summary> /// Determines if the source type is convertible to the destination type via /// any conversion: implicit, explicit, user-defined or built-in. /// </summary> /// <remarks> /// It is rare but possible for a source type to be convertible to a destination type /// by both an implicit user-defined conversion and a built-in explicit conversion. /// In that circumstance, this method classifies the conversion as the built-in conversion. /// </remarks> private Conversion ClassifyConversionFromTypeForCast(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion; } Conversion implicitBuiltInConversion = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (implicitBuiltInConversion.Exists && !ExplicitConversionMayDifferFromImplicit(implicitBuiltInConversion)) { return implicitBuiltInConversion; } Conversion explicitBuiltInConversion = ClassifyExplicitBuiltInOnlyConversion(source, destination, ref useSiteInfo, forCast: true); if (explicitBuiltInConversion.Exists) { return explicitBuiltInConversion; } if (implicitBuiltInConversion.Exists) { return implicitBuiltInConversion; } // It is possible for a user-defined conversion to be unambiguous when considered as // an implicit conversion and ambiguous when considered as an explicit conversion. // The native compiler does not check to see if a cast could be successfully bound as // an unambiguous user-defined implicit conversion; it goes right to the ambiguous // user-defined explicit conversion and produces an error. This means that in // C# 5 it is possible to have: // // Y y = new Y(); // Z z1 = y; // // succeed but // // Z z2 = (Z)y; // // fail. var conversion = GetExplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } return GetImplicitUserDefinedConversion(null, source, destination, ref useSiteInfo); } /// <summary> /// Attempt a quick classification of builtin conversions. As result of "no conversion" /// means that there is no built-in conversion, though there still may be a user-defined /// conversion if compiling against a custom mscorlib. /// </summary> public static Conversion FastClassifyConversion(TypeSymbol source, TypeSymbol target) { ConversionKind convKind = ConversionEasyOut.ClassifyConversion(source, target); if (convKind != ConversionKind.ImplicitNullable && convKind != ConversionKind.ExplicitNullable) { return Conversion.GetTrivialConversion(convKind); } return Conversion.MakeNullableConversion(convKind, FastClassifyConversion(source.StrippedType(), target.StrippedType())); } public Conversion ClassifyBuiltInConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(source, destination); if (fastConversion.Exists) { return fastConversion; } else { Conversion conversion = ClassifyImplicitBuiltInConversionSlow(source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } } return ClassifyExplicitBuiltInOnlyConversion(source, destination, ref useSiteInfo, forCast: false); } /// <summary> /// Determines if the source type is convertible to the destination type via /// any standard implicit or standard explicit conversion. /// </summary> /// <remarks> /// Not all built-in explicit conversions are standard explicit conversions. /// </remarks> public Conversion ClassifyStandardConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert((object)destination != null); // Note that the definition of explicit standard conversion does not include all explicit // reference conversions! There is a standard implicit reference conversion from // Action<Object> to Action<Exception>, thanks to contravariance. There is a standard // implicit reference conversion from Action<Object> to Action<String> for the same reason. // Therefore there is an explicit reference conversion from Action<Exception> to // Action<String>; a given Action<Exception> might be an Action<Object>, and hence // convertible to Action<String>. However, this is not a *standard* explicit conversion. The // standard explicit conversions are all the standard implicit conversions and their // opposites. Therefore Action<Object>-->Action<String> and Action<String>-->Action<Object> // are both standard conversions. But Action<String>-->Action<Exception> is not a standard // explicit conversion because neither it nor its opposite is a standard implicit // conversion. // // Similarly, there is no standard explicit conversion from double to decimal, because // there is no standard implicit conversion between the two types. // SPEC: The standard explicit conversions are all standard implicit conversions plus // SPEC: the subset of the explicit conversions for which an opposite standard implicit // SPEC: conversion exists. In other words, if a standard implicit conversion exists from // SPEC: a type A to a type B, then a standard explicit conversion exists from type A to // SPEC: type B and from type B to type A. Conversion conversion = ClassifyStandardImplicitConversion(sourceExpression, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } if ((object)source != null) { return DeriveStandardExplicitFromOppositeStandardImplicitConversion(source, destination, ref useSiteInfo); } return Conversion.NoConversion; } private Conversion ClassifyStandardImplicitConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert(sourceExpression == null || (object)sourceExpression.Type == (object)source); Debug.Assert((object)destination != null); // SPEC: The following implicit conversions are classified as standard implicit conversions: // SPEC: Identity conversions // SPEC: Implicit numeric conversions // SPEC: Implicit nullable conversions // SPEC: Implicit reference conversions // SPEC: Boxing conversions // SPEC: Implicit constant expression conversions // SPEC: Implicit conversions involving type parameters // // and in unsafe code: // // SPEC: From any pointer type to void* // // SPEC ERROR: // The specification does not say to take into account the conversion from // the *expression*, only its *type*. But the expression may not have a type // (because it is null, a method group, or a lambda), or the expression might // be convertible to the destination type via a constant numeric conversion. // For example, the native compiler allows "C c = 1;" to work if C is a class which // has an implicit conversion from byte to C, despite the fact that there is // obviously no standard implicit conversion from *int* to *byte*. // Similarly, if a struct S has an implicit conversion from string to S, then // "S s = null;" should be allowed. // // We extend the definition of standard implicit conversions to include // all of the implicit conversions that are allowed based on an expression, // with the exception of the switch expression conversion. Conversion conversion = ClassifyImplicitBuiltInConversionFromExpression(sourceExpression, source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } if ((object)source != null) { return ClassifyStandardImplicitConversion(source, destination, ref useSiteInfo); } return Conversion.NoConversion; } private Conversion ClassifyStandardImplicitConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return Conversion.Identity; } if (HasImplicitNumericConversion(source, destination)) { return Conversion.ImplicitNumeric; } var nullableConversion = ClassifyImplicitNullableConversion(source, destination, ref useSiteInfo); if (nullableConversion.Exists) { return nullableConversion; } if (HasImplicitReferenceConversion(source, destination, ref useSiteInfo)) { return Conversion.ImplicitReference; } if (HasBoxingConversion(source, destination, ref useSiteInfo)) { return Conversion.Boxing; } if (HasImplicitPointerToVoidConversion(source, destination)) { return Conversion.PointerToVoid; } if (HasImplicitPointerConversion(source, destination, ref useSiteInfo)) { return Conversion.ImplicitPointer; } var tupleConversion = ClassifyImplicitTupleConversion(source, destination, ref useSiteInfo); if (tupleConversion.Exists) { return tupleConversion; } return Conversion.NoConversion; } private Conversion ClassifyImplicitBuiltInConversionSlow(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsVoidType() || destination.IsVoidType()) { return Conversion.NoConversion; } Conversion conversion = ClassifyStandardImplicitConversion(source, destination, ref useSiteInfo); if (conversion.Exists) { return conversion; } return Conversion.NoConversion; } private Conversion GetImplicitUserDefinedConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var conversionResult = AnalyzeImplicitUserDefinedConversions(sourceExpression, source, destination, ref useSiteInfo); return new Conversion(conversionResult, isImplicit: true); } private Conversion ClassifyExplicitBuiltInOnlyConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsVoidType() || destination.IsVoidType()) { return Conversion.NoConversion; } // The call to HasExplicitNumericConversion isn't necessary, because it is always tested // already by the "FastConversion" code. Debug.Assert(!HasExplicitNumericConversion(source, destination)); //if (HasExplicitNumericConversion(source, specialTypeSource, destination, specialTypeDest)) //{ // return Conversion.ExplicitNumeric; //} if (HasSpecialIntPtrConversion(source, destination)) { return Conversion.IntPtr; } if (HasExplicitEnumerationConversion(source, destination)) { return Conversion.ExplicitEnumeration; } var nullableConversion = ClassifyExplicitNullableConversion(source, destination, ref useSiteInfo, forCast); if (nullableConversion.Exists) { return nullableConversion; } if (HasExplicitReferenceConversion(source, destination, ref useSiteInfo)) { return (source.Kind == SymbolKind.DynamicType) ? Conversion.ExplicitDynamic : Conversion.ExplicitReference; } if (HasUnboxingConversion(source, destination, ref useSiteInfo)) { return Conversion.Unboxing; } var tupleConversion = ClassifyExplicitTupleConversion(source, destination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return tupleConversion; } if (HasPointerToPointerConversion(source, destination)) { return Conversion.PointerToPointer; } if (HasPointerToIntegerConversion(source, destination)) { return Conversion.PointerToInteger; } if (HasIntegerToPointerConversion(source, destination)) { return Conversion.IntegerToPointer; } if (HasExplicitDynamicConversion(source, destination)) { return Conversion.ExplicitDynamic; } return Conversion.NoConversion; } private Conversion GetExplicitUserDefinedConversion(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { UserDefinedConversionResult conversionResult = AnalyzeExplicitUserDefinedConversions(sourceExpression, source, destination, ref useSiteInfo); return new Conversion(conversionResult, isImplicit: false); } private Conversion DeriveStandardExplicitFromOppositeStandardImplicitConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var oppositeConversion = ClassifyStandardImplicitConversion(destination, source, ref useSiteInfo); Conversion impliedExplicitConversion; switch (oppositeConversion.Kind) { case ConversionKind.Identity: impliedExplicitConversion = Conversion.Identity; break; case ConversionKind.ImplicitNumeric: impliedExplicitConversion = Conversion.ExplicitNumeric; break; case ConversionKind.ImplicitReference: impliedExplicitConversion = Conversion.ExplicitReference; break; case ConversionKind.Boxing: impliedExplicitConversion = Conversion.Unboxing; break; case ConversionKind.NoConversion: impliedExplicitConversion = Conversion.NoConversion; break; case ConversionKind.ImplicitPointerToVoid: impliedExplicitConversion = Conversion.PointerToPointer; break; case ConversionKind.ImplicitTuple: // only implicit tuple conversions are standard conversions, // having implicit conversion in the other direction does not help here. impliedExplicitConversion = Conversion.NoConversion; break; case ConversionKind.ImplicitNullable: var strippedSource = source.StrippedType(); var strippedDestination = destination.StrippedType(); var underlyingConversion = DeriveStandardExplicitFromOppositeStandardImplicitConversion(strippedSource, strippedDestination, ref useSiteInfo); // the opposite underlying conversion may not exist // for example if underlying conversion is implicit tuple impliedExplicitConversion = underlyingConversion.Exists ? Conversion.MakeNullableConversion(ConversionKind.ExplicitNullable, underlyingConversion) : Conversion.NoConversion; break; default: throw ExceptionUtilities.UnexpectedValue(oppositeConversion.Kind); } return impliedExplicitConversion; } /// <summary> /// IsBaseInterface returns true if baseType is on the base interface list of derivedType or /// any base class of derivedType. It may be on the base interface list either directly or /// indirectly. /// * baseType must be an interface. /// * type parameters do not have base interfaces. (They have an "effective interface list".) /// * an interface is not a base of itself. /// * this does not check for variance conversions; if a type inherits from /// IEnumerable&lt;string> then IEnumerable&lt;object> is not a base interface. /// </summary> public bool IsBaseInterface(TypeSymbol baseType, TypeSymbol derivedType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)baseType != null); Debug.Assert((object)derivedType != null); if (!baseType.IsInterfaceType()) { return false; } var d = derivedType as NamedTypeSymbol; if ((object)d == null) { return false; } foreach (var iface in d.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(iface, baseType)) { return true; } } return false; } // IsBaseClass returns true if and only if baseType is a base class of derivedType, period. // // * interfaces do not have base classes. (Structs, enums and classes other than object do.) // * a class is not a base class of itself // * type parameters do not have base classes. (They have "effective base classes".) // * all base classes must be classes // * dynamics are removed; if we have class D : B<dynamic> then B<object> is a // base class of D. However, dynamic is never a base class of anything. public bool IsBaseClass(TypeSymbol derivedType, TypeSymbol baseType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)derivedType != null); Debug.Assert((object)baseType != null); // A base class has got to be a class. The derived type might be a struct, enum, or delegate. if (!baseType.IsClassType()) { return false; } for (TypeSymbol b = derivedType.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); (object)b != null; b = b.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(b, baseType)) { return true; } } return false; } /// <summary> /// returns true when implicit conversion is not necessarily the same as explicit conversion /// </summary> private static bool ExplicitConversionMayDifferFromImplicit(Conversion implicitConversion) { switch (implicitConversion.Kind) { case ConversionKind.ImplicitUserDefined: case ConversionKind.ImplicitDynamic: case ConversionKind.ImplicitTuple: case ConversionKind.ImplicitTupleLiteral: case ConversionKind.ImplicitNullable: case ConversionKind.ConditionalExpression: return true; default: return false; } } private Conversion ClassifyImplicitBuiltInConversionFromExpression(BoundExpression sourceExpression, TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpression != null || (object)source != null); Debug.Assert(sourceExpression == null || (object)sourceExpression.Type == (object)source); Debug.Assert((object)destination != null); if (HasImplicitDynamicConversionFromExpression(source, destination)) { return Conversion.ImplicitDynamic; } // The following conversions only exist for certain form of expressions, // if we have no expression none if them is applicable. if (sourceExpression == null) { return Conversion.NoConversion; } if (HasImplicitEnumerationConversion(sourceExpression, destination)) { return Conversion.ImplicitEnumeration; } var constantConversion = ClassifyImplicitConstantExpressionConversion(sourceExpression, destination); if (constantConversion.Exists) { return constantConversion; } switch (sourceExpression.Kind) { case BoundKind.Literal: var nullLiteralConversion = ClassifyNullLiteralConversion(sourceExpression, destination); if (nullLiteralConversion.Exists) { return nullLiteralConversion; } break; case BoundKind.DefaultLiteral: return Conversion.DefaultLiteral; case BoundKind.ExpressionWithNullability: { var innerExpression = ((BoundExpressionWithNullability)sourceExpression).Expression; var innerConversion = ClassifyImplicitBuiltInConversionFromExpression(innerExpression, innerExpression.Type, destination, ref useSiteInfo); if (innerConversion.Exists) { return innerConversion; } break; } case BoundKind.TupleLiteral: var tupleConversion = ClassifyImplicitTupleLiteralConversion((BoundTupleLiteral)sourceExpression, destination, ref useSiteInfo); if (tupleConversion.Exists) { return tupleConversion; } break; case BoundKind.UnboundLambda: if (HasAnonymousFunctionConversion(sourceExpression, destination)) { return Conversion.AnonymousFunction; } break; case BoundKind.MethodGroup: Conversion methodGroupConversion = GetMethodGroupDelegateConversion((BoundMethodGroup)sourceExpression, destination, ref useSiteInfo); if (methodGroupConversion.Exists) { return methodGroupConversion; } break; case BoundKind.UnconvertedInterpolatedString: Conversion interpolatedStringConversion = GetInterpolatedStringConversion((BoundUnconvertedInterpolatedString)sourceExpression, destination, ref useSiteInfo); if (interpolatedStringConversion.Exists) { return interpolatedStringConversion; } break; case BoundKind.StackAllocArrayCreation: var stackAllocConversion = GetStackAllocConversion((BoundStackAllocArrayCreation)sourceExpression, destination, ref useSiteInfo); if (stackAllocConversion.Exists) { return stackAllocConversion; } break; case BoundKind.UnconvertedAddressOfOperator when destination is FunctionPointerTypeSymbol funcPtrType: var addressOfConversion = GetMethodGroupFunctionPointerConversion(((BoundUnconvertedAddressOfOperator)sourceExpression).Operand, funcPtrType, ref useSiteInfo); if (addressOfConversion.Exists) { return addressOfConversion; } break; case BoundKind.ThrowExpression: return Conversion.ImplicitThrow; case BoundKind.UnconvertedObjectCreationExpression: return Conversion.ObjectCreation; } return Conversion.NoConversion; } private Conversion GetSwitchExpressionConversion(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { switch (source) { case BoundConvertedSwitchExpression _: // It has already been subjected to a switch expression conversion. return Conversion.NoConversion; case BoundUnconvertedSwitchExpression switchExpression: var innerConversions = ArrayBuilder<Conversion>.GetInstance(switchExpression.SwitchArms.Length); foreach (var arm in switchExpression.SwitchArms) { var nestedConversion = this.ClassifyImplicitConversionFromExpression(arm.Value, destination, ref useSiteInfo); if (!nestedConversion.Exists) { innerConversions.Free(); return Conversion.NoConversion; } innerConversions.Add(nestedConversion); } return Conversion.MakeSwitchExpression(innerConversions.ToImmutableAndFree()); default: return Conversion.NoConversion; } } private Conversion GetConditionalExpressionConversion(BoundExpression source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!(source is BoundUnconvertedConditionalOperator conditionalOperator)) return Conversion.NoConversion; var trueConversion = this.ClassifyImplicitConversionFromExpression(conditionalOperator.Consequence, destination, ref useSiteInfo); if (!trueConversion.Exists) return Conversion.NoConversion; var falseConversion = this.ClassifyImplicitConversionFromExpression(conditionalOperator.Alternative, destination, ref useSiteInfo); if (!falseConversion.Exists) return Conversion.NoConversion; return Conversion.MakeConditionalExpression(ImmutableArray.Create(trueConversion, falseConversion)); } private static Conversion ClassifyNullLiteralConversion(BoundExpression source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!source.IsLiteralNull()) { return Conversion.NoConversion; } // SPEC: An implicit conversion exists from the null literal to any nullable type. if (destination.IsNullableType()) { // The spec defines a "null literal conversion" specifically as a conversion from // null to nullable type. return Conversion.NullLiteral; } // SPEC: An implicit conversion exists from the null literal to any reference type. // SPEC: An implicit conversion exists from the null literal to type parameter T, // SPEC: provided T is known to be a reference type. [...] The conversion [is] classified // SPEC: as implicit reference conversion. if (destination.IsReferenceType) { return Conversion.ImplicitReference; } // SPEC: The set of implicit conversions is extended to include... // SPEC: ... from the null literal to any pointer type. if (destination.IsPointerOrFunctionPointer()) { return Conversion.NullToPointer; } return Conversion.NoConversion; } private static Conversion ClassifyImplicitConstantExpressionConversion(BoundExpression source, TypeSymbol destination) { if (HasImplicitConstantExpressionConversion(source, destination)) { return Conversion.ImplicitConstant; } // strip nullable from the destination // // the following should work and it is an ImplicitNullable conversion // int? x = 1; if (destination.Kind == SymbolKind.NamedType) { var nt = (NamedTypeSymbol)destination; if (nt.OriginalDefinition.GetSpecialTypeSafe() == SpecialType.System_Nullable_T && HasImplicitConstantExpressionConversion(source, nt.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type)) { return new Conversion(ConversionKind.ImplicitNullable, Conversion.ImplicitConstantUnderlying); } } return Conversion.NoConversion; } private Conversion ClassifyImplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var tupleConversion = GetImplicitTupleLiteralConversion(source, destination, ref useSiteInfo); if (tupleConversion.Exists) { return tupleConversion; } // strip nullable from the destination // // the following should work and it is an ImplicitNullable conversion // (int, double)? x = (1,2); if (destination.Kind == SymbolKind.NamedType) { var nt = (NamedTypeSymbol)destination; if (nt.OriginalDefinition.GetSpecialTypeSafe() == SpecialType.System_Nullable_T) { var underlyingTupleConversion = GetImplicitTupleLiteralConversion(source, nt.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type, ref useSiteInfo); if (underlyingTupleConversion.Exists) { return new Conversion(ConversionKind.ImplicitNullable, ImmutableArray.Create(underlyingTupleConversion)); } } } return Conversion.NoConversion; } private Conversion ClassifyExplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { var tupleConversion = GetExplicitTupleLiteralConversion(source, destination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return tupleConversion; } // strip nullable from the destination // // the following should work and it is an ExplicitNullable conversion // var x = ((byte, string)?)(1,null); if (destination.Kind == SymbolKind.NamedType) { var nt = (NamedTypeSymbol)destination; if (nt.OriginalDefinition.GetSpecialTypeSafe() == SpecialType.System_Nullable_T) { var underlyingTupleConversion = GetExplicitTupleLiteralConversion(source, nt.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type, ref useSiteInfo, forCast); if (underlyingTupleConversion.Exists) { return new Conversion(ConversionKind.ExplicitNullable, ImmutableArray.Create(underlyingTupleConversion)); } } } return Conversion.NoConversion; } internal static bool HasImplicitConstantExpressionConversion(BoundExpression source, TypeSymbol destination) { var constantValue = source.ConstantValue; if (constantValue == null || (object)source.Type == null) { return false; } // An implicit constant expression conversion permits the following conversions: // A constant-expression of type int can be converted to type sbyte, byte, short, // ushort, uint, or ulong, provided the value of the constant-expression is within the // range of the destination type. var specialSource = source.Type.GetSpecialTypeSafe(); if (specialSource == SpecialType.System_Int32) { //if the constant value could not be computed, be generous and assume the conversion will work int value = constantValue.IsBad ? 0 : constantValue.Int32Value; switch (destination.GetSpecialTypeSafe()) { case SpecialType.System_Byte: return byte.MinValue <= value && value <= byte.MaxValue; case SpecialType.System_SByte: return sbyte.MinValue <= value && value <= sbyte.MaxValue; case SpecialType.System_Int16: return short.MinValue <= value && value <= short.MaxValue; case SpecialType.System_IntPtr when destination.IsNativeIntegerType: return true; case SpecialType.System_UInt32: case SpecialType.System_UIntPtr when destination.IsNativeIntegerType: return uint.MinValue <= value; case SpecialType.System_UInt64: return (int)ulong.MinValue <= value; case SpecialType.System_UInt16: return ushort.MinValue <= value && value <= ushort.MaxValue; default: return false; } } else if (specialSource == SpecialType.System_Int64 && destination.GetSpecialTypeSafe() == SpecialType.System_UInt64 && (constantValue.IsBad || 0 <= constantValue.Int64Value)) { // A constant-expression of type long can be converted to type ulong, provided the // value of the constant-expression is not negative. return true; } return false; } private Conversion ClassifyExplicitOnlyConversionFromExpression(BoundExpression sourceExpression, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { Debug.Assert(sourceExpression != null); Debug.Assert((object)destination != null); var sourceType = sourceExpression.Type; // NB: need to check for explicit tuple literal conversion before checking for explicit conversion from type // The same literal may have both explicit tuple conversion and explicit tuple literal conversion to the target type. // They are, however, observably different conversions via the order of argument evaluations and element-wise conversions if (sourceExpression.Kind == BoundKind.TupleLiteral) { Conversion tupleConversion = ClassifyExplicitTupleLiteralConversion((BoundTupleLiteral)sourceExpression, destination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return tupleConversion; } } if ((object)sourceType != null) { // Try using the short-circuit "fast-conversion" path. Conversion fastConversion = FastClassifyConversion(sourceType, destination); if (fastConversion.Exists) { return fastConversion; } else { var conversion = ClassifyExplicitBuiltInOnlyConversion(sourceType, destination, ref useSiteInfo, forCast); if (conversion.Exists) { return conversion; } } } return GetExplicitUserDefinedConversion(sourceExpression, sourceType, destination, ref useSiteInfo); } #nullable enable private static bool HasImplicitEnumerationConversion(BoundExpression source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: An implicit enumeration conversion permits the decimal-integer-literal 0 to be converted to any enum-type // SPEC: and to any nullable-type whose underlying type is an enum-type. // // For historical reasons we actually allow a conversion from any *numeric constant // zero* to be converted to any enum type, not just the literal integer zero. bool validType = destination.IsEnumType() || destination.IsNullableType() && destination.GetNullableUnderlyingType().IsEnumType(); if (!validType) { return false; } var sourceConstantValue = source.ConstantValue; return sourceConstantValue != null && source.Type is object && IsNumericType(source.Type) && IsConstantNumericZero(sourceConstantValue); } private static LambdaConversionResult IsAnonymousFunctionCompatibleWithDelegate(UnboundLambda anonymousFunction, TypeSymbol type, bool isTargetExpressionTree) { Debug.Assert((object)anonymousFunction != null); Debug.Assert((object)type != null); // SPEC: An anonymous-method-expression or lambda-expression is classified as an anonymous function. // SPEC: The expression does not have a type but can be implicitly converted to a compatible delegate // SPEC: type or expression tree type. Specifically, a delegate type D is compatible with an // SPEC: anonymous function F provided: var delegateType = (NamedTypeSymbol)type; var invokeMethod = delegateType.DelegateInvokeMethod; if ((object)invokeMethod == null || invokeMethod.HasUseSiteError) { return LambdaConversionResult.BadTargetType; } if (anonymousFunction.HasExplicitReturnType(out var refKind, out var returnType)) { if (invokeMethod.RefKind != refKind || !invokeMethod.ReturnType.Equals(returnType.Type, TypeCompareKind.AllIgnoreOptions)) { return LambdaConversionResult.MismatchedReturnType; } } var delegateParameters = invokeMethod.Parameters; // SPEC: If F contains an anonymous-function-signature, then D and F have the same number of parameters. // SPEC: If F does not contain an anonymous-function-signature, then D may have zero or more parameters // SPEC: of any type, as long as no parameter of D has the out parameter modifier. if (anonymousFunction.HasSignature) { if (anonymousFunction.ParameterCount != invokeMethod.ParameterCount) { return LambdaConversionResult.BadParameterCount; } // SPEC: If F has an explicitly typed parameter list, each parameter in D has the same type // SPEC: and modifiers as the corresponding parameter in F. // SPEC: If F has an implicitly typed parameter list, D has no ref or out parameters. if (anonymousFunction.HasExplicitlyTypedParameterList) { for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].RefKind != anonymousFunction.RefKind(p) || !delegateParameters[p].Type.Equals(anonymousFunction.ParameterType(p), TypeCompareKind.AllIgnoreOptions)) { return LambdaConversionResult.MismatchedParameterType; } } } else { for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].RefKind != RefKind.None) { return LambdaConversionResult.RefInImplicitlyTypedLambda; } } // In C# it is not possible to make a delegate type // such that one of its parameter types is a static type. But static types are // in metadata just sealed abstract types; there is nothing stopping someone in // another language from creating a delegate with a static type for a parameter, // though the only argument you could pass for that parameter is null. // // In the native compiler we forbid conversion of an anonymous function that has // an implicitly-typed parameter list to a delegate type that has a static type // for a formal parameter type. However, we do *not* forbid it for an explicitly- // typed lambda (because we already require that the explicitly typed parameter not // be static) and we do not forbid it for an anonymous method with the entire // parameter list missing (because the body cannot possibly have a parameter that // is of static type, even though this means that we will be generating a hidden // method with a parameter of static type.) // // We also allow more exotic situations to work in the native compiler. For example, // though it is not possible to convert x=>{} to Action<GC>, it is possible to convert // it to Action<List<GC>> should there be a language that allows you to construct // a variable of that type. // // We might consider beefing up this rule to disallow a conversion of *any* anonymous // function to *any* delegate that has a static type *anywhere* in the parameter list. for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].TypeWithAnnotations.IsStatic) { return LambdaConversionResult.StaticTypeInImplicitlyTypedLambda; } } } } else { for (int p = 0; p < delegateParameters.Length; ++p) { if (delegateParameters[p].RefKind == RefKind.Out) { return LambdaConversionResult.MissingSignatureWithOutParameter; } } } // Ensure the body can be converted to that delegate type var bound = anonymousFunction.Bind(delegateType, isTargetExpressionTree); if (ErrorFacts.PreventsSuccessfulDelegateConversion(bound.Diagnostics.Diagnostics)) { return LambdaConversionResult.BindingFailed; } return LambdaConversionResult.Success; } private static LambdaConversionResult IsAnonymousFunctionCompatibleWithExpressionTree(UnboundLambda anonymousFunction, NamedTypeSymbol type) { Debug.Assert((object)anonymousFunction != null); Debug.Assert((object)type != null); Debug.Assert(type.IsGenericOrNonGenericExpressionType(out _)); // SPEC OMISSION: // // The C# 3 spec said that anonymous methods and statement lambdas are *convertible* to expression tree // types if the anonymous method/statement lambda is convertible to its delegate type; however, actually // *using* such a conversion is an error. However, that is not what we implemented. In C# 3 we implemented // that an anonymous method is *not convertible* to an expression tree type, period. (Statement lambdas // used the rule described in the spec.) // // This appears to be a spec omission; the intention is to make old-style anonymous methods not // convertible to expression trees. var delegateType = type.Arity == 0 ? null : type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type; if (delegateType is { } && !delegateType.IsDelegateType()) { return LambdaConversionResult.ExpressionTreeMustHaveDelegateTypeArgument; } if (anonymousFunction.Syntax.Kind() == SyntaxKind.AnonymousMethodExpression) { return LambdaConversionResult.ExpressionTreeFromAnonymousMethod; } if (delegateType is null) { return LambdaConversionResult.Success; } return IsAnonymousFunctionCompatibleWithDelegate(anonymousFunction, delegateType, isTargetExpressionTree: true); } public static LambdaConversionResult IsAnonymousFunctionCompatibleWithType(UnboundLambda anonymousFunction, TypeSymbol type) { Debug.Assert((object)anonymousFunction != null); Debug.Assert((object)type != null); if (type.SpecialType == SpecialType.System_Delegate) { return LambdaConversionResult.Success; } else if (type.IsDelegateType()) { return IsAnonymousFunctionCompatibleWithDelegate(anonymousFunction, type, isTargetExpressionTree: false); } else if (type.IsGenericOrNonGenericExpressionType(out bool _)) { return IsAnonymousFunctionCompatibleWithExpressionTree(anonymousFunction, (NamedTypeSymbol)type); } return LambdaConversionResult.BadTargetType; } private static bool HasAnonymousFunctionConversion(BoundExpression source, TypeSymbol destination) { Debug.Assert(source != null); Debug.Assert((object)destination != null); if (source.Kind != BoundKind.UnboundLambda) { return false; } return IsAnonymousFunctionCompatibleWithType((UnboundLambda)source, destination) == LambdaConversionResult.Success; } #nullable disable internal Conversion ClassifyImplicitUserDefinedConversionForV6SwitchGoverningType(TypeSymbol sourceType, out TypeSymbol switchGoverningType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The governing type of a switch statement is established by the switch expression. // SPEC: 1) If the type of the switch expression is sbyte, byte, short, ushort, int, uint, // SPEC: long, ulong, bool, char, string, or an enum-type, or if it is the nullable type // SPEC: corresponding to one of these types, then that is the governing type of the switch statement. // SPEC: 2) Otherwise, exactly one user-defined implicit conversion (§6.4) must exist from the // SPEC: type of the switch expression to one of the following possible governing types: // SPEC: sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or, a nullable type // SPEC: corresponding to one of those types // NOTE: We should be called only if (1) is false for source type. Debug.Assert((object)sourceType != null); Debug.Assert(!sourceType.IsValidV6SwitchGoverningType()); UserDefinedConversionResult result = AnalyzeImplicitUserDefinedConversionForV6SwitchGoverningType(sourceType, ref useSiteInfo); if (result.Kind == UserDefinedConversionResultKind.Valid) { UserDefinedConversionAnalysis analysis = result.Results[result.Best]; switchGoverningType = analysis.ToType; Debug.Assert(switchGoverningType.IsValidV6SwitchGoverningType(isTargetTypeOfUserDefinedOp: true)); } else { switchGoverningType = null; } return new Conversion(result, isImplicit: true); } internal Conversion GetCallerLineNumberConversion(TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var greenNode = new Syntax.InternalSyntax.LiteralExpressionSyntax(SyntaxKind.NumericLiteralExpression, new Syntax.InternalSyntax.SyntaxToken(SyntaxKind.NumericLiteralToken)); var syntaxNode = new LiteralExpressionSyntax(greenNode, null, 0); TypeSymbol expectedAttributeType = corLibrary.GetSpecialType(SpecialType.System_Int32); BoundLiteral intMaxValueLiteral = new BoundLiteral(syntaxNode, ConstantValue.Create(int.MaxValue), expectedAttributeType); return ClassifyStandardImplicitConversion(intMaxValueLiteral, expectedAttributeType, destination, ref useSiteInfo); } internal bool HasCallerLineNumberConversion(TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return GetCallerLineNumberConversion(destination, ref useSiteInfo).Exists; } internal bool HasCallerInfoStringConversion(TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { TypeSymbol expectedAttributeType = corLibrary.GetSpecialType(SpecialType.System_String); Conversion conversion = ClassifyStandardImplicitConversion(expectedAttributeType, destination, ref useSiteInfo); return conversion.Exists; } public static bool HasIdentityConversion(TypeSymbol type1, TypeSymbol type2) { return HasIdentityConversionInternal(type1, type2, includeNullability: false); } private static bool HasIdentityConversionInternal(TypeSymbol type1, TypeSymbol type2, bool includeNullability) { // Spec (6.1.1): // An identity conversion converts from any type to the same type. This conversion exists // such that an entity that already has a required type can be said to be convertible to // that type. // // Because object and dynamic are considered equivalent there is an identity conversion // between object and dynamic, and between constructed types that are the same when replacing // all occurrences of dynamic with object. Debug.Assert((object)type1 != null); Debug.Assert((object)type2 != null); // Note, when we are paying attention to nullability, we ignore oblivious mismatch. // See TypeCompareKind.ObliviousNullableModifierMatchesAny var compareKind = includeNullability ? TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.IgnoreNullableModifiersForReferenceTypes : TypeCompareKind.AllIgnoreOptions; return type1.Equals(type2, compareKind); } private bool HasIdentityConversionInternal(TypeSymbol type1, TypeSymbol type2) { return HasIdentityConversionInternal(type1, type2, IncludeNullability); } /// <summary> /// Returns true if: /// - Either type has no nullability information (oblivious). /// - Both types cannot have different nullability at the same time, /// including the case of type parameters that by themselves can represent nullable and not nullable reference types. /// </summary> internal bool HasTopLevelNullabilityIdentityConversion(TypeWithAnnotations source, TypeWithAnnotations destination) { if (!IncludeNullability) { return true; } if (source.NullableAnnotation.IsOblivious() || destination.NullableAnnotation.IsOblivious()) { return true; } var sourceIsPossiblyNullableTypeParameter = IsPossiblyNullableTypeTypeParameter(source); var destinationIsPossiblyNullableTypeParameter = IsPossiblyNullableTypeTypeParameter(destination); if (sourceIsPossiblyNullableTypeParameter && !destinationIsPossiblyNullableTypeParameter) { return destination.NullableAnnotation.IsAnnotated(); } if (destinationIsPossiblyNullableTypeParameter && !sourceIsPossiblyNullableTypeParameter) { return source.NullableAnnotation.IsAnnotated(); } return source.NullableAnnotation.IsAnnotated() == destination.NullableAnnotation.IsAnnotated(); } /// <summary> /// Returns false if source type can be nullable at the same time when destination type can be not nullable, /// including the case of type parameters that by themselves can represent nullable and not nullable reference types. /// When either type has no nullability information (oblivious), this method returns true. /// </summary> internal bool HasTopLevelNullabilityImplicitConversion(TypeWithAnnotations source, TypeWithAnnotations destination) { if (!IncludeNullability) { return true; } if (source.NullableAnnotation.IsOblivious() || destination.NullableAnnotation.IsOblivious() || destination.NullableAnnotation.IsAnnotated()) { return true; } if (IsPossiblyNullableTypeTypeParameter(source) && !IsPossiblyNullableTypeTypeParameter(destination)) { return false; } return !source.NullableAnnotation.IsAnnotated(); } private static bool IsPossiblyNullableTypeTypeParameter(in TypeWithAnnotations typeWithAnnotations) { var type = typeWithAnnotations.Type; return type is object && (type.IsPossiblyNullableReferenceTypeTypeParameter() || type.IsNullableTypeOrTypeParameter()); } /// <summary> /// Returns false if the source does not have an implicit conversion to the destination /// because of either incompatible top level or nested nullability. /// </summary> public bool HasAnyNullabilityImplicitConversion(TypeWithAnnotations source, TypeWithAnnotations destination) { Debug.Assert(IncludeNullability); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return HasTopLevelNullabilityImplicitConversion(source, destination) && ClassifyImplicitConversionFromType(source.Type, destination.Type, ref discardedUseSiteInfo).Kind != ConversionKind.NoConversion; } public static bool HasIdentityConversionToAny<T>(T type, ArrayBuilder<T> targetTypes) where T : TypeSymbol { foreach (var targetType in targetTypes) { if (HasIdentityConversionInternal(type, targetType, includeNullability: false)) { return true; } } return false; } public Conversion ConvertExtensionMethodThisArg(TypeSymbol parameterType, TypeSymbol thisType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)thisType != null); var conversion = this.ClassifyImplicitExtensionMethodThisArgConversion(null, thisType, parameterType, ref useSiteInfo); return IsValidExtensionMethodThisArgConversion(conversion) ? conversion : Conversion.NoConversion; } // Spec 7.6.5.2: "An extension method ... is eligible if ... [an] implicit identity, reference, // or boxing conversion exists from expr to the type of the first parameter" public Conversion ClassifyImplicitExtensionMethodThisArgConversion(BoundExpression sourceExpressionOpt, TypeSymbol sourceType, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceExpressionOpt == null || (object)sourceExpressionOpt.Type == sourceType); Debug.Assert((object)destination != null); if ((object)sourceType != null) { if (HasIdentityConversionInternal(sourceType, destination)) { return Conversion.Identity; } if (HasBoxingConversion(sourceType, destination, ref useSiteInfo)) { return Conversion.Boxing; } if (HasImplicitReferenceConversion(sourceType, destination, ref useSiteInfo)) { return Conversion.ImplicitReference; } } if (sourceExpressionOpt?.Kind == BoundKind.TupleLiteral) { // GetTupleLiteralConversion is not used with IncludeNullability currently. // If that changes, the delegate below will need to consider top-level nullability. Debug.Assert(!IncludeNullability); var tupleConversion = GetTupleLiteralConversion( (BoundTupleLiteral)sourceExpressionOpt, destination, ref useSiteInfo, ConversionKind.ImplicitTupleLiteral, (ConversionsBase conversions, BoundExpression s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => conversions.ClassifyImplicitExtensionMethodThisArgConversion(s, s.Type, d.Type, ref u), arg: false); if (tupleConversion.Exists) { return tupleConversion; } } if ((object)sourceType != null) { var tupleConversion = ClassifyTupleConversion( sourceType, destination, ref useSiteInfo, ConversionKind.ImplicitTuple, (ConversionsBase conversions, TypeWithAnnotations s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => { if (!conversions.HasTopLevelNullabilityImplicitConversion(s, d)) { return Conversion.NoConversion; } return conversions.ClassifyImplicitExtensionMethodThisArgConversion(null, s.Type, d.Type, ref u); }, arg: false); if (tupleConversion.Exists) { return tupleConversion; } } return Conversion.NoConversion; } // It should be possible to remove IsValidExtensionMethodThisArgConversion // since ClassifyImplicitExtensionMethodThisArgConversion should only // return valid conversions. https://github.com/dotnet/roslyn/issues/19622 // Spec 7.6.5.2: "An extension method ... is eligible if ... [an] implicit identity, reference, // or boxing conversion exists from expr to the type of the first parameter" public static bool IsValidExtensionMethodThisArgConversion(Conversion conversion) { switch (conversion.Kind) { case ConversionKind.Identity: case ConversionKind.Boxing: case ConversionKind.ImplicitReference: return true; case ConversionKind.ImplicitTuple: case ConversionKind.ImplicitTupleLiteral: // check if all element conversions satisfy the requirement foreach (var elementConversion in conversion.UnderlyingConversions) { if (!IsValidExtensionMethodThisArgConversion(elementConversion)) { return false; } } return true; default: // Caller should have not have calculated another conversion. Debug.Assert(conversion.Kind == ConversionKind.NoConversion); return false; } } private const bool F = false; private const bool T = true; // Notice that there is no implicit numeric conversion from a type to itself. That's an // identity conversion. private static readonly bool[,] s_implicitNumericConversions = { // to sb b s us i ui l ul c f d m // from /* sb */ { F, F, T, F, T, F, T, F, F, T, T, T }, /* b */ { F, F, T, T, T, T, T, T, F, T, T, T }, /* s */ { F, F, F, F, T, F, T, F, F, T, T, T }, /* us */ { F, F, F, F, T, T, T, T, F, T, T, T }, /* i */ { F, F, F, F, F, F, T, F, F, T, T, T }, /* ui */ { F, F, F, F, F, F, T, T, F, T, T, T }, /* l */ { F, F, F, F, F, F, F, F, F, T, T, T }, /* ul */ { F, F, F, F, F, F, F, F, F, T, T, T }, /* c */ { F, F, F, T, T, T, T, T, F, T, T, T }, /* f */ { F, F, F, F, F, F, F, F, F, F, T, F }, /* d */ { F, F, F, F, F, F, F, F, F, F, F, F }, /* m */ { F, F, F, F, F, F, F, F, F, F, F, F } }; private static readonly bool[,] s_explicitNumericConversions = { // to sb b s us i ui l ul c f d m // from /* sb */ { F, T, F, T, F, T, F, T, T, F, F, F }, /* b */ { T, F, F, F, F, F, F, F, T, F, F, F }, /* s */ { T, T, F, T, F, T, F, T, T, F, F, F }, /* us */ { T, T, T, F, F, F, F, F, T, F, F, F }, /* i */ { T, T, T, T, F, T, F, T, T, F, F, F }, /* ui */ { T, T, T, T, T, F, F, F, T, F, F, F }, /* l */ { T, T, T, T, T, T, F, T, T, F, F, F }, /* ul */ { T, T, T, T, T, T, T, F, T, F, F, F }, /* c */ { T, T, T, F, F, F, F, F, F, F, F, F }, /* f */ { T, T, T, T, T, T, T, T, T, F, F, T }, /* d */ { T, T, T, T, T, T, T, T, T, T, F, T }, /* m */ { T, T, T, T, T, T, T, T, T, T, T, F } }; private static int GetNumericTypeIndex(SpecialType specialType) { switch (specialType) { case SpecialType.System_SByte: return 0; case SpecialType.System_Byte: return 1; case SpecialType.System_Int16: return 2; case SpecialType.System_UInt16: return 3; case SpecialType.System_Int32: return 4; case SpecialType.System_UInt32: return 5; case SpecialType.System_Int64: return 6; case SpecialType.System_UInt64: return 7; case SpecialType.System_Char: return 8; case SpecialType.System_Single: return 9; case SpecialType.System_Double: return 10; case SpecialType.System_Decimal: return 11; default: return -1; } } #nullable enable private static bool HasImplicitNumericConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); int sourceIndex = GetNumericTypeIndex(source.SpecialType); if (sourceIndex < 0) { return false; } int destinationIndex = GetNumericTypeIndex(destination.SpecialType); if (destinationIndex < 0) { return false; } return s_implicitNumericConversions[sourceIndex, destinationIndex]; } private static bool HasExplicitNumericConversion(TypeSymbol source, TypeSymbol destination) { // SPEC: The explicit numeric conversions are the conversions from a numeric-type to another // SPEC: numeric-type for which an implicit numeric conversion does not already exist. Debug.Assert((object)source != null); Debug.Assert((object)destination != null); int sourceIndex = GetNumericTypeIndex(source.SpecialType); if (sourceIndex < 0) { return false; } int destinationIndex = GetNumericTypeIndex(destination.SpecialType); if (destinationIndex < 0) { return false; } return s_explicitNumericConversions[sourceIndex, destinationIndex]; } private static bool IsConstantNumericZero(ConstantValue value) { switch (value.Discriminator) { case ConstantValueTypeDiscriminator.SByte: return value.SByteValue == 0; case ConstantValueTypeDiscriminator.Byte: return value.ByteValue == 0; case ConstantValueTypeDiscriminator.Int16: return value.Int16Value == 0; case ConstantValueTypeDiscriminator.Int32: case ConstantValueTypeDiscriminator.NInt: return value.Int32Value == 0; case ConstantValueTypeDiscriminator.Int64: return value.Int64Value == 0; case ConstantValueTypeDiscriminator.UInt16: return value.UInt16Value == 0; case ConstantValueTypeDiscriminator.UInt32: case ConstantValueTypeDiscriminator.NUInt: return value.UInt32Value == 0; case ConstantValueTypeDiscriminator.UInt64: return value.UInt64Value == 0; case ConstantValueTypeDiscriminator.Single: case ConstantValueTypeDiscriminator.Double: return value.DoubleValue == 0; case ConstantValueTypeDiscriminator.Decimal: return value.DecimalValue == 0; } return false; } private static bool IsNumericType(TypeSymbol type) { switch (type.SpecialType) { case SpecialType.System_Char: case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Single: case SpecialType.System_Double: case SpecialType.System_Decimal: case SpecialType.System_IntPtr when type.IsNativeIntegerType: case SpecialType.System_UIntPtr when type.IsNativeIntegerType: return true; default: return false; } } private static bool HasSpecialIntPtrConversion(TypeSymbol source, TypeSymbol target) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); // There are only a total of twelve user-defined explicit conversions on IntPtr and UIntPtr: // // IntPtr <---> int // IntPtr <---> long // IntPtr <---> void* // UIntPtr <---> uint // UIntPtr <---> ulong // UIntPtr <---> void* // // The specification says that you can put any *standard* implicit or explicit conversion // on "either side" of a user-defined explicit conversion, so the specification allows, say, // UIntPtr --> byte because the conversion UIntPtr --> uint is user-defined and the // conversion uint --> byte is "standard". It is "standard" because the conversion // byte --> uint is an implicit numeric conversion. // This means that certain conversions should be illegal. For example, IntPtr --> ulong // should be illegal because none of int --> ulong, long --> ulong and void* --> ulong // are "standard" conversions. // Similarly, some conversions involving IntPtr should be illegal because they are // ambiguous. byte --> IntPtr?, for example, is ambiguous. (There are four possible // UD operators: int --> IntPtr and long --> IntPtr, and their lifted versions. The // best possible source type is int, the best possible target type is IntPtr?, and // there is an ambiguity between the unlifted int --> IntPtr, and the lifted // int? --> IntPtr? conversions.) // In practice, the native compiler, and hence, the Roslyn compiler, allows all // these conversions. Any conversion from a numeric type to IntPtr, or from an IntPtr // to a numeric type, is allowed. Also, any conversion from a pointer type to IntPtr // or vice versa is allowed. var s0 = source.StrippedType(); var t0 = target.StrippedType(); TypeSymbol otherType; if (isIntPtrOrUIntPtr(s0)) { otherType = t0; } else if (isIntPtrOrUIntPtr(t0)) { otherType = s0; } else { return false; } if (otherType.IsPointerOrFunctionPointer()) { return true; } if (otherType.TypeKind == TypeKind.Enum) { return true; } switch (otherType.SpecialType) { case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Char: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: case SpecialType.System_Double: case SpecialType.System_Single: case SpecialType.System_Decimal: return true; } return false; static bool isIntPtrOrUIntPtr(TypeSymbol type) => (type.SpecialType == SpecialType.System_IntPtr || type.SpecialType == SpecialType.System_UIntPtr) && !type.IsNativeIntegerType; } private static bool HasExplicitEnumerationConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: The explicit enumeration conversions are: // SPEC: From sbyte, byte, short, ushort, int, uint, long, ulong, nint, nuint, char, float, double, or decimal to any enum-type. // SPEC: From any enum-type to sbyte, byte, short, ushort, int, uint, long, ulong, nint, nuint, char, float, double, or decimal. // SPEC: From any enum-type to any other enum-type. if (IsNumericType(source) && destination.IsEnumType()) { return true; } if (IsNumericType(destination) && source.IsEnumType()) { return true; } if (source.IsEnumType() && destination.IsEnumType()) { return true; } return false; } #nullable disable private Conversion ClassifyImplicitNullableConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: Predefined implicit conversions that operate on non-nullable value types can also be used with // SPEC: nullable forms of those types. For each of the predefined implicit identity, numeric and tuple conversions // SPEC: that convert from a non-nullable value type S to a non-nullable value type T, the following implicit // SPEC: nullable conversions exist: // SPEC: * An implicit conversion from S? to T?. // SPEC: * An implicit conversion from S to T?. if (!destination.IsNullableType()) { return Conversion.NoConversion; } TypeSymbol unwrappedDestination = destination.GetNullableUnderlyingType(); TypeSymbol unwrappedSource = source.StrippedType(); if (!unwrappedSource.IsValueType) { return Conversion.NoConversion; } if (HasIdentityConversionInternal(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ImplicitNullable, Conversion.IdentityUnderlying); } if (HasImplicitNumericConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ImplicitNullable, Conversion.ImplicitNumericUnderlying); } var tupleConversion = ClassifyImplicitTupleConversion(unwrappedSource, unwrappedDestination, ref useSiteInfo); if (tupleConversion.Exists) { return new Conversion(ConversionKind.ImplicitNullable, ImmutableArray.Create(tupleConversion)); } return Conversion.NoConversion; } private delegate Conversion ClassifyConversionFromExpressionDelegate(ConversionsBase conversions, BoundExpression sourceExpression, TypeWithAnnotations destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool arg); private delegate Conversion ClassifyConversionFromTypeDelegate(ConversionsBase conversions, TypeWithAnnotations source, TypeWithAnnotations destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool arg); private Conversion GetImplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // GetTupleLiteralConversion is not used with IncludeNullability currently. // If that changes, the delegate below will need to consider top-level nullability. Debug.Assert(!IncludeNullability); return GetTupleLiteralConversion( source, destination, ref useSiteInfo, ConversionKind.ImplicitTupleLiteral, (ConversionsBase conversions, BoundExpression s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => conversions.ClassifyImplicitConversionFromExpression(s, d.Type, ref u), arg: false); } private Conversion GetExplicitTupleLiteralConversion(BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { // GetTupleLiteralConversion is not used with IncludeNullability currently. // If that changes, the delegate below will need to consider top-level nullability. Debug.Assert(!IncludeNullability); return GetTupleLiteralConversion( source, destination, ref useSiteInfo, ConversionKind.ExplicitTupleLiteral, (ConversionsBase conversions, BoundExpression s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => conversions.ClassifyConversionFromExpression(s, d.Type, ref u, a), forCast); } private Conversion GetTupleLiteralConversion( BoundTupleLiteral source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConversionKind kind, ClassifyConversionFromExpressionDelegate classifyConversion, bool arg) { var arguments = source.Arguments; // check if the type is actually compatible type for a tuple of given cardinality if (!destination.IsTupleTypeOfCardinality(arguments.Length)) { return Conversion.NoConversion; } var targetElementTypes = destination.TupleElementTypesWithAnnotations; Debug.Assert(arguments.Length == targetElementTypes.Length); // check arguments against flattened list of target element types var argumentConversions = ArrayBuilder<Conversion>.GetInstance(arguments.Length); for (int i = 0; i < arguments.Length; i++) { var argument = arguments[i]; var result = classifyConversion(this, argument, targetElementTypes[i], ref useSiteInfo, arg); if (!result.Exists) { argumentConversions.Free(); return Conversion.NoConversion; } argumentConversions.Add(result); } return new Conversion(kind, argumentConversions.ToImmutableAndFree()); } private Conversion ClassifyImplicitTupleConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ClassifyTupleConversion( source, destination, ref useSiteInfo, ConversionKind.ImplicitTuple, (ConversionsBase conversions, TypeWithAnnotations s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => { if (!conversions.HasTopLevelNullabilityImplicitConversion(s, d)) { return Conversion.NoConversion; } return conversions.ClassifyImplicitConversionFromType(s.Type, d.Type, ref u); }, arg: false); } private Conversion ClassifyExplicitTupleConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { return ClassifyTupleConversion( source, destination, ref useSiteInfo, ConversionKind.ExplicitTuple, (ConversionsBase conversions, TypeWithAnnotations s, TypeWithAnnotations d, ref CompoundUseSiteInfo<AssemblySymbol> u, bool a) => { if (!conversions.HasTopLevelNullabilityImplicitConversion(s, d)) { return Conversion.NoConversion; } return conversions.ClassifyConversionFromType(s.Type, d.Type, ref u, a); }, forCast); } private Conversion ClassifyTupleConversion( TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConversionKind kind, ClassifyConversionFromTypeDelegate classifyConversion, bool arg) { ImmutableArray<TypeWithAnnotations> sourceTypes; ImmutableArray<TypeWithAnnotations> destTypes; if (!source.TryGetElementTypesWithAnnotationsIfTupleType(out sourceTypes) || !destination.TryGetElementTypesWithAnnotationsIfTupleType(out destTypes) || sourceTypes.Length != destTypes.Length) { return Conversion.NoConversion; } var nestedConversions = ArrayBuilder<Conversion>.GetInstance(sourceTypes.Length); for (int i = 0; i < sourceTypes.Length; i++) { var conversion = classifyConversion(this, sourceTypes[i], destTypes[i], ref useSiteInfo, arg); if (!conversion.Exists) { nestedConversions.Free(); return Conversion.NoConversion; } nestedConversions.Add(conversion); } return new Conversion(kind, nestedConversions.ToImmutableAndFree()); } private Conversion ClassifyExplicitNullableConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, bool forCast) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: Explicit nullable conversions permit predefined explicit conversions that operate on // SPEC: non-nullable value types to also be used with nullable forms of those types. For // SPEC: each of the predefined explicit conversions that convert from a non-nullable value type // SPEC: S to a non-nullable value type T, the following nullable conversions exist: // SPEC: An explicit conversion from S? to T?. // SPEC: An explicit conversion from S to T?. // SPEC: An explicit conversion from S? to T. if (!source.IsNullableType() && !destination.IsNullableType()) { return Conversion.NoConversion; } TypeSymbol unwrappedSource = source.StrippedType(); TypeSymbol unwrappedDestination = destination.StrippedType(); if (HasIdentityConversionInternal(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.IdentityUnderlying); } if (HasImplicitNumericConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.ImplicitNumericUnderlying); } if (HasExplicitNumericConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.ExplicitNumericUnderlying); } var tupleConversion = ClassifyExplicitTupleConversion(unwrappedSource, unwrappedDestination, ref useSiteInfo, forCast); if (tupleConversion.Exists) { return new Conversion(ConversionKind.ExplicitNullable, ImmutableArray.Create(tupleConversion)); } if (HasExplicitEnumerationConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.ExplicitEnumerationUnderlying); } if (HasPointerToIntegerConversion(unwrappedSource, unwrappedDestination)) { return new Conversion(ConversionKind.ExplicitNullable, Conversion.PointerToIntegerUnderlying); } return Conversion.NoConversion; } private bool HasCovariantArrayConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); var s = source as ArrayTypeSymbol; var d = destination as ArrayTypeSymbol; if ((object)s == null || (object)d == null) { return false; } // * S and T differ only in element type. In other words, S and T have the same number of dimensions. if (!s.HasSameShapeAs(d)) { return false; } // * Both SE and TE are reference types. // * An implicit reference conversion exists from SE to TE. return HasImplicitReferenceConversion(s.ElementTypeWithAnnotations, d.ElementTypeWithAnnotations, ref useSiteInfo); } public bool HasIdentityOrImplicitReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return true; } return HasImplicitReferenceConversion(source, destination, ref useSiteInfo); } private static bool HasImplicitDynamicConversionFromExpression(TypeSymbol expressionType, TypeSymbol destination) { // Spec (§6.1.8) // An implicit dynamic conversion exists from an expression of type dynamic to any type T. Debug.Assert((object)destination != null); return expressionType?.Kind == SymbolKind.DynamicType && !destination.IsPointerOrFunctionPointer(); } private static bool HasExplicitDynamicConversion(TypeSymbol source, TypeSymbol destination) { // SPEC: An explicit dynamic conversion exists from an expression of [sic] type dynamic to any type T. // ISSUE: The "an expression of" part of the spec is probably an error; see https://github.com/dotnet/csharplang/issues/132 Debug.Assert((object)source != null); Debug.Assert((object)destination != null); return source.Kind == SymbolKind.DynamicType && !destination.IsPointerOrFunctionPointer(); } private bool HasArrayConversionToInterface(ArrayTypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!source.IsSZArray) { return false; } if (!destination.IsInterfaceType()) { return false; } // The specification says that there is a conversion: // * From a single-dimensional array type S[] to IList<T> and its base // interfaces, provided that there is an implicit identity or reference // conversion from S to T. // // Newer versions of the framework also have arrays be convertible to // IReadOnlyList<T> and IReadOnlyCollection<T>; we honor that as well. // // Therefore we must check for: // // IList<T> // ICollection<T> // IEnumerable<T> // IEnumerable // IReadOnlyList<T> // IReadOnlyCollection<T> if (destination.SpecialType == SpecialType.System_Collections_IEnumerable) { return true; } NamedTypeSymbol destinationAgg = (NamedTypeSymbol)destination; if (destinationAgg.AllTypeArgumentCount() != 1) { return false; } if (!destinationAgg.IsPossibleArrayGenericInterface()) { return false; } TypeWithAnnotations elementType = source.ElementTypeWithAnnotations; TypeWithAnnotations argument0 = destinationAgg.TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo); if (IncludeNullability && !HasTopLevelNullabilityImplicitConversion(elementType, argument0)) { return false; } return HasIdentityOrImplicitReferenceConversion(elementType.Type, argument0.Type, ref useSiteInfo); } private bool HasImplicitReferenceConversion(TypeWithAnnotations source, TypeWithAnnotations destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (IncludeNullability) { if (!HasTopLevelNullabilityImplicitConversion(source, destination)) { return false; } // Check for identity conversion of underlying types if the top-level nullability is distinct. // (An identity conversion where nullability matches is not considered an implicit reference conversion.) if (source.NullableAnnotation != destination.NullableAnnotation && HasIdentityConversionInternal(source.Type, destination.Type, includeNullability: true)) { return true; } } return HasImplicitReferenceConversion(source.Type, destination.Type, ref useSiteInfo); } internal bool HasImplicitReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsErrorType()) { return false; } if (!source.IsReferenceType) { return false; } // SPEC: The implicit reference conversions are: // SPEC: UNDONE: From any reference-type to a reference-type T if it has an implicit identity // SPEC: UNDONE: or reference conversion to a reference-type T0 and T0 has an identity conversion to T. // UNDONE: Is the right thing to do here to strip dynamic off and check for convertibility? // SPEC: From any reference type to object and dynamic. if (destination.SpecialType == SpecialType.System_Object || destination.Kind == SymbolKind.DynamicType) { return true; } switch (source.TypeKind) { case TypeKind.Class: // SPEC: From any class type S to any class type T provided S is derived from T. if (destination.IsClassType() && IsBaseClass(source, destination, ref useSiteInfo)) { return true; } return HasImplicitConversionToInterface(source, destination, ref useSiteInfo); case TypeKind.Interface: // SPEC: From any interface-type S to any interface-type T, provided S is derived from T. // NOTE: This handles variance conversions return HasImplicitConversionToInterface(source, destination, ref useSiteInfo); case TypeKind.Delegate: // SPEC: From any delegate-type to System.Delegate and the interfaces it implements. // NOTE: This handles variance conversions. return HasImplicitConversionFromDelegate(source, destination, ref useSiteInfo); case TypeKind.TypeParameter: return HasImplicitReferenceTypeParameterConversion((TypeParameterSymbol)source, destination, ref useSiteInfo); case TypeKind.Array: // SPEC: From an array-type S ... to an array-type T, provided ... // SPEC: From any array-type to System.Array and the interfaces it implements. // SPEC: From a single-dimensional array type S[] to IList<T>, provided ... return HasImplicitConversionFromArray(source, destination, ref useSiteInfo); } // UNDONE: Implicit conversions involving type parameters that are known to be reference types. return false; } private bool HasImplicitConversionToInterface(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!destination.IsInterfaceType()) { return false; } // * From any class type S to any interface type T provided S implements an interface // convertible to T. if (source.IsClassType()) { return HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo); } // * From any interface type S to any interface type T provided S implements an interface // convertible to T. // * From any interface type S to any interface type T provided S is not T and S is // an interface convertible to T. if (source.IsInterfaceType()) { if (HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo)) { return true; } if (!HasIdentityConversionInternal(source, destination) && HasInterfaceVarianceConversion(source, destination, ref useSiteInfo)) { return true; } } return false; } private bool HasImplicitConversionFromArray(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { ArrayTypeSymbol s = source as ArrayTypeSymbol; if ((object)s == null) { return false; } // * From an array type S with an element type SE to an array type T with element type TE // provided that all of the following are true: // * S and T differ only in element type. In other words, S and T have the same number of dimensions. // * Both SE and TE are reference types. // * An implicit reference conversion exists from SE to TE. if (HasCovariantArrayConversion(source, destination, ref useSiteInfo)) { return true; } // * From any array type to System.Array or any interface implemented by System.Array. if (destination.GetSpecialTypeSafe() == SpecialType.System_Array) { return true; } if (IsBaseInterface(destination, this.corLibrary.GetDeclaredSpecialType(SpecialType.System_Array), ref useSiteInfo)) { return true; } // * From a single-dimensional array type S[] to IList<T> and its base // interfaces, provided that there is an implicit identity or reference // conversion from S to T. if (HasArrayConversionToInterface(s, destination, ref useSiteInfo)) { return true; } return false; } private bool HasImplicitConversionFromDelegate(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!source.IsDelegateType()) { return false; } // * From any delegate type to System.Delegate // // SPEC OMISSION: // // The spec should actually say // // * From any delegate type to System.Delegate // * From any delegate type to System.MulticastDelegate // * From any delegate type to any interface implemented by System.MulticastDelegate var specialDestination = destination.GetSpecialTypeSafe(); if (specialDestination == SpecialType.System_MulticastDelegate || specialDestination == SpecialType.System_Delegate || IsBaseInterface(destination, this.corLibrary.GetDeclaredSpecialType(SpecialType.System_MulticastDelegate), ref useSiteInfo)) { return true; } // * From any delegate type S to a delegate type T provided S is not T and // S is a delegate convertible to T if (HasDelegateVarianceConversion(source, destination, ref useSiteInfo)) { return true; } return false; } public bool HasImplicitTypeParameterConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (HasImplicitReferenceTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } if (HasImplicitBoxingTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } if ((destination.TypeKind == TypeKind.TypeParameter) && source.DependsOn((TypeParameterSymbol)destination)) { return true; } return false; } private bool HasImplicitReferenceTypeParameterConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsValueType) { return false; // Not a reference conversion. } // The following implicit conversions exist for a given type parameter T: // // * From T to its effective base class C. // * From T to any base class of C. // * From T to any interface implemented by C (or any interface variance-compatible with such) if (HasImplicitEffectiveBaseConversion(source, destination, ref useSiteInfo)) { return true; } // * From T to any interface type I in T's effective interface set, and // from T to any base interface of I (or any interface variance-compatible with such) if (HasImplicitEffectiveInterfaceSetConversion(source, destination, ref useSiteInfo)) { return true; } // * From T to a type parameter U, provided T depends on U. if ((destination.TypeKind == TypeKind.TypeParameter) && source.DependsOn((TypeParameterSymbol)destination)) { return true; } return false; } // Spec 6.1.10: Implicit conversions involving type parameters private bool HasImplicitEffectiveBaseConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // * From T to its effective base class C. var effectiveBaseClass = source.EffectiveBaseClass(ref useSiteInfo); if (HasIdentityConversionInternal(effectiveBaseClass, destination)) { return true; } // * From T to any base class of C. if (IsBaseClass(effectiveBaseClass, destination, ref useSiteInfo)) { return true; } // * From T to any interface implemented by C (or any interface variance-compatible with such) if (HasAnyBaseInterfaceConversion(effectiveBaseClass, destination, ref useSiteInfo)) { return true; } return false; } private bool HasImplicitEffectiveInterfaceSetConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!destination.IsInterfaceType()) { return false; } // * From T to any interface type I in T's effective interface set, and // from T to any base interface of I (or any interface variance-compatible with such) foreach (var i in source.AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasInterfaceVarianceConversion(i, destination, ref useSiteInfo)) { return true; } } return false; } private bool HasAnyBaseInterfaceConversion(TypeSymbol derivedType, TypeSymbol baseType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)derivedType != null); Debug.Assert((object)baseType != null); if (!baseType.IsInterfaceType()) { return false; } var d = derivedType as NamedTypeSymbol; if ((object)d == null) { return false; } foreach (var i in d.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasInterfaceVarianceConversion(i, baseType, ref useSiteInfo)) { return true; } } return false; } //////////////////////////////////////////////////////////////////////////////// // The rules for variant interface and delegate conversions are the same: // // An interface/delegate type S is convertible to an interface/delegate type T // if and only if T is U<S1, ... Sn> and T is U<T1, ... Tn> such that for all // parameters of U: // // * if the ith parameter of U is invariant then Si is exactly equal to Ti. // * if the ith parameter of U is covariant then either Si is exactly equal // to Ti, or there is an implicit reference conversion from Si to Ti. // * if the ith parameter of U is contravariant then either Si is exactly // equal to Ti, or there is an implicit reference conversion from Ti to Si. private bool HasInterfaceVarianceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); NamedTypeSymbol s = source as NamedTypeSymbol; NamedTypeSymbol d = destination as NamedTypeSymbol; if ((object)s == null || (object)d == null) { return false; } if (!s.IsInterfaceType() || !d.IsInterfaceType()) { return false; } return HasVariantConversion(s, d, ref useSiteInfo); } private bool HasDelegateVarianceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); NamedTypeSymbol s = source as NamedTypeSymbol; NamedTypeSymbol d = destination as NamedTypeSymbol; if ((object)s == null || (object)d == null) { return false; } if (!s.IsDelegateType() || !d.IsDelegateType()) { return false; } return HasVariantConversion(s, d, ref useSiteInfo); } private bool HasVariantConversion(NamedTypeSymbol source, NamedTypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // We check for overflows in HasVariantConversion, because they are only an issue // in the presence of contravariant type parameters, which are not involved in // most conversions. // See VarianceTests for examples (e.g. TestVarianceConversionCycle, // TestVarianceConversionInfiniteExpansion). // // CONSIDER: A more rigorous solution would mimic the CLI approach, which uses // a combination of requiring finite instantiation closures (see section 9.2 of // the CLI spec) and records previous conversion steps to check for cycles. if (currentRecursionDepth >= MaximumRecursionDepth) { // NOTE: The spec doesn't really address what happens if there's an overflow // in our conversion check. It's sort of implied that the conversion "proof" // should be finite, so we'll just say that no conversion is possible. return false; } // Do a quick check up front to avoid instantiating a new Conversions object, // if possible. var quickResult = HasVariantConversionQuick(source, destination); if (quickResult.HasValue()) { return quickResult.Value(); } return this.CreateInstance(currentRecursionDepth + 1). HasVariantConversionNoCycleCheck(source, destination, ref useSiteInfo); } private ThreeState HasVariantConversionQuick(NamedTypeSymbol source, NamedTypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return ThreeState.True; } NamedTypeSymbol typeSymbol = source.OriginalDefinition; if (!TypeSymbol.Equals(typeSymbol, destination.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { return ThreeState.False; } return ThreeState.Unknown; } private bool HasVariantConversionNoCycleCheck(NamedTypeSymbol source, NamedTypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); var typeParameters = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var destinationTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); try { source.OriginalDefinition.GetAllTypeArguments(typeParameters, ref useSiteInfo); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); destination.GetAllTypeArguments(destinationTypeArguments, ref useSiteInfo); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, destination.OriginalDefinition, TypeCompareKind.AllIgnoreOptions)); Debug.Assert(typeParameters.Count == sourceTypeArguments.Count); Debug.Assert(typeParameters.Count == destinationTypeArguments.Count); for (int paramIndex = 0; paramIndex < typeParameters.Count; ++paramIndex) { var sourceTypeArgument = sourceTypeArguments[paramIndex]; var destinationTypeArgument = destinationTypeArguments[paramIndex]; // If they're identical then this one is automatically good, so skip it. if (HasIdentityConversionInternal(sourceTypeArgument.Type, destinationTypeArgument.Type) && HasTopLevelNullabilityIdentityConversion(sourceTypeArgument, destinationTypeArgument)) { continue; } TypeParameterSymbol typeParameterSymbol = (TypeParameterSymbol)typeParameters[paramIndex].Type; switch (typeParameterSymbol.Variance) { case VarianceKind.None: // System.IEquatable<T> is invariant for back compat reasons (dynamic type checks could start // to succeed where they previously failed, creating different runtime behavior), but the uses // require treatment specifically of nullability as contravariant, so we special case the // behavior here. Normally we use GetWellKnownType for these kinds of checks, but in this // case we don't want just the canonical IEquatable to be special-cased, we want all definitions // to be treated as contravariant, in case there are other definitions in metadata that were // compiled with that expectation. if (isTypeIEquatable(destination.OriginalDefinition) && TypeSymbol.Equals(destinationTypeArgument.Type, sourceTypeArgument.Type, TypeCompareKind.AllNullableIgnoreOptions) && HasAnyNullabilityImplicitConversion(destinationTypeArgument, sourceTypeArgument)) { return true; } return false; case VarianceKind.Out: if (!HasImplicitReferenceConversion(sourceTypeArgument, destinationTypeArgument, ref useSiteInfo)) { return false; } break; case VarianceKind.In: if (!HasImplicitReferenceConversion(destinationTypeArgument, sourceTypeArgument, ref useSiteInfo)) { return false; } break; default: throw ExceptionUtilities.UnexpectedValue(typeParameterSymbol.Variance); } } } finally { typeParameters.Free(); sourceTypeArguments.Free(); destinationTypeArguments.Free(); } return true; static bool isTypeIEquatable(NamedTypeSymbol type) { return type is { IsInterface: true, Name: "IEquatable", ContainingNamespace: { Name: "System", ContainingNamespace: { IsGlobalNamespace: true } }, ContainingSymbol: { Kind: SymbolKind.Namespace }, TypeParameters: { Length: 1 } }; } } // Spec 6.1.10 private bool HasImplicitBoxingTypeParameterConversion(TypeParameterSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (source.IsReferenceType) { return false; // Not a boxing conversion; both source and destination are references. } // The following implicit conversions exist for a given type parameter T: // // * From T to its effective base class C. // * From T to any base class of C. // * From T to any interface implemented by C (or any interface variance-compatible with such) if (HasImplicitEffectiveBaseConversion(source, destination, ref useSiteInfo)) { return true; } // * From T to any interface type I in T's effective interface set, and // from T to any base interface of I (or any interface variance-compatible with such) if (HasImplicitEffectiveInterfaceSetConversion(source, destination, ref useSiteInfo)) { return true; } // SPEC: From T to a type parameter U, provided T depends on U if ((destination.TypeKind == TypeKind.TypeParameter) && source.DependsOn((TypeParameterSymbol)destination)) { return true; } // SPEC: From T to a reference type I if it has an implicit conversion to a reference // SPEC: type S0 and S0 has an identity conversion to S. At run-time the conversion // SPEC: is executed the same way as the conversion to S0. // REVIEW: If T is not known to be a reference type then the only way this clause can // REVIEW: come into effect is if the target type is dynamic. Is that correct? if (destination.Kind == SymbolKind.DynamicType) { return true; } return false; } public bool HasBoxingConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // Certain type parameter conversions are classified as boxing conversions. if ((source.TypeKind == TypeKind.TypeParameter) && HasImplicitBoxingTypeParameterConversion((TypeParameterSymbol)source, destination, ref useSiteInfo)) { return true; } // The rest of the boxing conversions only operate when going from a value type to a // reference type. if (!source.IsValueType || !destination.IsReferenceType) { return false; } // A boxing conversion exists from a nullable type to a reference type if and only if a // boxing conversion exists from the underlying type. if (source.IsNullableType()) { return HasBoxingConversion(source.GetNullableUnderlyingType(), destination, ref useSiteInfo); } // A boxing conversion exists from any non-nullable value type to object and dynamic, to // System.ValueType, and to any interface type variance-compatible with one implemented // by the non-nullable value type. // Furthermore, an enum type can be converted to the type System.Enum. // We set the base class of the structs to System.ValueType, System.Enum, etc, so we can // just check here. // There are a couple of exceptions. The very special types ArgIterator, ArgumentHandle and // TypedReference are not boxable: if (source.IsRestrictedType()) { return false; } if (destination.Kind == SymbolKind.DynamicType) { return !source.IsPointerOrFunctionPointer(); } if (IsBaseClass(source, destination, ref useSiteInfo)) { return true; } if (HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo)) { return true; } return false; } internal static bool HasImplicitPointerToVoidConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: The set of implicit conversions is extended to include... // SPEC: ... from any pointer type to the type void*. return source.IsPointerOrFunctionPointer() && destination is PointerTypeSymbol { PointedAtType: { SpecialType: SpecialType.System_Void } }; } #nullable enable internal bool HasImplicitPointerConversion(TypeSymbol? source, TypeSymbol? destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!(source is FunctionPointerTypeSymbol { Signature: { } sourceSig }) || !(destination is FunctionPointerTypeSymbol { Signature: { } destinationSig })) { return false; } if (sourceSig.ParameterCount != destinationSig.ParameterCount || sourceSig.CallingConvention != destinationSig.CallingConvention) { return false; } if (sourceSig.CallingConvention == Cci.CallingConvention.Unmanaged && !sourceSig.GetCallingConventionModifiers().SetEquals(destinationSig.GetCallingConventionModifiers())) { return false; } for (int i = 0; i < sourceSig.ParameterCount; i++) { var sourceParam = sourceSig.Parameters[i]; var destinationParam = destinationSig.Parameters[i]; if (sourceParam.RefKind != destinationParam.RefKind) { return false; } if (!hasConversion(sourceParam.RefKind, destinationSig.Parameters[i].TypeWithAnnotations, sourceSig.Parameters[i].TypeWithAnnotations, ref useSiteInfo)) { return false; } } return sourceSig.RefKind == destinationSig.RefKind && hasConversion(sourceSig.RefKind, sourceSig.ReturnTypeWithAnnotations, destinationSig.ReturnTypeWithAnnotations, ref useSiteInfo); bool hasConversion(RefKind refKind, TypeWithAnnotations sourceType, TypeWithAnnotations destinationType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { switch (refKind) { case RefKind.None: return (!IncludeNullability || HasTopLevelNullabilityImplicitConversion(sourceType, destinationType)) && (HasIdentityOrImplicitReferenceConversion(sourceType.Type, destinationType.Type, ref useSiteInfo) || HasImplicitPointerToVoidConversion(sourceType.Type, destinationType.Type) || HasImplicitPointerConversion(sourceType.Type, destinationType.Type, ref useSiteInfo)); default: return (!IncludeNullability || HasTopLevelNullabilityIdentityConversion(sourceType, destinationType)) && HasIdentityConversion(sourceType.Type, destinationType.Type); } } } #nullable disable private bool HasIdentityOrReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (HasIdentityConversionInternal(source, destination)) { return true; } if (HasImplicitReferenceConversion(source, destination, ref useSiteInfo)) { return true; } if (HasExplicitReferenceConversion(source, destination, ref useSiteInfo)) { return true; } return false; } private bool HasExplicitReferenceConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: The explicit reference conversions are: // SPEC: From object and dynamic to any other reference type. if (source.SpecialType == SpecialType.System_Object) { if (destination.IsReferenceType) { return true; } } else if (source.Kind == SymbolKind.DynamicType && destination.IsReferenceType) { return true; } // SPEC: From any class-type S to any class-type T, provided S is a base class of T. if (destination.IsClassType() && IsBaseClass(destination, source, ref useSiteInfo)) { return true; } // SPEC: From any class-type S to any interface-type T, provided S is not sealed and provided S does not implement T. // ISSUE: class C : IEnumerable<Mammal> { } converting this to IEnumerable<Animal> is not an explicit conversion, // ISSUE: it is an implicit conversion. if (source.IsClassType() && destination.IsInterfaceType() && !source.IsSealed && !HasAnyBaseInterfaceConversion(source, destination, ref useSiteInfo)) { return true; } // SPEC: From any interface-type S to any class-type T, provided T is not sealed or provided T implements S. // ISSUE: What if T is sealed and implements an interface variance-convertible to S? // ISSUE: eg, sealed class C : IEnum<Mammal> { ... } you should be able to cast an IEnum<Animal> to C. if (source.IsInterfaceType() && destination.IsClassType() && (!destination.IsSealed || HasAnyBaseInterfaceConversion(destination, source, ref useSiteInfo))) { return true; } // SPEC: From any interface-type S to any interface-type T, provided S is not derived from T. // ISSUE: This does not rule out identity conversions, which ought not to be classified as // ISSUE: explicit reference conversions. // ISSUE: IEnumerable<Mammal> and IEnumerable<Animal> do not derive from each other but this is // ISSUE: not an explicit reference conversion, this is an implicit reference conversion. if (source.IsInterfaceType() && destination.IsInterfaceType() && !HasImplicitConversionToInterface(source, destination, ref useSiteInfo)) { return true; } // SPEC: UNDONE: From a reference type to a reference type T if it has an explicit reference conversion to a reference type T0 and T0 has an identity conversion T. // SPEC: UNDONE: From a reference type to an interface or delegate type T if it has an explicit reference conversion to an interface or delegate type T0 and either T0 is variance-convertible to T or T is variance-convertible to T0 (§13.1.3.2). if (HasExplicitArrayConversion(source, destination, ref useSiteInfo)) { return true; } if (HasExplicitDelegateConversion(source, destination, ref useSiteInfo)) { return true; } if (HasExplicitReferenceTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } return false; } // Spec 6.2.7 Explicit conversions involving type parameters private bool HasExplicitReferenceTypeParameterConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); TypeParameterSymbol s = source as TypeParameterSymbol; TypeParameterSymbol t = destination as TypeParameterSymbol; // SPEC: The following explicit conversions exist for a given type parameter T: // SPEC: If T is known to be a reference type, the conversions are all classified as explicit reference conversions. // SPEC: If T is not known to be a reference type, the conversions are classified as unboxing conversions. // SPEC: From the effective base class C of T to T and from any base class of C to T. if ((object)t != null && t.IsReferenceType) { for (var type = t.EffectiveBaseClass(ref useSiteInfo); (object)type != null; type = type.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(type, source)) { return true; } } } // SPEC: From any interface type to T. if ((object)t != null && source.IsInterfaceType() && t.IsReferenceType) { return true; } // SPEC: From T to any interface-type I provided there is not already an implicit conversion from T to I. if ((object)s != null && s.IsReferenceType && destination.IsInterfaceType() && !HasImplicitReferenceTypeParameterConversion(s, destination, ref useSiteInfo)) { return true; } // SPEC: From a type parameter U to T, provided T depends on U (§10.1.5) if ((object)s != null && (object)t != null && t.IsReferenceType && t.DependsOn(s)) { return true; } return false; } // Spec 6.2.7 Explicit conversions involving type parameters private bool HasUnboxingTypeParameterConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); TypeParameterSymbol s = source as TypeParameterSymbol; TypeParameterSymbol t = destination as TypeParameterSymbol; // SPEC: The following explicit conversions exist for a given type parameter T: // SPEC: If T is known to be a reference type, the conversions are all classified as explicit reference conversions. // SPEC: If T is not known to be a reference type, the conversions are classified as unboxing conversions. // SPEC: From the effective base class C of T to T and from any base class of C to T. if ((object)t != null && !t.IsReferenceType) { for (var type = t.EffectiveBaseClass(ref useSiteInfo); (object)type != null; type = type.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (TypeSymbol.Equals(type, source, TypeCompareKind.ConsiderEverything2)) { return true; } } } // SPEC: From any interface type to T. if (source.IsInterfaceType() && (object)t != null && !t.IsReferenceType) { return true; } // SPEC: From T to any interface-type I provided there is not already an implicit conversion from T to I. if ((object)s != null && !s.IsReferenceType && destination.IsInterfaceType() && !HasImplicitReferenceTypeParameterConversion(s, destination, ref useSiteInfo)) { return true; } // SPEC: From a type parameter U to T, provided T depends on U (§10.1.5) if ((object)s != null && (object)t != null && !t.IsReferenceType && t.DependsOn(s)) { return true; } return false; } private bool HasExplicitDelegateConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); // SPEC: From System.Delegate and the interfaces it implements to any delegate-type. // We also support System.MulticastDelegate in the implementation, in spite of it not being mentioned in the spec. if (destination.IsDelegateType()) { if (source.SpecialType == SpecialType.System_Delegate || source.SpecialType == SpecialType.System_MulticastDelegate) { return true; } if (HasImplicitConversionToInterface(this.corLibrary.GetDeclaredSpecialType(SpecialType.System_Delegate), source, ref useSiteInfo)) { return true; } } // SPEC: From D<S1...Sn> to a D<T1...Tn> where D<X1...Xn> is a generic delegate type, D<S1...Sn> is not compatible with or identical to D<T1...Tn>, // SPEC: and for each type parameter Xi of D the following holds: // SPEC: If Xi is invariant, then Si is identical to Ti. // SPEC: If Xi is covariant, then there is an implicit or explicit identity or reference conversion from Si to Ti. // SPECL If Xi is contravariant, then Si and Ti are either identical or both reference types. if (!source.IsDelegateType() || !destination.IsDelegateType()) { return false; } if (!TypeSymbol.Equals(source.OriginalDefinition, destination.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { return false; } var sourceType = (NamedTypeSymbol)source; var destinationType = (NamedTypeSymbol)destination; var original = sourceType.OriginalDefinition; if (HasIdentityConversionInternal(source, destination)) { return false; } if (HasDelegateVarianceConversion(source, destination, ref useSiteInfo)) { return false; } var sourceTypeArguments = sourceType.TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteInfo); var destinationTypeArguments = destinationType.TypeArgumentsWithDefinitionUseSiteDiagnostics(ref useSiteInfo); for (int i = 0; i < sourceTypeArguments.Length; ++i) { var sourceArg = sourceTypeArguments[i].Type; var destinationArg = destinationTypeArguments[i].Type; switch (original.TypeParameters[i].Variance) { case VarianceKind.None: if (!HasIdentityConversionInternal(sourceArg, destinationArg)) { return false; } break; case VarianceKind.Out: if (!HasIdentityOrReferenceConversion(sourceArg, destinationArg, ref useSiteInfo)) { return false; } break; case VarianceKind.In: bool hasIdentityConversion = HasIdentityConversionInternal(sourceArg, destinationArg); bool bothAreReferenceTypes = sourceArg.IsReferenceType && destinationArg.IsReferenceType; if (!(hasIdentityConversion || bothAreReferenceTypes)) { return false; } break; } } return true; } private bool HasExplicitArrayConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); var sourceArray = source as ArrayTypeSymbol; var destinationArray = destination as ArrayTypeSymbol; // SPEC: From an array-type S with an element type SE to an array-type T with an element type TE, provided all of the following are true: // SPEC: S and T differ only in element type. (In other words, S and T have the same number of dimensions.) // SPEC: Both SE and TE are reference-types. // SPEC: An explicit reference conversion exists from SE to TE. if ((object)sourceArray != null && (object)destinationArray != null) { // HasExplicitReferenceConversion checks that SE and TE are reference types so // there's no need for that check here. Moreover, it's not as simple as checking // IsReferenceType, at least not in the case of type parameters, since SE will be // considered a reference type implicitly in the case of "where TE : class, SE" even // though SE.IsReferenceType may be false. Again, HasExplicitReferenceConversion // already handles these cases. return sourceArray.HasSameShapeAs(destinationArray) && HasExplicitReferenceConversion(sourceArray.ElementType, destinationArray.ElementType, ref useSiteInfo); } // SPEC: From System.Array and the interfaces it implements to any array-type. if ((object)destinationArray != null) { if (source.SpecialType == SpecialType.System_Array) { return true; } foreach (var iface in this.corLibrary.GetDeclaredSpecialType(SpecialType.System_Array).AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)) { if (HasIdentityConversionInternal(iface, source)) { return true; } } } // SPEC: From a single-dimensional array type S[] to System.Collections.Generic.IList<T> and its base interfaces // SPEC: provided that there is an explicit reference conversion from S to T. // The framework now also allows arrays to be converted to IReadOnlyList<T> and IReadOnlyCollection<T>; we // honor that as well. if ((object)sourceArray != null && sourceArray.IsSZArray && destination.IsPossibleArrayGenericInterface()) { if (HasExplicitReferenceConversion(sourceArray.ElementType, ((NamedTypeSymbol)destination).TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo).Type, ref useSiteInfo)) { return true; } } // SPEC: From System.Collections.Generic.IList<S> and its base interfaces to a single-dimensional array type T[], // provided that there is an explicit identity or reference conversion from S to T. // Similarly, we honor IReadOnlyList<S> and IReadOnlyCollection<S> in the same way. if ((object)destinationArray != null && destinationArray.IsSZArray) { var specialDefinition = ((TypeSymbol)source.OriginalDefinition).SpecialType; if (specialDefinition == SpecialType.System_Collections_Generic_IList_T || specialDefinition == SpecialType.System_Collections_Generic_ICollection_T || specialDefinition == SpecialType.System_Collections_Generic_IEnumerable_T || specialDefinition == SpecialType.System_Collections_Generic_IReadOnlyList_T || specialDefinition == SpecialType.System_Collections_Generic_IReadOnlyCollection_T) { var sourceElement = ((NamedTypeSymbol)source).TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo).Type; var destinationElement = destinationArray.ElementType; if (HasIdentityConversionInternal(sourceElement, destinationElement)) { return true; } if (HasImplicitReferenceConversion(sourceElement, destinationElement, ref useSiteInfo)) { return true; } if (HasExplicitReferenceConversion(sourceElement, destinationElement, ref useSiteInfo)) { return true; } } } return false; } private bool HasUnboxingConversion(TypeSymbol source, TypeSymbol destination, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (destination.IsPointerOrFunctionPointer()) { return false; } // Ref-like types cannot be boxed or unboxed if (destination.IsRestrictedType()) { return false; } // SPEC: An unboxing conversion permits a reference type to be explicitly converted to a value-type. // SPEC: An unboxing conversion exists from the types object and System.ValueType to any non-nullable-value-type, var specialTypeSource = source.SpecialType; if (specialTypeSource == SpecialType.System_Object || specialTypeSource == SpecialType.System_ValueType) { if (destination.IsValueType && !destination.IsNullableType()) { return true; } } // SPEC: and from any interface-type to any non-nullable-value-type that implements the interface-type. if (source.IsInterfaceType() && destination.IsValueType && !destination.IsNullableType() && HasBoxingConversion(destination, source, ref useSiteInfo)) { return true; } // SPEC: Furthermore type System.Enum can be unboxed to any enum-type. if (source.SpecialType == SpecialType.System_Enum && destination.IsEnumType()) { return true; } // SPEC: An unboxing conversion exists from a reference type to a nullable-type if an unboxing // SPEC: conversion exists from the reference type to the underlying non-nullable-value-type // SPEC: of the nullable-type. if (source.IsReferenceType && destination.IsNullableType() && HasUnboxingConversion(source, destination.GetNullableUnderlyingType(), ref useSiteInfo)) { return true; } // SPEC: UNDONE A value type S has an unboxing conversion from an interface type I if it has an unboxing // SPEC: UNDONE conversion from an interface type I0 and I0 has an identity conversion to I. // SPEC: UNDONE A value type S has an unboxing conversion from an interface type I if it has an unboxing conversion // SPEC: UNDONE from an interface or delegate type I0 and either I0 is variance-convertible to I or I is variance-convertible to I0. if (HasUnboxingTypeParameterConversion(source, destination, ref useSiteInfo)) { return true; } return false; } private static bool HasPointerToPointerConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); return source.IsPointerOrFunctionPointer() && destination.IsPointerOrFunctionPointer(); } private static bool HasPointerToIntegerConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!source.IsPointerOrFunctionPointer()) { return false; } // SPEC OMISSION: // // The spec should state that any pointer type is convertible to // sbyte, byte, ... etc, or any corresponding nullable type. return IsIntegerTypeSupportingPointerConversions(destination.StrippedType()); } private static bool HasIntegerToPointerConversion(TypeSymbol source, TypeSymbol destination) { Debug.Assert((object)source != null); Debug.Assert((object)destination != null); if (!destination.IsPointerOrFunctionPointer()) { return false; } // Note that void* is convertible to int?, but int? is not convertible to void*. return IsIntegerTypeSupportingPointerConversions(source); } private static bool IsIntegerTypeSupportingPointerConversions(TypeSymbol type) { switch (type.SpecialType) { case SpecialType.System_SByte: case SpecialType.System_Byte: case SpecialType.System_Int16: case SpecialType.System_UInt16: case SpecialType.System_Int32: case SpecialType.System_UInt32: case SpecialType.System_Int64: case SpecialType.System_UInt64: return true; case SpecialType.System_IntPtr: case SpecialType.System_UIntPtr: return type.IsNativeIntegerType; } return false; } } }
1
dotnet/roslyn
55,125
Don't use DefaultInterpolatedStringHandler in expression trees
Introduces a binder flag to track whether we are currently in an expression tree or not. Fixes https://github.com/dotnet/roslyn/issues/55114.
333fred
2021-07-26T22:08:39Z
2021-07-27T19:33:24Z
5840335153dcca42570a853cdacd06d660fe9596
cfc12ce93ce377c4b9581ccf88403e6740d63977
Don't use DefaultInterpolatedStringHandler in expression trees. Introduces a binder flag to track whether we are currently in an expression tree or not. Fixes https://github.com/dotnet/roslyn/issues/55114.
./src/Compilers/CSharp/Portable/BoundTree/UnboundLambda.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal interface IBoundLambdaOrFunction { MethodSymbol Symbol { get; } SyntaxNode Syntax { get; } BoundBlock? Body { get; } bool WasCompilerGenerated { get; } } internal sealed partial class BoundLocalFunctionStatement : IBoundLambdaOrFunction { MethodSymbol IBoundLambdaOrFunction.Symbol { get { return Symbol; } } SyntaxNode IBoundLambdaOrFunction.Syntax { get { return Syntax; } } BoundBlock? IBoundLambdaOrFunction.Body { get => this.Body; } } internal readonly struct InferredLambdaReturnType { internal readonly int NumExpressions; internal readonly bool IsExplicitType; internal readonly bool HadExpressionlessReturn; internal readonly RefKind RefKind; internal readonly TypeWithAnnotations TypeWithAnnotations; internal readonly ImmutableArray<DiagnosticInfo> UseSiteDiagnostics; internal readonly ImmutableArray<AssemblySymbol> Dependencies; internal InferredLambdaReturnType( int numExpressions, bool isExplicitType, bool hadExpressionlessReturn, RefKind refKind, TypeWithAnnotations typeWithAnnotations, ImmutableArray<DiagnosticInfo> useSiteDiagnostics, ImmutableArray<AssemblySymbol> dependencies) { NumExpressions = numExpressions; IsExplicitType = isExplicitType; HadExpressionlessReturn = hadExpressionlessReturn; RefKind = refKind; TypeWithAnnotations = typeWithAnnotations; UseSiteDiagnostics = useSiteDiagnostics; Dependencies = dependencies; } } internal sealed partial class BoundLambda : IBoundLambdaOrFunction { public MessageID MessageID { get { return Syntax.Kind() == SyntaxKind.AnonymousMethodExpression ? MessageID.IDS_AnonMethod : MessageID.IDS_Lambda; } } internal InferredLambdaReturnType InferredReturnType { get; } MethodSymbol IBoundLambdaOrFunction.Symbol { get { return Symbol; } } SyntaxNode IBoundLambdaOrFunction.Syntax { get { return Syntax; } } public BoundLambda(SyntaxNode syntax, UnboundLambda unboundLambda, BoundBlock body, ImmutableBindingDiagnostic<AssemblySymbol> diagnostics, Binder binder, TypeSymbol? delegateType, InferredLambdaReturnType inferredReturnType) : this(syntax, unboundLambda.WithNoCache(), (LambdaSymbol)binder.ContainingMemberOrLambda!, body, diagnostics, binder, delegateType) { InferredReturnType = inferredReturnType; Debug.Assert( syntax.IsAnonymousFunction() || // lambda expressions syntax is ExpressionSyntax && LambdaUtilities.IsLambdaBody(syntax, allowReducedLambdas: true) || // query lambdas LambdaUtilities.IsQueryPairLambda(syntax) // "pair" lambdas in queries ); } public TypeWithAnnotations GetInferredReturnType(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // Nullability (and conversions) are ignored. return GetInferredReturnType(conversions: null, nullableState: null, ref useSiteInfo); } /// <summary> /// Infer return type. If `nullableState` is non-null, nullability is also inferred and `NullableWalker.Analyze` /// uses that state to set the inferred nullability of variables in the enclosing scope. `conversions` is /// only needed when nullability is inferred. /// </summary> public TypeWithAnnotations GetInferredReturnType(ConversionsBase? conversions, NullableWalker.VariableState? nullableState, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!InferredReturnType.UseSiteDiagnostics.IsEmpty) { useSiteInfo.AddDiagnostics(InferredReturnType.UseSiteDiagnostics); } if (!InferredReturnType.Dependencies.IsEmpty) { useSiteInfo.AddDependencies(InferredReturnType.Dependencies); } if (nullableState == null || InferredReturnType.IsExplicitType) { return InferredReturnType.TypeWithAnnotations; } else { Debug.Assert(!UnboundLambda.HasExplicitReturnType(out _, out _)); Debug.Assert(conversions != null); // Diagnostics from NullableWalker.Analyze can be dropped here since Analyze // will be called again from NullableWalker.ApplyConversion when the // BoundLambda is converted to an anonymous function. // https://github.com/dotnet/roslyn/issues/31752: Can we avoid generating extra // diagnostics? And is this exponential when there are nested lambdas? var returnTypes = ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>.GetInstance(); var diagnostics = DiagnosticBag.GetInstance(); var delegateType = Type.GetDelegateType(); var compilation = Binder.Compilation; NullableWalker.Analyze(compilation, lambda: this, (Conversions)conversions, diagnostics, delegateInvokeMethodOpt: delegateType?.DelegateInvokeMethod, initialState: nullableState, returnTypes); diagnostics.Free(); var inferredReturnType = InferReturnType(returnTypes, node: this, Binder, delegateType, Symbol.IsAsync, conversions); returnTypes.Free(); return inferredReturnType.TypeWithAnnotations; } } internal LambdaSymbol CreateLambdaSymbol(NamedTypeSymbol delegateType, Symbol containingSymbol) => UnboundLambda.Data.CreateLambdaSymbol(delegateType, containingSymbol); internal LambdaSymbol CreateLambdaSymbol( Symbol containingSymbol, TypeWithAnnotations returnType, ImmutableArray<TypeWithAnnotations> parameterTypes, ImmutableArray<RefKind> parameterRefKinds, RefKind refKind) => UnboundLambda.Data.CreateLambdaSymbol( containingSymbol, returnType, parameterTypes, parameterRefKinds.IsDefault ? Enumerable.Repeat(RefKind.None, parameterTypes.Length).ToImmutableArray() : parameterRefKinds, refKind); /// <summary> /// Indicates the type of return statement with no expression. Used in InferReturnType. /// </summary> internal static readonly TypeSymbol NoReturnExpression = new UnsupportedMetadataTypeSymbol(); internal static InferredLambdaReturnType InferReturnType(ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)> returnTypes, BoundLambda node, Binder binder, TypeSymbol? delegateType, bool isAsync, ConversionsBase conversions) { Debug.Assert(!node.UnboundLambda.HasExplicitReturnType(out _, out _)); return InferReturnTypeImpl(returnTypes, node, binder, delegateType, isAsync, conversions, node.UnboundLambda.WithDependencies); } internal static InferredLambdaReturnType InferReturnType(ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)> returnTypes, UnboundLambda node, Binder binder, TypeSymbol? delegateType, bool isAsync, ConversionsBase conversions) { Debug.Assert(!node.HasExplicitReturnType(out _, out _)); return InferReturnTypeImpl(returnTypes, node, binder, delegateType, isAsync, conversions, node.WithDependencies); } /// <summary> /// Behavior of this function should be kept aligned with <see cref="UnboundLambdaState.ReturnInferenceCacheKey"/>. /// </summary> private static InferredLambdaReturnType InferReturnTypeImpl(ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)> returnTypes, BoundNode node, Binder binder, TypeSymbol? delegateType, bool isAsync, ConversionsBase conversions, bool withDependencies) { var types = ArrayBuilder<(BoundExpression, TypeWithAnnotations)>.GetInstance(); bool hasReturnWithoutArgument = false; RefKind refKind = RefKind.None; foreach (var (returnStatement, type) in returnTypes) { RefKind rk = returnStatement.RefKind; if (rk != RefKind.None) { refKind = rk; } if ((object)type.Type == NoReturnExpression) { hasReturnWithoutArgument = true; } else { types.Add((returnStatement.ExpressionOpt!, type)); } } var useSiteInfo = withDependencies ? new CompoundUseSiteInfo<AssemblySymbol>(binder.Compilation.Assembly) : CompoundUseSiteInfo<AssemblySymbol>.DiscardedDependencies; var bestType = CalculateReturnType(binder, conversions, delegateType, types, isAsync, node, ref useSiteInfo); int numExpressions = types.Count; types.Free(); return new InferredLambdaReturnType( numExpressions, isExplicitType: false, hasReturnWithoutArgument, refKind, bestType, useSiteInfo.Diagnostics.AsImmutableOrEmpty(), useSiteInfo.AccumulatesDependencies ? useSiteInfo.Dependencies.AsImmutableOrEmpty() : ImmutableArray<AssemblySymbol>.Empty); } private static TypeWithAnnotations CalculateReturnType( Binder binder, ConversionsBase conversions, TypeSymbol? delegateType, ArrayBuilder<(BoundExpression, TypeWithAnnotations resultType)> returns, bool isAsync, BoundNode node, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { TypeWithAnnotations bestResultType; int n = returns.Count; switch (n) { case 0: bestResultType = default; break; case 1: bestResultType = returns[0].resultType; break; default: // Need to handle ref returns. See https://github.com/dotnet/roslyn/issues/30432 if (conversions.IncludeNullability) { bestResultType = NullableWalker.BestTypeForLambdaReturns(returns, binder, node, (Conversions)conversions); } else { var typesOnly = ArrayBuilder<TypeSymbol>.GetInstance(n); foreach (var (_, resultType) in returns) { typesOnly.Add(resultType.Type); } var bestType = BestTypeInferrer.GetBestType(typesOnly, conversions, ref useSiteInfo); bestResultType = bestType is null ? default : TypeWithAnnotations.Create(bestType); typesOnly.Free(); } break; } if (!isAsync) { return bestResultType; } // For async lambdas, the return type is the return type of the // delegate Invoke method if Invoke has a Task-like return type. // Otherwise the return type is Task or Task<T>. NamedTypeSymbol? taskType = null; var delegateReturnType = delegateType?.GetDelegateType()?.DelegateInvokeMethod?.ReturnType as NamedTypeSymbol; if (delegateReturnType?.IsVoidType() == false) { if (delegateReturnType.IsCustomTaskType(builderArgument: out _)) { taskType = delegateReturnType.ConstructedFrom; } } if (n == 0) { // No return statements have expressions; use delegate InvokeMethod // or infer type Task if delegate type not available. var resultType = taskType?.Arity == 0 ? taskType : binder.Compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task); return TypeWithAnnotations.Create(resultType); } if (!bestResultType.HasType || bestResultType.IsVoidType()) { // If the best type was 'void', ERR_CantReturnVoid is reported while binding the "return void" // statement(s). return default; } // Some non-void best type T was found; use delegate InvokeMethod // or infer type Task<T> if delegate type not available. var taskTypeT = taskType?.Arity == 1 ? taskType : binder.Compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T); return TypeWithAnnotations.Create(taskTypeT.Construct(ImmutableArray.Create(bestResultType))); } internal sealed class BlockReturns : BoundTreeWalker { private readonly ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)> _builder; private BlockReturns(ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)> builder) { _builder = builder; } public static void GetReturnTypes(ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)> builder, BoundBlock block) { var visitor = new BlockReturns(builder); visitor.Visit(block); } public override BoundNode? Visit(BoundNode node) { if (!(node is BoundExpression)) { return base.Visit(node); } return null; } protected override BoundExpression VisitExpressionWithoutStackGuard(BoundExpression node) { throw ExceptionUtilities.Unreachable; } public override BoundNode? VisitLocalFunctionStatement(BoundLocalFunctionStatement node) { // Do not recurse into local functions; we don't want their returns. return null; } public override BoundNode? VisitReturnStatement(BoundReturnStatement node) { var expression = node.ExpressionOpt; var type = (expression is null) ? NoReturnExpression : expression.Type?.SetUnknownNullabilityForReferenceTypes(); _builder.Add((node, TypeWithAnnotations.Create(type))); return null; } } } internal partial class UnboundLambda { private readonly NullableWalker.VariableState? _nullableState; public UnboundLambda( CSharpSyntaxNode syntax, Binder binder, bool withDependencies, RefKind returnRefKind, TypeWithAnnotations returnType, ImmutableArray<SyntaxList<AttributeListSyntax>> parameterAttributes, ImmutableArray<RefKind> refKinds, ImmutableArray<TypeWithAnnotations> types, ImmutableArray<string> names, ImmutableArray<bool> discardsOpt, bool isAsync, bool isStatic) : this(syntax, new PlainUnboundLambdaState(binder, returnRefKind, returnType, parameterAttributes, names, discardsOpt, types, refKinds, isAsync, isStatic, includeCache: true), withDependencies, !types.IsDefault && types.Any(t => t.Type?.Kind == SymbolKind.ErrorType)) { Debug.Assert(binder != null); Debug.Assert(syntax.IsAnonymousFunction()); this.Data.SetUnboundLambda(this); } private UnboundLambda(SyntaxNode syntax, UnboundLambdaState state, bool withDependencies, NullableWalker.VariableState? nullableState, bool hasErrors) : this(syntax, state, withDependencies, hasErrors) { this._nullableState = nullableState; } internal UnboundLambda WithNullableState(NullableWalker.VariableState nullableState) { var data = Data.WithCaching(true); var lambda = new UnboundLambda(Syntax, data, WithDependencies, nullableState, HasErrors); data.SetUnboundLambda(lambda); return lambda; } internal UnboundLambda WithNoCache() { var data = Data.WithCaching(false); if ((object)data == Data) { return this; } var lambda = new UnboundLambda(Syntax, data, WithDependencies, _nullableState, HasErrors); data.SetUnboundLambda(lambda); return lambda; } public MessageID MessageID { get { return Data.MessageID; } } public NamedTypeSymbol? InferDelegateType(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) => Data.InferDelegateType(ref useSiteInfo); public BoundLambda Bind(NamedTypeSymbol delegateType) => SuppressIfNeeded(Data.Bind(delegateType)); public BoundLambda BindForErrorRecovery() => SuppressIfNeeded(Data.BindForErrorRecovery()); public BoundLambda BindForReturnTypeInference(NamedTypeSymbol delegateType) => SuppressIfNeeded(Data.BindForReturnTypeInference(delegateType)); private BoundLambda SuppressIfNeeded(BoundLambda lambda) => this.IsSuppressed ? (BoundLambda)lambda.WithSuppression() : lambda; public bool HasSignature { get { return Data.HasSignature; } } public bool HasExplicitReturnType(out RefKind refKind, out TypeWithAnnotations returnType) => Data.HasExplicitReturnType(out refKind, out returnType); public bool HasExplicitlyTypedParameterList { get { return Data.HasExplicitlyTypedParameterList; } } public int ParameterCount { get { return Data.ParameterCount; } } public TypeWithAnnotations InferReturnType(ConversionsBase conversions, NamedTypeSymbol delegateType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) => BindForReturnTypeInference(delegateType).GetInferredReturnType(conversions, _nullableState, ref useSiteInfo); public RefKind RefKind(int index) { return Data.RefKind(index); } public void GenerateAnonymousFunctionConversionError(BindingDiagnosticBag diagnostics, TypeSymbol targetType) { Data.GenerateAnonymousFunctionConversionError(diagnostics, targetType); } public bool GenerateSummaryErrors(BindingDiagnosticBag diagnostics) { return Data.GenerateSummaryErrors(diagnostics); } public bool IsAsync { get { return Data.IsAsync; } } public bool IsStatic => Data.IsStatic; public SyntaxList<AttributeListSyntax> ParameterAttributes(int index) { return Data.ParameterAttributes(index); } public TypeWithAnnotations ParameterTypeWithAnnotations(int index) { return Data.ParameterTypeWithAnnotations(index); } public TypeSymbol ParameterType(int index) { return ParameterTypeWithAnnotations(index).Type; } public Location ParameterLocation(int index) { return Data.ParameterLocation(index); } public string ParameterName(int index) { return Data.ParameterName(index); } public bool ParameterIsDiscard(int index) { return Data.ParameterIsDiscard(index); } } internal abstract class UnboundLambdaState { private UnboundLambda _unboundLambda = null!; // we would prefer this readonly, but we have an initialization cycle. internal readonly Binder Binder; [PerformanceSensitive( "https://github.com/dotnet/roslyn/issues/23582", Constraint = "Avoid " + nameof(ConcurrentDictionary<NamedTypeSymbol, BoundLambda>) + " which has a large default size, but this cache is normally small.")] private ImmutableDictionary<NamedTypeSymbol, BoundLambda>? _bindingCache; [PerformanceSensitive( "https://github.com/dotnet/roslyn/issues/23582", Constraint = "Avoid " + nameof(ConcurrentDictionary<ReturnInferenceCacheKey, BoundLambda>) + " which has a large default size, but this cache is normally small.")] private ImmutableDictionary<ReturnInferenceCacheKey, BoundLambda>? _returnInferenceCache; private BoundLambda? _errorBinding; public UnboundLambdaState(Binder binder, bool includeCache) { Debug.Assert(binder != null); Debug.Assert(binder.ContainingMemberOrLambda != null); if (includeCache) { _bindingCache = ImmutableDictionary<NamedTypeSymbol, BoundLambda>.Empty.WithComparers(Symbols.SymbolEqualityComparer.ConsiderEverything); _returnInferenceCache = ImmutableDictionary<ReturnInferenceCacheKey, BoundLambda>.Empty; } this.Binder = binder; } public void SetUnboundLambda(UnboundLambda unbound) { Debug.Assert(unbound != null); Debug.Assert(_unboundLambda == null || (object)_unboundLambda == unbound); _unboundLambda = unbound; } protected abstract UnboundLambdaState WithCachingCore(bool includeCache); internal UnboundLambdaState WithCaching(bool includeCache) { if ((_bindingCache == null) != includeCache) { return this; } var state = WithCachingCore(includeCache); Debug.Assert((state._bindingCache == null) != includeCache); return state; } public UnboundLambda UnboundLambda => _unboundLambda; public abstract MessageID MessageID { get; } public abstract string ParameterName(int index); public abstract bool ParameterIsDiscard(int index); public abstract SyntaxList<AttributeListSyntax> ParameterAttributes(int index); public abstract bool HasSignature { get; } public abstract bool HasExplicitReturnType(out RefKind refKind, out TypeWithAnnotations returnType); public abstract bool HasExplicitlyTypedParameterList { get; } public abstract int ParameterCount { get; } public abstract bool IsAsync { get; } public abstract bool HasNames { get; } public abstract bool IsStatic { get; } public abstract Location ParameterLocation(int index); public abstract TypeWithAnnotations ParameterTypeWithAnnotations(int index); public abstract RefKind RefKind(int index); protected abstract BoundBlock BindLambdaBody(LambdaSymbol lambdaSymbol, Binder lambdaBodyBinder, BindingDiagnosticBag diagnostics); /// <summary> /// Return the bound expression if the lambda has an expression body and can be reused easily. /// This is an optimization only. Implementations can return null to skip reuse. /// </summary> protected abstract BoundExpression? GetLambdaExpressionBody(BoundBlock body); /// <summary> /// Produce a bound block for the expression returned from GetLambdaExpressionBody. /// </summary> protected abstract BoundBlock CreateBlockFromLambdaExpressionBody(Binder lambdaBodyBinder, BoundExpression expression, BindingDiagnosticBag diagnostics); public virtual void GenerateAnonymousFunctionConversionError(BindingDiagnosticBag diagnostics, TypeSymbol targetType) { this.Binder.GenerateAnonymousFunctionConversionError(diagnostics, _unboundLambda.Syntax, _unboundLambda, targetType); } // Returns the inferred return type, or null if none can be inferred. public BoundLambda Bind(NamedTypeSymbol delegateType) { BoundLambda? result; if (!_bindingCache!.TryGetValue(delegateType, out result)) { result = ReallyBind(delegateType); result = ImmutableInterlocked.GetOrAdd(ref _bindingCache, delegateType, result); } return result; } internal IEnumerable<TypeSymbol> InferredReturnTypes() { bool any = false; foreach (var lambda in _returnInferenceCache!.Values) { var type = lambda.InferredReturnType.TypeWithAnnotations; if (type.HasType) { any = true; yield return type.Type; } } if (!any) { var type = BindForErrorRecovery().InferredReturnType.TypeWithAnnotations; if (type.HasType) { yield return type.Type; } } } private static MethodSymbol? DelegateInvokeMethod(NamedTypeSymbol? delegateType) { return delegateType.GetDelegateType()?.DelegateInvokeMethod; } private static TypeWithAnnotations DelegateReturnTypeWithAnnotations(MethodSymbol? invokeMethod, out RefKind refKind) { if (invokeMethod is null) { refKind = CodeAnalysis.RefKind.None; return default; } refKind = invokeMethod.RefKind; return invokeMethod.ReturnTypeWithAnnotations; } internal NamedTypeSymbol? InferDelegateType(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(Binder.ContainingMemberOrLambda is { }); if (!HasExplicitlyTypedParameterList) { return null; } var parameterRefKindsBuilder = ArrayBuilder<RefKind>.GetInstance(ParameterCount); var parameterTypesBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(ParameterCount); for (int i = 0; i < ParameterCount; i++) { parameterRefKindsBuilder.Add(RefKind(i)); parameterTypesBuilder.Add(ParameterTypeWithAnnotations(i)); } var parameterRefKinds = parameterRefKindsBuilder.ToImmutableAndFree(); var parameterTypes = parameterTypesBuilder.ToImmutableAndFree(); if (!HasExplicitReturnType(out var returnRefKind, out var returnType)) { var lambdaSymbol = new LambdaSymbol( Binder, Binder.Compilation, Binder.ContainingMemberOrLambda, _unboundLambda, parameterTypes, parameterRefKinds, refKind: default, returnType: default); var lambdaBodyBinder = new ExecutableCodeBinder(_unboundLambda.Syntax, lambdaSymbol, ParameterBinder(lambdaSymbol, Binder)); var block = BindLambdaBody(lambdaSymbol, lambdaBodyBinder, BindingDiagnosticBag.Discarded); var returnTypes = ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>.GetInstance(); BoundLambda.BlockReturns.GetReturnTypes(returnTypes, block); var inferredReturnType = BoundLambda.InferReturnType( returnTypes, _unboundLambda, lambdaBodyBinder, delegateType: null, isAsync: IsAsync, Binder.Conversions); returnType = inferredReturnType.TypeWithAnnotations; returnRefKind = inferredReturnType.RefKind; if (!returnType.HasType && returnTypes.Count > 0) { return null; } } return Binder.GetMethodGroupOrLambdaDelegateType( returnRefKind, returnType.Type?.IsVoidType() == true ? default : returnType, parameterRefKinds, parameterTypes, ref useSiteInfo); } private BoundLambda ReallyBind(NamedTypeSymbol delegateType) { Debug.Assert(Binder.ContainingMemberOrLambda is { }); var invokeMethod = DelegateInvokeMethod(delegateType); var returnType = DelegateReturnTypeWithAnnotations(invokeMethod, out RefKind refKind); LambdaSymbol lambdaSymbol; Binder lambdaBodyBinder; BoundBlock block; var diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, _unboundLambda.WithDependencies); var compilation = Binder.Compilation; var cacheKey = ReturnInferenceCacheKey.Create(delegateType, IsAsync); // When binding for real (not for return inference), there is still a good chance // we could reuse a body of a lambda previous bound for return type inference. // For simplicity, reuse is limited to expression-bodied lambdas. In those cases, // we reuse the bound expression and apply any conversion to the return value // since the inferred return type was not used when binding for return inference. if (refKind == CodeAnalysis.RefKind.None && _returnInferenceCache!.TryGetValue(cacheKey, out BoundLambda? returnInferenceLambda) && GetLambdaExpressionBody(returnInferenceLambda.Body) is BoundExpression expression && (lambdaSymbol = returnInferenceLambda.Symbol).RefKind == refKind && (object)LambdaSymbol.InferenceFailureReturnType != lambdaSymbol.ReturnType && lambdaSymbol.ReturnTypeWithAnnotations.Equals(returnType, TypeCompareKind.ConsiderEverything)) { lambdaBodyBinder = returnInferenceLambda.Binder; block = CreateBlockFromLambdaExpressionBody(lambdaBodyBinder, expression, diagnostics); diagnostics.AddRange(returnInferenceLambda.Diagnostics); } else { lambdaSymbol = CreateLambdaSymbol(Binder.ContainingMemberOrLambda, returnType, cacheKey.ParameterTypes, cacheKey.ParameterRefKinds, refKind); lambdaBodyBinder = new ExecutableCodeBinder(_unboundLambda.Syntax, lambdaSymbol, ParameterBinder(lambdaSymbol, Binder)); block = BindLambdaBody(lambdaSymbol, lambdaBodyBinder, diagnostics); } lambdaSymbol.GetDeclarationDiagnostics(diagnostics); if (lambdaSymbol.RefKind == CodeAnalysis.RefKind.RefReadOnly) { compilation.EnsureIsReadOnlyAttributeExists(diagnostics, lambdaSymbol.DiagnosticLocation, modifyCompilation: false); } var lambdaParameters = lambdaSymbol.Parameters; ParameterHelpers.EnsureIsReadOnlyAttributeExists(compilation, lambdaParameters, diagnostics, modifyCompilation: false); if (returnType.HasType) { if (returnType.Type.ContainsNativeInteger()) { compilation.EnsureNativeIntegerAttributeExists(diagnostics, lambdaSymbol.DiagnosticLocation, modifyCompilation: false); } if (compilation.ShouldEmitNullableAttributes(lambdaSymbol) && returnType.NeedsNullableAttribute()) { compilation.EnsureNullableAttributeExists(diagnostics, lambdaSymbol.DiagnosticLocation, modifyCompilation: false); // Note: we don't need to warn on annotations used in #nullable disable context for lambdas, as this is handled in binding already } } ParameterHelpers.EnsureNativeIntegerAttributeExists(compilation, lambdaParameters, diagnostics, modifyCompilation: false); ParameterHelpers.EnsureNullableAttributeExists(compilation, lambdaSymbol, lambdaParameters, diagnostics, modifyCompilation: false); // Note: we don't need to warn on annotations used in #nullable disable context for lambdas, as this is handled in binding already ValidateUnsafeParameters(diagnostics, cacheKey.ParameterTypes); bool reachableEndpoint = ControlFlowPass.Analyze(compilation, lambdaSymbol, block, diagnostics.DiagnosticBag); if (reachableEndpoint) { if (Binder.MethodOrLambdaRequiresValue(lambdaSymbol, this.Binder.Compilation)) { // Not all code paths return a value in {0} of type '{1}' diagnostics.Add(ErrorCode.ERR_AnonymousReturnExpected, lambdaSymbol.DiagnosticLocation, this.MessageID.Localize(), delegateType); } else { block = FlowAnalysisPass.AppendImplicitReturn(block, lambdaSymbol); } } if (IsAsync && !ErrorFacts.PreventsSuccessfulDelegateConversion(diagnostics.DiagnosticBag)) { if (returnType.HasType && // Can be null if "delegateType" is not actually a delegate type. !returnType.IsVoidType() && !lambdaSymbol.IsAsyncEffectivelyReturningTask(compilation) && !lambdaSymbol.IsAsyncEffectivelyReturningGenericTask(compilation)) { // 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}'. diagnostics.Add(ErrorCode.ERR_CantConvAsyncAnonFuncReturns, lambdaSymbol.DiagnosticLocation, lambdaSymbol.MessageID.Localize(), delegateType); } } var result = new BoundLambda(_unboundLambda.Syntax, _unboundLambda, block, diagnostics.ToReadOnlyAndFree(), lambdaBodyBinder, delegateType, inferredReturnType: default) { WasCompilerGenerated = _unboundLambda.WasCompilerGenerated }; return result; } internal LambdaSymbol CreateLambdaSymbol( Symbol containingSymbol, TypeWithAnnotations returnType, ImmutableArray<TypeWithAnnotations> parameterTypes, ImmutableArray<RefKind> parameterRefKinds, RefKind refKind) => new LambdaSymbol( Binder, Binder.Compilation, containingSymbol, _unboundLambda, parameterTypes, parameterRefKinds, refKind, returnType); internal LambdaSymbol CreateLambdaSymbol(NamedTypeSymbol delegateType, Symbol containingSymbol) { var invokeMethod = DelegateInvokeMethod(delegateType); var returnType = DelegateReturnTypeWithAnnotations(invokeMethod, out RefKind refKind); ReturnInferenceCacheKey.GetFields(delegateType, IsAsync, out var parameterTypes, out var parameterRefKinds, out _); return CreateLambdaSymbol(containingSymbol, returnType, parameterTypes, parameterRefKinds, refKind); } private void ValidateUnsafeParameters(BindingDiagnosticBag diagnostics, ImmutableArray<TypeWithAnnotations> targetParameterTypes) { // It is legal to use a delegate type that has unsafe parameter types inside // a safe context if the anonymous method has no parameter list! // // unsafe delegate void D(int* p); // class C { D d = delegate {}; } // // is legal even if C is not an unsafe context because no int* is actually used. if (this.HasSignature) { // NOTE: we can get here with targetParameterTypes.Length > ParameterCount // in a case where we are binding for error reporting purposes var numParametersToCheck = Math.Min(targetParameterTypes.Length, ParameterCount); for (int i = 0; i < numParametersToCheck; i++) { if (targetParameterTypes[i].Type.IsUnsafe()) { this.Binder.ReportUnsafeIfNotAllowed(this.ParameterLocation(i), diagnostics); } } } } private BoundLambda ReallyInferReturnType( NamedTypeSymbol? delegateType, ImmutableArray<TypeWithAnnotations> parameterTypes, ImmutableArray<RefKind> parameterRefKinds) { bool hasExplicitReturnType = HasExplicitReturnType(out var refKind, out var returnType); (var lambdaSymbol, var block, var lambdaBodyBinder, var diagnostics) = BindWithParameterAndReturnType(parameterTypes, parameterRefKinds, returnType, refKind); InferredLambdaReturnType inferredReturnType; if (hasExplicitReturnType) { // The InferredLambdaReturnType fields other than RefKind and ReturnType // are only used when actually inferring a type, not when the type is explicit. inferredReturnType = new InferredLambdaReturnType( numExpressions: 0, isExplicitType: true, hadExpressionlessReturn: false, refKind, returnType, ImmutableArray<DiagnosticInfo>.Empty, ImmutableArray<AssemblySymbol>.Empty); } else { var returnTypes = ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>.GetInstance(); BoundLambda.BlockReturns.GetReturnTypes(returnTypes, block); inferredReturnType = BoundLambda.InferReturnType(returnTypes, _unboundLambda, lambdaBodyBinder, delegateType, lambdaSymbol.IsAsync, lambdaBodyBinder.Conversions); // TODO: Should InferredReturnType.UseSiteDiagnostics be merged into BoundLambda.Diagnostics? refKind = inferredReturnType.RefKind; returnType = inferredReturnType.TypeWithAnnotations; if (!returnType.HasType) { bool forErrorRecovery = delegateType is null; returnType = (forErrorRecovery && returnTypes.Count == 0) ? TypeWithAnnotations.Create(this.Binder.Compilation.GetSpecialType(SpecialType.System_Void)) : TypeWithAnnotations.Create(LambdaSymbol.InferenceFailureReturnType); } returnTypes.Free(); } var result = new BoundLambda( _unboundLambda.Syntax, _unboundLambda, block, diagnostics.ToReadOnlyAndFree(), lambdaBodyBinder, delegateType, inferredReturnType) { WasCompilerGenerated = _unboundLambda.WasCompilerGenerated }; if (!hasExplicitReturnType) { lambdaSymbol.SetInferredReturnType(refKind, returnType); } return result; } private (LambdaSymbol lambdaSymbol, BoundBlock block, ExecutableCodeBinder lambdaBodyBinder, BindingDiagnosticBag diagnostics) BindWithParameterAndReturnType( ImmutableArray<TypeWithAnnotations> parameterTypes, ImmutableArray<RefKind> parameterRefKinds, TypeWithAnnotations returnType, RefKind refKind) { var diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, _unboundLambda.WithDependencies); var lambdaSymbol = CreateLambdaSymbol(Binder.ContainingMemberOrLambda!, returnType, parameterTypes, parameterRefKinds, refKind); var lambdaBodyBinder = new ExecutableCodeBinder(_unboundLambda.Syntax, lambdaSymbol, ParameterBinder(lambdaSymbol, Binder)); var block = BindLambdaBody(lambdaSymbol, lambdaBodyBinder, diagnostics); lambdaSymbol.GetDeclarationDiagnostics(diagnostics); return (lambdaSymbol, block, lambdaBodyBinder, diagnostics); } public BoundLambda BindForReturnTypeInference(NamedTypeSymbol delegateType) { var cacheKey = ReturnInferenceCacheKey.Create(delegateType, IsAsync); BoundLambda? result; if (!_returnInferenceCache!.TryGetValue(cacheKey, out result)) { result = ReallyInferReturnType(delegateType, cacheKey.ParameterTypes, cacheKey.ParameterRefKinds); result = ImmutableInterlocked.GetOrAdd(ref _returnInferenceCache, cacheKey, result); } return result; } /// <summary> /// Behavior of this key should be kept aligned with <see cref="BoundLambda.InferReturnTypeImpl"/>. /// </summary> private sealed class ReturnInferenceCacheKey { public readonly ImmutableArray<TypeWithAnnotations> ParameterTypes; public readonly ImmutableArray<RefKind> ParameterRefKinds; public readonly NamedTypeSymbol? TaskLikeReturnTypeOpt; public static readonly ReturnInferenceCacheKey Empty = new ReturnInferenceCacheKey(ImmutableArray<TypeWithAnnotations>.Empty, ImmutableArray<RefKind>.Empty, null); private ReturnInferenceCacheKey(ImmutableArray<TypeWithAnnotations> parameterTypes, ImmutableArray<RefKind> parameterRefKinds, NamedTypeSymbol? taskLikeReturnTypeOpt) { Debug.Assert(parameterTypes.Length == parameterRefKinds.Length); Debug.Assert(taskLikeReturnTypeOpt is null || ((object)taskLikeReturnTypeOpt == taskLikeReturnTypeOpt.ConstructedFrom && taskLikeReturnTypeOpt.IsCustomTaskType(out var builderArgument))); this.ParameterTypes = parameterTypes; this.ParameterRefKinds = parameterRefKinds; this.TaskLikeReturnTypeOpt = taskLikeReturnTypeOpt; } public override bool Equals(object? obj) { if ((object)this == obj) { return true; } var other = obj as ReturnInferenceCacheKey; if (other is null || other.ParameterTypes.Length != this.ParameterTypes.Length || !TypeSymbol.Equals(other.TaskLikeReturnTypeOpt, this.TaskLikeReturnTypeOpt, TypeCompareKind.ConsiderEverything2)) { return false; } for (int i = 0; i < this.ParameterTypes.Length; i++) { if (!other.ParameterTypes[i].Equals(this.ParameterTypes[i], TypeCompareKind.ConsiderEverything) || other.ParameterRefKinds[i] != this.ParameterRefKinds[i]) { return false; } } return true; } public override int GetHashCode() { var value = TaskLikeReturnTypeOpt?.GetHashCode() ?? 0; foreach (var type in ParameterTypes) { value = Hash.Combine(type.Type, value); } return value; } public static ReturnInferenceCacheKey Create(NamedTypeSymbol? delegateType, bool isAsync) { GetFields(delegateType, isAsync, out var parameterTypes, out var parameterRefKinds, out var taskLikeReturnTypeOpt); if (parameterTypes.IsEmpty && parameterRefKinds.IsEmpty && taskLikeReturnTypeOpt is null) { return Empty; } return new ReturnInferenceCacheKey(parameterTypes, parameterRefKinds, taskLikeReturnTypeOpt); } public static void GetFields( NamedTypeSymbol? delegateType, bool isAsync, out ImmutableArray<TypeWithAnnotations> parameterTypes, out ImmutableArray<RefKind> parameterRefKinds, out NamedTypeSymbol? taskLikeReturnTypeOpt) { // delegateType or DelegateInvokeMethod can be null in cases of malformed delegates // in such case we would want something trivial with no parameters parameterTypes = ImmutableArray<TypeWithAnnotations>.Empty; parameterRefKinds = ImmutableArray<RefKind>.Empty; taskLikeReturnTypeOpt = null; MethodSymbol? invoke = DelegateInvokeMethod(delegateType); if (invoke is not null) { int parameterCount = invoke.ParameterCount; if (parameterCount > 0) { var typesBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(parameterCount); var refKindsBuilder = ArrayBuilder<RefKind>.GetInstance(parameterCount); foreach (var p in invoke.Parameters) { refKindsBuilder.Add(p.RefKind); typesBuilder.Add(p.TypeWithAnnotations); } parameterTypes = typesBuilder.ToImmutableAndFree(); parameterRefKinds = refKindsBuilder.ToImmutableAndFree(); } if (isAsync) { var delegateReturnType = invoke.ReturnType as NamedTypeSymbol; if (delegateReturnType?.IsVoidType() == false) { if (delegateReturnType.IsCustomTaskType(out var builderType)) { taskLikeReturnTypeOpt = delegateReturnType.ConstructedFrom; } } } } } } public virtual Binder ParameterBinder(LambdaSymbol lambdaSymbol, Binder binder) { return new WithLambdaParametersBinder(lambdaSymbol, binder); } // UNDONE: [MattWar] // UNDONE: Here we enable the consumer of an unbound lambda that could not be // UNDONE: successfully converted to a best bound lambda to do error recovery // UNDONE: by either picking an existing binding, or by binding the body using // UNDONE: error types for parameter types as necessary. This is not exactly // UNDONE: the strategy we discussed in the design meeting; rather there we // UNDONE: decided to do this more the way we did it in the native compiler: // UNDONE: there we wrote a post-processing pass that searched the tree for // UNDONE: unbound lambdas and did this sort of replacement on them, so that // UNDONE: we never observed an unbound lambda in the tree. // UNDONE: // UNDONE: I think that is a reasonable approach but it is not implemented yet. // UNDONE: When we figure out precisely where that rewriting pass should go, // UNDONE: we can use the gear implemented in this method as an implementation // UNDONE: detail of it. // UNDONE: // UNDONE: Note: that rewriting can now be done in BindToTypeForErrorRecovery. public BoundLambda BindForErrorRecovery() { // It is possible that either (1) we never did a binding, because // we've got code like "var x = (z)=>{int y = 123; M(y, z);};" or // (2) we did a bunch of bindings but none of them turned out to // be the one we wanted. In such a situation we still want // IntelliSense to work on y in the body of the lambda, and // possibly to make a good guess as to what M means even if we // don't know the type of z. if (_errorBinding == null) { Interlocked.CompareExchange(ref _errorBinding, ReallyBindForErrorRecovery(), null); } return _errorBinding; } private BoundLambda ReallyBindForErrorRecovery() { // If we have bindings, we can use heuristics to choose one. // If not, we can assign error types to all the parameters // and bind. return GuessBestBoundLambda(_bindingCache!) ?? rebind(GuessBestBoundLambda(_returnInferenceCache!)) ?? rebind(ReallyInferReturnType(delegateType: null, ImmutableArray<TypeWithAnnotations>.Empty, ImmutableArray<RefKind>.Empty)); // Rebind a lambda to push target conversions through the return/result expressions [return: NotNullIfNotNull("lambda")] BoundLambda? rebind(BoundLambda? lambda) { if (lambda is null) return null; var delegateType = (NamedTypeSymbol?)lambda.Type; ReturnInferenceCacheKey.GetFields(delegateType, IsAsync, out var parameterTypes, out var parameterRefKinds, out _); return ReallyBindForErrorRecovery(delegateType, lambda.InferredReturnType, parameterTypes, parameterRefKinds); } } private BoundLambda ReallyBindForErrorRecovery( NamedTypeSymbol? delegateType, InferredLambdaReturnType inferredReturnType, ImmutableArray<TypeWithAnnotations> parameterTypes, ImmutableArray<RefKind> parameterRefKinds) { var returnType = inferredReturnType.TypeWithAnnotations; var refKind = inferredReturnType.RefKind; if (!returnType.HasType) { Debug.Assert(!inferredReturnType.IsExplicitType); var invokeMethod = DelegateInvokeMethod(delegateType); returnType = DelegateReturnTypeWithAnnotations(invokeMethod, out refKind); if (!returnType.HasType || returnType.Type.ContainsTypeParameter()) { var t = (inferredReturnType.HadExpressionlessReturn || inferredReturnType.NumExpressions == 0) ? this.Binder.Compilation.GetSpecialType(SpecialType.System_Void) : this.Binder.CreateErrorType(); returnType = TypeWithAnnotations.Create(t); refKind = CodeAnalysis.RefKind.None; } } (var lambdaSymbol, var block, var lambdaBodyBinder, var diagnostics) = BindWithParameterAndReturnType(parameterTypes, parameterRefKinds, returnType, refKind); return new BoundLambda( _unboundLambda.Syntax, _unboundLambda, block, diagnostics.ToReadOnlyAndFree(), lambdaBodyBinder, delegateType, new InferredLambdaReturnType(inferredReturnType.NumExpressions, isExplicitType: inferredReturnType.IsExplicitType, inferredReturnType.HadExpressionlessReturn, refKind, returnType, ImmutableArray<DiagnosticInfo>.Empty, ImmutableArray<AssemblySymbol>.Empty)) { WasCompilerGenerated = _unboundLambda.WasCompilerGenerated }; } private static BoundLambda? GuessBestBoundLambda<T>(ImmutableDictionary<T, BoundLambda> candidates) where T : notnull { switch (candidates.Count) { case 0: return null; case 1: return candidates.First().Value; default: // Prefer candidates with fewer diagnostics. IEnumerable<KeyValuePair<T, BoundLambda>> minDiagnosticsGroup = candidates.GroupBy(lambda => lambda.Value.Diagnostics.Diagnostics.Length).OrderBy(group => group.Key).First(); // If multiple candidates have the same number of diagnostics, order them by delegate type name. // It's not great, but it should be stable. return minDiagnosticsGroup .OrderBy(lambda => GetLambdaSortString(lambda.Value.Symbol)) .FirstOrDefault() .Value; } } private static string GetLambdaSortString(LambdaSymbol lambda) { var builder = PooledStringBuilder.GetInstance(); foreach (var parameter in lambda.Parameters) { builder.Builder.Append(parameter.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat)); } if (lambda.ReturnTypeWithAnnotations.HasType) { builder.Builder.Append(lambda.ReturnTypeWithAnnotations.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)); } var result = builder.ToStringAndFree(); return result; } public bool GenerateSummaryErrors(BindingDiagnosticBag diagnostics) { // It is highly likely that "the same" error will be given for two different // bindings of the same lambda but with different values for the parameters // of the error. For example, if we have x=>x.Blah() where x could be int // or string, then the two errors will be "int does not have member Blah" and // "string does not have member Blah", but the locations and errors numbers // will be the same. // // We should first see if there is a set of errors that are "the same" by // this definition that occur in every lambda binding; if there are then // those are the errors we should report. // // If there are no errors that are common to *every* binding then we // can report the complete set of errors produced by every binding. However, // we still wish to avoid duplicates, so we will use the same logic for // building the union as the intersection; two errors with the same code // and location are to be treated as the same error and only reported once, // regardless of how that error is parameterized. // // The question then rears its head: when given two of "the same" error // to report that are nevertheless different in their arguments, which one // do we choose? To the user it hardly matters; either one points to the // right location in source code. But it surely matters to our testing team; // we do not want to be in a position where some small change to our internal // representation of lambdas causes tests to break because errors are reported // differently. // // What we need to do is find a *repeatable* arbitrary way to choose between // two errors; we can for example simply take the one that is lower in alphabetical // order when converted to a string. var convBags = from boundLambda in _bindingCache select boundLambda.Value.Diagnostics; var retBags = from boundLambda in _returnInferenceCache!.Values select boundLambda.Diagnostics; var allBags = convBags.Concat(retBags); FirstAmongEqualsSet<Diagnostic>? intersection = null; foreach (ImmutableBindingDiagnostic<AssemblySymbol> bag in allBags) { if (intersection == null) { intersection = CreateFirstAmongEqualsSet(bag.Diagnostics); } else { intersection.IntersectWith(bag.Diagnostics); } } if (intersection != null) { if (PreventsSuccessfulDelegateConversion(intersection)) { diagnostics.AddRange(intersection); return true; } } FirstAmongEqualsSet<Diagnostic>? union = null; foreach (ImmutableBindingDiagnostic<AssemblySymbol> bag in allBags) { if (union == null) { union = CreateFirstAmongEqualsSet(bag.Diagnostics); } else { union.UnionWith(bag.Diagnostics); } } if (union != null) { if (PreventsSuccessfulDelegateConversion(union)) { diagnostics.AddRange(union); return true; } } return false; } private static bool PreventsSuccessfulDelegateConversion(FirstAmongEqualsSet<Diagnostic> set) { foreach (var diagnostic in set) { if (ErrorFacts.PreventsSuccessfulDelegateConversion((ErrorCode)diagnostic.Code)) { return true; } } return false; } private static FirstAmongEqualsSet<Diagnostic> CreateFirstAmongEqualsSet(ImmutableArray<Diagnostic> bag) { // For the purposes of lambda error reporting we wish to compare // diagnostics for equality only considering their code and location, // but not other factors such as the values supplied for the // parameters of the diagnostic. return new FirstAmongEqualsSet<Diagnostic>( bag, CommonDiagnosticComparer.Instance, CanonicallyCompareDiagnostics); } /// <summary> /// What we need to do is find a *repeatable* arbitrary way to choose between /// two errors; we can for example simply take the one whose arguments are lower in alphabetical /// order when converted to a string. As an optimization, we compare error codes /// first and skip string comparison if they differ. /// </summary> private static int CanonicallyCompareDiagnostics(Diagnostic x, Diagnostic y) { // Optimization: don't bother if (x.Code != y.Code) return x.Code - y.Code; var nx = x.Arguments?.Count ?? 0; var ny = y.Arguments?.Count ?? 0; for (int i = 0, n = Math.Min(nx, ny); i < n; i++) { object? argx = x.Arguments![i]; object? argy = y.Arguments![i]; int argCompare = string.CompareOrdinal(argx?.ToString(), argy?.ToString()); if (argCompare != 0) return argCompare; } return nx - ny; } } internal sealed class PlainUnboundLambdaState : UnboundLambdaState { private readonly RefKind _returnRefKind; private readonly TypeWithAnnotations _returnType; private readonly ImmutableArray<SyntaxList<AttributeListSyntax>> _parameterAttributes; private readonly ImmutableArray<string> _parameterNames; private readonly ImmutableArray<bool> _parameterIsDiscardOpt; private readonly ImmutableArray<TypeWithAnnotations> _parameterTypesWithAnnotations; private readonly ImmutableArray<RefKind> _parameterRefKinds; private readonly bool _isAsync; private readonly bool _isStatic; internal PlainUnboundLambdaState( Binder binder, RefKind returnRefKind, TypeWithAnnotations returnType, ImmutableArray<SyntaxList<AttributeListSyntax>> parameterAttributes, ImmutableArray<string> parameterNames, ImmutableArray<bool> parameterIsDiscardOpt, ImmutableArray<TypeWithAnnotations> parameterTypesWithAnnotations, ImmutableArray<RefKind> parameterRefKinds, bool isAsync, bool isStatic, bool includeCache) : base(binder, includeCache) { _returnRefKind = returnRefKind; _returnType = returnType; _parameterAttributes = parameterAttributes; _parameterNames = parameterNames; _parameterIsDiscardOpt = parameterIsDiscardOpt; _parameterTypesWithAnnotations = parameterTypesWithAnnotations; _parameterRefKinds = parameterRefKinds; _isAsync = isAsync; _isStatic = isStatic; } public override bool HasNames { get { return !_parameterNames.IsDefault; } } public override bool HasSignature { get { return !_parameterNames.IsDefault; } } public override bool HasExplicitReturnType(out RefKind refKind, out TypeWithAnnotations returnType) { refKind = _returnRefKind; returnType = _returnType; return _returnType.HasType; } public override bool HasExplicitlyTypedParameterList { get { return !_parameterTypesWithAnnotations.IsDefault; } } public override int ParameterCount { get { return _parameterNames.IsDefault ? 0 : _parameterNames.Length; } } public override bool IsAsync { get { return _isAsync; } } public override bool IsStatic => _isStatic; public override MessageID MessageID { get { return this.UnboundLambda.Syntax.Kind() == SyntaxKind.AnonymousMethodExpression ? MessageID.IDS_AnonMethod : MessageID.IDS_Lambda; } } private CSharpSyntaxNode Body { get { return UnboundLambda.Syntax.AnonymousFunctionBody(); } } public override Location ParameterLocation(int index) { Debug.Assert(HasSignature && 0 <= index && index < ParameterCount); var syntax = UnboundLambda.Syntax; switch (syntax.Kind()) { default: case SyntaxKind.SimpleLambdaExpression: return ((SimpleLambdaExpressionSyntax)syntax).Parameter.Identifier.GetLocation(); case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)syntax).ParameterList.Parameters[index].Identifier.GetLocation(); case SyntaxKind.AnonymousMethodExpression: return ((AnonymousMethodExpressionSyntax)syntax).ParameterList!.Parameters[index].Identifier.GetLocation(); } } private bool IsExpressionLambda { get { return Body.Kind() != SyntaxKind.Block; } } public override SyntaxList<AttributeListSyntax> ParameterAttributes(int index) { return _parameterAttributes.IsDefault ? default : _parameterAttributes[index]; } public override string ParameterName(int index) { Debug.Assert(!_parameterNames.IsDefault && 0 <= index && index < _parameterNames.Length); return _parameterNames[index]; } public override bool ParameterIsDiscard(int index) { return _parameterIsDiscardOpt.IsDefault ? false : _parameterIsDiscardOpt[index]; } public override RefKind RefKind(int index) { Debug.Assert(0 <= index && index < _parameterTypesWithAnnotations.Length); return _parameterRefKinds.IsDefault ? Microsoft.CodeAnalysis.RefKind.None : _parameterRefKinds[index]; } public override TypeWithAnnotations ParameterTypeWithAnnotations(int index) { Debug.Assert(this.HasExplicitlyTypedParameterList); Debug.Assert(0 <= index && index < _parameterTypesWithAnnotations.Length); return _parameterTypesWithAnnotations[index]; } protected override UnboundLambdaState WithCachingCore(bool includeCache) { return new PlainUnboundLambdaState(Binder, _returnRefKind, _returnType, _parameterAttributes, _parameterNames, _parameterIsDiscardOpt, _parameterTypesWithAnnotations, _parameterRefKinds, _isAsync, _isStatic, includeCache); } protected override BoundExpression? GetLambdaExpressionBody(BoundBlock body) { if (IsExpressionLambda) { var statements = body.Statements; if (statements.Length == 1 && // To simplify Binder.CreateBlockFromExpression (used below), we only reuse by-value return values. statements[0] is BoundReturnStatement { RefKind: Microsoft.CodeAnalysis.RefKind.None, ExpressionOpt: BoundExpression expr }) { return expr; } } return null; } protected override BoundBlock CreateBlockFromLambdaExpressionBody(Binder lambdaBodyBinder, BoundExpression expression, BindingDiagnosticBag diagnostics) { return lambdaBodyBinder.CreateBlockFromExpression((ExpressionSyntax)this.Body, expression, diagnostics); } protected override BoundBlock BindLambdaBody(LambdaSymbol lambdaSymbol, Binder lambdaBodyBinder, BindingDiagnosticBag diagnostics) { if (this.IsExpressionLambda) { return lambdaBodyBinder.BindLambdaExpressionAsBlock((ExpressionSyntax)this.Body, diagnostics); } else { return lambdaBodyBinder.BindEmbeddedBlock((BlockSyntax)this.Body, diagnostics); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { internal interface IBoundLambdaOrFunction { MethodSymbol Symbol { get; } SyntaxNode Syntax { get; } BoundBlock? Body { get; } bool WasCompilerGenerated { get; } } internal sealed partial class BoundLocalFunctionStatement : IBoundLambdaOrFunction { MethodSymbol IBoundLambdaOrFunction.Symbol { get { return Symbol; } } SyntaxNode IBoundLambdaOrFunction.Syntax { get { return Syntax; } } BoundBlock? IBoundLambdaOrFunction.Body { get => this.Body; } } internal readonly struct InferredLambdaReturnType { internal readonly int NumExpressions; internal readonly bool IsExplicitType; internal readonly bool HadExpressionlessReturn; internal readonly RefKind RefKind; internal readonly TypeWithAnnotations TypeWithAnnotations; internal readonly ImmutableArray<DiagnosticInfo> UseSiteDiagnostics; internal readonly ImmutableArray<AssemblySymbol> Dependencies; internal InferredLambdaReturnType( int numExpressions, bool isExplicitType, bool hadExpressionlessReturn, RefKind refKind, TypeWithAnnotations typeWithAnnotations, ImmutableArray<DiagnosticInfo> useSiteDiagnostics, ImmutableArray<AssemblySymbol> dependencies) { NumExpressions = numExpressions; IsExplicitType = isExplicitType; HadExpressionlessReturn = hadExpressionlessReturn; RefKind = refKind; TypeWithAnnotations = typeWithAnnotations; UseSiteDiagnostics = useSiteDiagnostics; Dependencies = dependencies; } } internal sealed partial class BoundLambda : IBoundLambdaOrFunction { public MessageID MessageID { get { return Syntax.Kind() == SyntaxKind.AnonymousMethodExpression ? MessageID.IDS_AnonMethod : MessageID.IDS_Lambda; } } internal InferredLambdaReturnType InferredReturnType { get; } MethodSymbol IBoundLambdaOrFunction.Symbol { get { return Symbol; } } SyntaxNode IBoundLambdaOrFunction.Syntax { get { return Syntax; } } public BoundLambda(SyntaxNode syntax, UnboundLambda unboundLambda, BoundBlock body, ImmutableBindingDiagnostic<AssemblySymbol> diagnostics, Binder binder, TypeSymbol? delegateType, InferredLambdaReturnType inferredReturnType) : this(syntax, unboundLambda.WithNoCache(), (LambdaSymbol)binder.ContainingMemberOrLambda!, body, diagnostics, binder, delegateType) { InferredReturnType = inferredReturnType; Debug.Assert( syntax.IsAnonymousFunction() || // lambda expressions syntax is ExpressionSyntax && LambdaUtilities.IsLambdaBody(syntax, allowReducedLambdas: true) || // query lambdas LambdaUtilities.IsQueryPairLambda(syntax) // "pair" lambdas in queries ); } public TypeWithAnnotations GetInferredReturnType(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // Nullability (and conversions) are ignored. return GetInferredReturnType(conversions: null, nullableState: null, ref useSiteInfo); } /// <summary> /// Infer return type. If `nullableState` is non-null, nullability is also inferred and `NullableWalker.Analyze` /// uses that state to set the inferred nullability of variables in the enclosing scope. `conversions` is /// only needed when nullability is inferred. /// </summary> public TypeWithAnnotations GetInferredReturnType(ConversionsBase? conversions, NullableWalker.VariableState? nullableState, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (!InferredReturnType.UseSiteDiagnostics.IsEmpty) { useSiteInfo.AddDiagnostics(InferredReturnType.UseSiteDiagnostics); } if (!InferredReturnType.Dependencies.IsEmpty) { useSiteInfo.AddDependencies(InferredReturnType.Dependencies); } if (nullableState == null || InferredReturnType.IsExplicitType) { return InferredReturnType.TypeWithAnnotations; } else { Debug.Assert(!UnboundLambda.HasExplicitReturnType(out _, out _)); Debug.Assert(conversions != null); // Diagnostics from NullableWalker.Analyze can be dropped here since Analyze // will be called again from NullableWalker.ApplyConversion when the // BoundLambda is converted to an anonymous function. // https://github.com/dotnet/roslyn/issues/31752: Can we avoid generating extra // diagnostics? And is this exponential when there are nested lambdas? var returnTypes = ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>.GetInstance(); var diagnostics = DiagnosticBag.GetInstance(); var delegateType = Type.GetDelegateType(); var compilation = Binder.Compilation; NullableWalker.Analyze(compilation, lambda: this, (Conversions)conversions, diagnostics, delegateInvokeMethodOpt: delegateType?.DelegateInvokeMethod, initialState: nullableState, returnTypes); diagnostics.Free(); var inferredReturnType = InferReturnType(returnTypes, node: this, Binder, delegateType, Symbol.IsAsync, conversions); returnTypes.Free(); return inferredReturnType.TypeWithAnnotations; } } internal LambdaSymbol CreateLambdaSymbol(NamedTypeSymbol delegateType, Symbol containingSymbol) => UnboundLambda.Data.CreateLambdaSymbol(delegateType, containingSymbol); internal LambdaSymbol CreateLambdaSymbol( Symbol containingSymbol, TypeWithAnnotations returnType, ImmutableArray<TypeWithAnnotations> parameterTypes, ImmutableArray<RefKind> parameterRefKinds, RefKind refKind) => UnboundLambda.Data.CreateLambdaSymbol( containingSymbol, returnType, parameterTypes, parameterRefKinds.IsDefault ? Enumerable.Repeat(RefKind.None, parameterTypes.Length).ToImmutableArray() : parameterRefKinds, refKind); /// <summary> /// Indicates the type of return statement with no expression. Used in InferReturnType. /// </summary> internal static readonly TypeSymbol NoReturnExpression = new UnsupportedMetadataTypeSymbol(); internal static InferredLambdaReturnType InferReturnType(ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)> returnTypes, BoundLambda node, Binder binder, TypeSymbol? delegateType, bool isAsync, ConversionsBase conversions) { Debug.Assert(!node.UnboundLambda.HasExplicitReturnType(out _, out _)); return InferReturnTypeImpl(returnTypes, node, binder, delegateType, isAsync, conversions, node.UnboundLambda.WithDependencies); } internal static InferredLambdaReturnType InferReturnType(ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)> returnTypes, UnboundLambda node, Binder binder, TypeSymbol? delegateType, bool isAsync, ConversionsBase conversions) { Debug.Assert(!node.HasExplicitReturnType(out _, out _)); return InferReturnTypeImpl(returnTypes, node, binder, delegateType, isAsync, conversions, node.WithDependencies); } /// <summary> /// Behavior of this function should be kept aligned with <see cref="UnboundLambdaState.ReturnInferenceCacheKey"/>. /// </summary> private static InferredLambdaReturnType InferReturnTypeImpl(ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)> returnTypes, BoundNode node, Binder binder, TypeSymbol? delegateType, bool isAsync, ConversionsBase conversions, bool withDependencies) { var types = ArrayBuilder<(BoundExpression, TypeWithAnnotations)>.GetInstance(); bool hasReturnWithoutArgument = false; RefKind refKind = RefKind.None; foreach (var (returnStatement, type) in returnTypes) { RefKind rk = returnStatement.RefKind; if (rk != RefKind.None) { refKind = rk; } if ((object)type.Type == NoReturnExpression) { hasReturnWithoutArgument = true; } else { types.Add((returnStatement.ExpressionOpt!, type)); } } var useSiteInfo = withDependencies ? new CompoundUseSiteInfo<AssemblySymbol>(binder.Compilation.Assembly) : CompoundUseSiteInfo<AssemblySymbol>.DiscardedDependencies; var bestType = CalculateReturnType(binder, conversions, delegateType, types, isAsync, node, ref useSiteInfo); int numExpressions = types.Count; types.Free(); return new InferredLambdaReturnType( numExpressions, isExplicitType: false, hasReturnWithoutArgument, refKind, bestType, useSiteInfo.Diagnostics.AsImmutableOrEmpty(), useSiteInfo.AccumulatesDependencies ? useSiteInfo.Dependencies.AsImmutableOrEmpty() : ImmutableArray<AssemblySymbol>.Empty); } private static TypeWithAnnotations CalculateReturnType( Binder binder, ConversionsBase conversions, TypeSymbol? delegateType, ArrayBuilder<(BoundExpression, TypeWithAnnotations resultType)> returns, bool isAsync, BoundNode node, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { TypeWithAnnotations bestResultType; int n = returns.Count; switch (n) { case 0: bestResultType = default; break; case 1: bestResultType = returns[0].resultType; break; default: // Need to handle ref returns. See https://github.com/dotnet/roslyn/issues/30432 if (conversions.IncludeNullability) { bestResultType = NullableWalker.BestTypeForLambdaReturns(returns, binder, node, (Conversions)conversions); } else { var typesOnly = ArrayBuilder<TypeSymbol>.GetInstance(n); foreach (var (_, resultType) in returns) { typesOnly.Add(resultType.Type); } var bestType = BestTypeInferrer.GetBestType(typesOnly, conversions, ref useSiteInfo); bestResultType = bestType is null ? default : TypeWithAnnotations.Create(bestType); typesOnly.Free(); } break; } if (!isAsync) { return bestResultType; } // For async lambdas, the return type is the return type of the // delegate Invoke method if Invoke has a Task-like return type. // Otherwise the return type is Task or Task<T>. NamedTypeSymbol? taskType = null; var delegateReturnType = delegateType?.GetDelegateType()?.DelegateInvokeMethod?.ReturnType as NamedTypeSymbol; if (delegateReturnType?.IsVoidType() == false) { if (delegateReturnType.IsCustomTaskType(builderArgument: out _)) { taskType = delegateReturnType.ConstructedFrom; } } if (n == 0) { // No return statements have expressions; use delegate InvokeMethod // or infer type Task if delegate type not available. var resultType = taskType?.Arity == 0 ? taskType : binder.Compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task); return TypeWithAnnotations.Create(resultType); } if (!bestResultType.HasType || bestResultType.IsVoidType()) { // If the best type was 'void', ERR_CantReturnVoid is reported while binding the "return void" // statement(s). return default; } // Some non-void best type T was found; use delegate InvokeMethod // or infer type Task<T> if delegate type not available. var taskTypeT = taskType?.Arity == 1 ? taskType : binder.Compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T); return TypeWithAnnotations.Create(taskTypeT.Construct(ImmutableArray.Create(bestResultType))); } internal sealed class BlockReturns : BoundTreeWalker { private readonly ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)> _builder; private BlockReturns(ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)> builder) { _builder = builder; } public static void GetReturnTypes(ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)> builder, BoundBlock block) { var visitor = new BlockReturns(builder); visitor.Visit(block); } public override BoundNode? Visit(BoundNode node) { if (!(node is BoundExpression)) { return base.Visit(node); } return null; } protected override BoundExpression VisitExpressionWithoutStackGuard(BoundExpression node) { throw ExceptionUtilities.Unreachable; } public override BoundNode? VisitLocalFunctionStatement(BoundLocalFunctionStatement node) { // Do not recurse into local functions; we don't want their returns. return null; } public override BoundNode? VisitReturnStatement(BoundReturnStatement node) { var expression = node.ExpressionOpt; var type = (expression is null) ? NoReturnExpression : expression.Type?.SetUnknownNullabilityForReferenceTypes(); _builder.Add((node, TypeWithAnnotations.Create(type))); return null; } } } internal partial class UnboundLambda { private readonly NullableWalker.VariableState? _nullableState; public UnboundLambda( CSharpSyntaxNode syntax, Binder binder, bool withDependencies, RefKind returnRefKind, TypeWithAnnotations returnType, ImmutableArray<SyntaxList<AttributeListSyntax>> parameterAttributes, ImmutableArray<RefKind> refKinds, ImmutableArray<TypeWithAnnotations> types, ImmutableArray<string> names, ImmutableArray<bool> discardsOpt, bool isAsync, bool isStatic) : this(syntax, new PlainUnboundLambdaState(binder, returnRefKind, returnType, parameterAttributes, names, discardsOpt, types, refKinds, isAsync, isStatic, includeCache: true), withDependencies, !types.IsDefault && types.Any(t => t.Type?.Kind == SymbolKind.ErrorType)) { Debug.Assert(binder != null); Debug.Assert(syntax.IsAnonymousFunction()); this.Data.SetUnboundLambda(this); } private UnboundLambda(SyntaxNode syntax, UnboundLambdaState state, bool withDependencies, NullableWalker.VariableState? nullableState, bool hasErrors) : this(syntax, state, withDependencies, hasErrors) { this._nullableState = nullableState; } internal UnboundLambda WithNullableState(NullableWalker.VariableState nullableState) { var data = Data.WithCaching(true); var lambda = new UnboundLambda(Syntax, data, WithDependencies, nullableState, HasErrors); data.SetUnboundLambda(lambda); return lambda; } internal UnboundLambda WithNoCache() { var data = Data.WithCaching(false); if ((object)data == Data) { return this; } var lambda = new UnboundLambda(Syntax, data, WithDependencies, _nullableState, HasErrors); data.SetUnboundLambda(lambda); return lambda; } public MessageID MessageID { get { return Data.MessageID; } } public NamedTypeSymbol? InferDelegateType(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) => Data.InferDelegateType(ref useSiteInfo); public BoundLambda Bind(NamedTypeSymbol delegateType, bool isExpressionTree) => SuppressIfNeeded(Data.Bind(delegateType, isExpressionTree)); public BoundLambda BindForErrorRecovery() => SuppressIfNeeded(Data.BindForErrorRecovery()); public BoundLambda BindForReturnTypeInference(NamedTypeSymbol delegateType) => SuppressIfNeeded(Data.BindForReturnTypeInference(delegateType)); private BoundLambda SuppressIfNeeded(BoundLambda lambda) => this.IsSuppressed ? (BoundLambda)lambda.WithSuppression() : lambda; public bool HasSignature { get { return Data.HasSignature; } } public bool HasExplicitReturnType(out RefKind refKind, out TypeWithAnnotations returnType) => Data.HasExplicitReturnType(out refKind, out returnType); public bool HasExplicitlyTypedParameterList { get { return Data.HasExplicitlyTypedParameterList; } } public int ParameterCount { get { return Data.ParameterCount; } } public TypeWithAnnotations InferReturnType(ConversionsBase conversions, NamedTypeSymbol delegateType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) => BindForReturnTypeInference(delegateType).GetInferredReturnType(conversions, _nullableState, ref useSiteInfo); public RefKind RefKind(int index) { return Data.RefKind(index); } public void GenerateAnonymousFunctionConversionError(BindingDiagnosticBag diagnostics, TypeSymbol targetType) { Data.GenerateAnonymousFunctionConversionError(diagnostics, targetType); } public bool GenerateSummaryErrors(BindingDiagnosticBag diagnostics) { return Data.GenerateSummaryErrors(diagnostics); } public bool IsAsync { get { return Data.IsAsync; } } public bool IsStatic => Data.IsStatic; public SyntaxList<AttributeListSyntax> ParameterAttributes(int index) { return Data.ParameterAttributes(index); } public TypeWithAnnotations ParameterTypeWithAnnotations(int index) { return Data.ParameterTypeWithAnnotations(index); } public TypeSymbol ParameterType(int index) { return ParameterTypeWithAnnotations(index).Type; } public Location ParameterLocation(int index) { return Data.ParameterLocation(index); } public string ParameterName(int index) { return Data.ParameterName(index); } public bool ParameterIsDiscard(int index) { return Data.ParameterIsDiscard(index); } } internal abstract class UnboundLambdaState { private UnboundLambda _unboundLambda = null!; // we would prefer this readonly, but we have an initialization cycle. internal readonly Binder Binder; [PerformanceSensitive( "https://github.com/dotnet/roslyn/issues/23582", Constraint = "Avoid " + nameof(ConcurrentDictionary<(NamedTypeSymbol, bool), BoundLambda>) + " which has a large default size, but this cache is normally small.")] private ImmutableDictionary<(NamedTypeSymbol Type, bool IsExpressionLambda), BoundLambda>? _bindingCache; [PerformanceSensitive( "https://github.com/dotnet/roslyn/issues/23582", Constraint = "Avoid " + nameof(ConcurrentDictionary<ReturnInferenceCacheKey, BoundLambda>) + " which has a large default size, but this cache is normally small.")] private ImmutableDictionary<ReturnInferenceCacheKey, BoundLambda>? _returnInferenceCache; private BoundLambda? _errorBinding; public UnboundLambdaState(Binder binder, bool includeCache) { Debug.Assert(binder != null); Debug.Assert(binder.ContainingMemberOrLambda != null); if (includeCache) { _bindingCache = ImmutableDictionary<(NamedTypeSymbol Type, bool IsExpressionLambda), BoundLambda>.Empty.WithComparers(BindingCacheComparer.Instance); _returnInferenceCache = ImmutableDictionary<ReturnInferenceCacheKey, BoundLambda>.Empty; } this.Binder = binder; } public void SetUnboundLambda(UnboundLambda unbound) { Debug.Assert(unbound != null); Debug.Assert(_unboundLambda == null || (object)_unboundLambda == unbound); _unboundLambda = unbound; } protected abstract UnboundLambdaState WithCachingCore(bool includeCache); internal UnboundLambdaState WithCaching(bool includeCache) { if ((_bindingCache == null) != includeCache) { return this; } var state = WithCachingCore(includeCache); Debug.Assert((state._bindingCache == null) != includeCache); return state; } public UnboundLambda UnboundLambda => _unboundLambda; public abstract MessageID MessageID { get; } public abstract string ParameterName(int index); public abstract bool ParameterIsDiscard(int index); public abstract SyntaxList<AttributeListSyntax> ParameterAttributes(int index); public abstract bool HasSignature { get; } public abstract bool HasExplicitReturnType(out RefKind refKind, out TypeWithAnnotations returnType); public abstract bool HasExplicitlyTypedParameterList { get; } public abstract int ParameterCount { get; } public abstract bool IsAsync { get; } public abstract bool HasNames { get; } public abstract bool IsStatic { get; } public abstract Location ParameterLocation(int index); public abstract TypeWithAnnotations ParameterTypeWithAnnotations(int index); public abstract RefKind RefKind(int index); protected abstract BoundBlock BindLambdaBody(LambdaSymbol lambdaSymbol, Binder lambdaBodyBinder, BindingDiagnosticBag diagnostics); /// <summary> /// Return the bound expression if the lambda has an expression body and can be reused easily. /// This is an optimization only. Implementations can return null to skip reuse. /// </summary> protected abstract BoundExpression? GetLambdaExpressionBody(BoundBlock body); /// <summary> /// Produce a bound block for the expression returned from GetLambdaExpressionBody. /// </summary> protected abstract BoundBlock CreateBlockFromLambdaExpressionBody(Binder lambdaBodyBinder, BoundExpression expression, BindingDiagnosticBag diagnostics); public virtual void GenerateAnonymousFunctionConversionError(BindingDiagnosticBag diagnostics, TypeSymbol targetType) { this.Binder.GenerateAnonymousFunctionConversionError(diagnostics, _unboundLambda.Syntax, _unboundLambda, targetType); } // Returns the inferred return type, or null if none can be inferred. public BoundLambda Bind(NamedTypeSymbol delegateType, bool isTargetExpressionTree) { bool inExpressionTree = Binder.InExpressionTree || isTargetExpressionTree; if (!_bindingCache!.TryGetValue((delegateType, inExpressionTree), out BoundLambda? result)) { result = ReallyBind(delegateType, inExpressionTree); result = ImmutableInterlocked.GetOrAdd(ref _bindingCache, (delegateType, inExpressionTree), result); } return result; } internal IEnumerable<TypeSymbol> InferredReturnTypes() { bool any = false; foreach (var lambda in _returnInferenceCache!.Values) { var type = lambda.InferredReturnType.TypeWithAnnotations; if (type.HasType) { any = true; yield return type.Type; } } if (!any) { var type = BindForErrorRecovery().InferredReturnType.TypeWithAnnotations; if (type.HasType) { yield return type.Type; } } } private static MethodSymbol? DelegateInvokeMethod(NamedTypeSymbol? delegateType) { return delegateType.GetDelegateType()?.DelegateInvokeMethod; } private static TypeWithAnnotations DelegateReturnTypeWithAnnotations(MethodSymbol? invokeMethod, out RefKind refKind) { if (invokeMethod is null) { refKind = CodeAnalysis.RefKind.None; return default; } refKind = invokeMethod.RefKind; return invokeMethod.ReturnTypeWithAnnotations; } internal NamedTypeSymbol? InferDelegateType(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(Binder.ContainingMemberOrLambda is { }); if (!HasExplicitlyTypedParameterList) { return null; } var parameterRefKindsBuilder = ArrayBuilder<RefKind>.GetInstance(ParameterCount); var parameterTypesBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(ParameterCount); for (int i = 0; i < ParameterCount; i++) { parameterRefKindsBuilder.Add(RefKind(i)); parameterTypesBuilder.Add(ParameterTypeWithAnnotations(i)); } var parameterRefKinds = parameterRefKindsBuilder.ToImmutableAndFree(); var parameterTypes = parameterTypesBuilder.ToImmutableAndFree(); if (!HasExplicitReturnType(out var returnRefKind, out var returnType)) { var lambdaSymbol = new LambdaSymbol( Binder, Binder.Compilation, Binder.ContainingMemberOrLambda, _unboundLambda, parameterTypes, parameterRefKinds, refKind: default, returnType: default); var lambdaBodyBinder = new ExecutableCodeBinder(_unboundLambda.Syntax, lambdaSymbol, ParameterBinder(lambdaSymbol, Binder)); var block = BindLambdaBody(lambdaSymbol, lambdaBodyBinder, BindingDiagnosticBag.Discarded); var returnTypes = ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>.GetInstance(); BoundLambda.BlockReturns.GetReturnTypes(returnTypes, block); var inferredReturnType = BoundLambda.InferReturnType( returnTypes, _unboundLambda, lambdaBodyBinder, delegateType: null, isAsync: IsAsync, Binder.Conversions); returnType = inferredReturnType.TypeWithAnnotations; returnRefKind = inferredReturnType.RefKind; if (!returnType.HasType && returnTypes.Count > 0) { return null; } } return Binder.GetMethodGroupOrLambdaDelegateType( returnRefKind, returnType.Type?.IsVoidType() == true ? default : returnType, parameterRefKinds, parameterTypes, ref useSiteInfo); } private BoundLambda ReallyBind(NamedTypeSymbol delegateType, bool inExpressionTree) { Debug.Assert(Binder.ContainingMemberOrLambda is { }); var invokeMethod = DelegateInvokeMethod(delegateType); var returnType = DelegateReturnTypeWithAnnotations(invokeMethod, out RefKind refKind); LambdaSymbol lambdaSymbol; Binder lambdaBodyBinder; BoundBlock block; var diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, _unboundLambda.WithDependencies); var compilation = Binder.Compilation; var cacheKey = ReturnInferenceCacheKey.Create(delegateType, IsAsync); // When binding for real (not for return inference), there is still a good chance // we could reuse a body of a lambda previous bound for return type inference. // For simplicity, reuse is limited to expression-bodied lambdas. In those cases, // we reuse the bound expression and apply any conversion to the return value // since the inferred return type was not used when binding for return inference. // We don't reuse the body if we're binding in an expression tree, because we didn't // know that we were binding for an expression tree when originally binding the lambda // for return inference. if (!inExpressionTree && refKind == CodeAnalysis.RefKind.None && _returnInferenceCache!.TryGetValue(cacheKey, out BoundLambda? returnInferenceLambda) && GetLambdaExpressionBody(returnInferenceLambda.Body) is BoundExpression expression && (lambdaSymbol = returnInferenceLambda.Symbol).RefKind == refKind && (object)LambdaSymbol.InferenceFailureReturnType != lambdaSymbol.ReturnType && lambdaSymbol.ReturnTypeWithAnnotations.Equals(returnType, TypeCompareKind.ConsiderEverything)) { lambdaBodyBinder = returnInferenceLambda.Binder; block = CreateBlockFromLambdaExpressionBody(lambdaBodyBinder, expression, diagnostics); diagnostics.AddRange(returnInferenceLambda.Diagnostics); } else { lambdaSymbol = CreateLambdaSymbol(Binder.ContainingMemberOrLambda, returnType, cacheKey.ParameterTypes, cacheKey.ParameterRefKinds, refKind); lambdaBodyBinder = new ExecutableCodeBinder(_unboundLambda.Syntax, lambdaSymbol, ParameterBinder(lambdaSymbol, Binder), inExpressionTree ? BinderFlags.InExpressionTree : BinderFlags.None); block = BindLambdaBody(lambdaSymbol, lambdaBodyBinder, diagnostics); } lambdaSymbol.GetDeclarationDiagnostics(diagnostics); if (lambdaSymbol.RefKind == CodeAnalysis.RefKind.RefReadOnly) { compilation.EnsureIsReadOnlyAttributeExists(diagnostics, lambdaSymbol.DiagnosticLocation, modifyCompilation: false); } var lambdaParameters = lambdaSymbol.Parameters; ParameterHelpers.EnsureIsReadOnlyAttributeExists(compilation, lambdaParameters, diagnostics, modifyCompilation: false); if (returnType.HasType) { if (returnType.Type.ContainsNativeInteger()) { compilation.EnsureNativeIntegerAttributeExists(diagnostics, lambdaSymbol.DiagnosticLocation, modifyCompilation: false); } if (compilation.ShouldEmitNullableAttributes(lambdaSymbol) && returnType.NeedsNullableAttribute()) { compilation.EnsureNullableAttributeExists(diagnostics, lambdaSymbol.DiagnosticLocation, modifyCompilation: false); // Note: we don't need to warn on annotations used in #nullable disable context for lambdas, as this is handled in binding already } } ParameterHelpers.EnsureNativeIntegerAttributeExists(compilation, lambdaParameters, diagnostics, modifyCompilation: false); ParameterHelpers.EnsureNullableAttributeExists(compilation, lambdaSymbol, lambdaParameters, diagnostics, modifyCompilation: false); // Note: we don't need to warn on annotations used in #nullable disable context for lambdas, as this is handled in binding already ValidateUnsafeParameters(diagnostics, cacheKey.ParameterTypes); bool reachableEndpoint = ControlFlowPass.Analyze(compilation, lambdaSymbol, block, diagnostics.DiagnosticBag); if (reachableEndpoint) { if (Binder.MethodOrLambdaRequiresValue(lambdaSymbol, this.Binder.Compilation)) { // Not all code paths return a value in {0} of type '{1}' diagnostics.Add(ErrorCode.ERR_AnonymousReturnExpected, lambdaSymbol.DiagnosticLocation, this.MessageID.Localize(), delegateType); } else { block = FlowAnalysisPass.AppendImplicitReturn(block, lambdaSymbol); } } if (IsAsync && !ErrorFacts.PreventsSuccessfulDelegateConversion(diagnostics.DiagnosticBag)) { if (returnType.HasType && // Can be null if "delegateType" is not actually a delegate type. !returnType.IsVoidType() && !lambdaSymbol.IsAsyncEffectivelyReturningTask(compilation) && !lambdaSymbol.IsAsyncEffectivelyReturningGenericTask(compilation)) { // 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}'. diagnostics.Add(ErrorCode.ERR_CantConvAsyncAnonFuncReturns, lambdaSymbol.DiagnosticLocation, lambdaSymbol.MessageID.Localize(), delegateType); } } var result = new BoundLambda(_unboundLambda.Syntax, _unboundLambda, block, diagnostics.ToReadOnlyAndFree(), lambdaBodyBinder, delegateType, inferredReturnType: default) { WasCompilerGenerated = _unboundLambda.WasCompilerGenerated }; return result; } internal LambdaSymbol CreateLambdaSymbol( Symbol containingSymbol, TypeWithAnnotations returnType, ImmutableArray<TypeWithAnnotations> parameterTypes, ImmutableArray<RefKind> parameterRefKinds, RefKind refKind) => new LambdaSymbol( Binder, Binder.Compilation, containingSymbol, _unboundLambda, parameterTypes, parameterRefKinds, refKind, returnType); internal LambdaSymbol CreateLambdaSymbol(NamedTypeSymbol delegateType, Symbol containingSymbol) { var invokeMethod = DelegateInvokeMethod(delegateType); var returnType = DelegateReturnTypeWithAnnotations(invokeMethod, out RefKind refKind); ReturnInferenceCacheKey.GetFields(delegateType, IsAsync, out var parameterTypes, out var parameterRefKinds, out _); return CreateLambdaSymbol(containingSymbol, returnType, parameterTypes, parameterRefKinds, refKind); } private void ValidateUnsafeParameters(BindingDiagnosticBag diagnostics, ImmutableArray<TypeWithAnnotations> targetParameterTypes) { // It is legal to use a delegate type that has unsafe parameter types inside // a safe context if the anonymous method has no parameter list! // // unsafe delegate void D(int* p); // class C { D d = delegate {}; } // // is legal even if C is not an unsafe context because no int* is actually used. if (this.HasSignature) { // NOTE: we can get here with targetParameterTypes.Length > ParameterCount // in a case where we are binding for error reporting purposes var numParametersToCheck = Math.Min(targetParameterTypes.Length, ParameterCount); for (int i = 0; i < numParametersToCheck; i++) { if (targetParameterTypes[i].Type.IsUnsafe()) { this.Binder.ReportUnsafeIfNotAllowed(this.ParameterLocation(i), diagnostics); } } } } private BoundLambda ReallyInferReturnType( NamedTypeSymbol? delegateType, ImmutableArray<TypeWithAnnotations> parameterTypes, ImmutableArray<RefKind> parameterRefKinds) { bool hasExplicitReturnType = HasExplicitReturnType(out var refKind, out var returnType); (var lambdaSymbol, var block, var lambdaBodyBinder, var diagnostics) = BindWithParameterAndReturnType(parameterTypes, parameterRefKinds, returnType, refKind); InferredLambdaReturnType inferredReturnType; if (hasExplicitReturnType) { // The InferredLambdaReturnType fields other than RefKind and ReturnType // are only used when actually inferring a type, not when the type is explicit. inferredReturnType = new InferredLambdaReturnType( numExpressions: 0, isExplicitType: true, hadExpressionlessReturn: false, refKind, returnType, ImmutableArray<DiagnosticInfo>.Empty, ImmutableArray<AssemblySymbol>.Empty); } else { var returnTypes = ArrayBuilder<(BoundReturnStatement, TypeWithAnnotations)>.GetInstance(); BoundLambda.BlockReturns.GetReturnTypes(returnTypes, block); inferredReturnType = BoundLambda.InferReturnType(returnTypes, _unboundLambda, lambdaBodyBinder, delegateType, lambdaSymbol.IsAsync, lambdaBodyBinder.Conversions); // TODO: Should InferredReturnType.UseSiteDiagnostics be merged into BoundLambda.Diagnostics? refKind = inferredReturnType.RefKind; returnType = inferredReturnType.TypeWithAnnotations; if (!returnType.HasType) { bool forErrorRecovery = delegateType is null; returnType = (forErrorRecovery && returnTypes.Count == 0) ? TypeWithAnnotations.Create(this.Binder.Compilation.GetSpecialType(SpecialType.System_Void)) : TypeWithAnnotations.Create(LambdaSymbol.InferenceFailureReturnType); } returnTypes.Free(); } var result = new BoundLambda( _unboundLambda.Syntax, _unboundLambda, block, diagnostics.ToReadOnlyAndFree(), lambdaBodyBinder, delegateType, inferredReturnType) { WasCompilerGenerated = _unboundLambda.WasCompilerGenerated }; if (!hasExplicitReturnType) { lambdaSymbol.SetInferredReturnType(refKind, returnType); } return result; } private (LambdaSymbol lambdaSymbol, BoundBlock block, ExecutableCodeBinder lambdaBodyBinder, BindingDiagnosticBag diagnostics) BindWithParameterAndReturnType( ImmutableArray<TypeWithAnnotations> parameterTypes, ImmutableArray<RefKind> parameterRefKinds, TypeWithAnnotations returnType, RefKind refKind) { var diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: true, _unboundLambda.WithDependencies); var lambdaSymbol = CreateLambdaSymbol(Binder.ContainingMemberOrLambda!, returnType, parameterTypes, parameterRefKinds, refKind); var lambdaBodyBinder = new ExecutableCodeBinder(_unboundLambda.Syntax, lambdaSymbol, ParameterBinder(lambdaSymbol, Binder)); var block = BindLambdaBody(lambdaSymbol, lambdaBodyBinder, diagnostics); lambdaSymbol.GetDeclarationDiagnostics(diagnostics); return (lambdaSymbol, block, lambdaBodyBinder, diagnostics); } public BoundLambda BindForReturnTypeInference(NamedTypeSymbol delegateType) { var cacheKey = ReturnInferenceCacheKey.Create(delegateType, IsAsync); BoundLambda? result; if (!_returnInferenceCache!.TryGetValue(cacheKey, out result)) { result = ReallyInferReturnType(delegateType, cacheKey.ParameterTypes, cacheKey.ParameterRefKinds); result = ImmutableInterlocked.GetOrAdd(ref _returnInferenceCache, cacheKey, result); } return result; } /// <summary> /// Behavior of this key should be kept aligned with <see cref="BoundLambda.InferReturnTypeImpl"/>. /// </summary> private sealed class ReturnInferenceCacheKey { public readonly ImmutableArray<TypeWithAnnotations> ParameterTypes; public readonly ImmutableArray<RefKind> ParameterRefKinds; public readonly NamedTypeSymbol? TaskLikeReturnTypeOpt; public static readonly ReturnInferenceCacheKey Empty = new ReturnInferenceCacheKey(ImmutableArray<TypeWithAnnotations>.Empty, ImmutableArray<RefKind>.Empty, null); private ReturnInferenceCacheKey(ImmutableArray<TypeWithAnnotations> parameterTypes, ImmutableArray<RefKind> parameterRefKinds, NamedTypeSymbol? taskLikeReturnTypeOpt) { Debug.Assert(parameterTypes.Length == parameterRefKinds.Length); Debug.Assert(taskLikeReturnTypeOpt is null || ((object)taskLikeReturnTypeOpt == taskLikeReturnTypeOpt.ConstructedFrom && taskLikeReturnTypeOpt.IsCustomTaskType(out var builderArgument))); this.ParameterTypes = parameterTypes; this.ParameterRefKinds = parameterRefKinds; this.TaskLikeReturnTypeOpt = taskLikeReturnTypeOpt; } public override bool Equals(object? obj) { if ((object)this == obj) { return true; } var other = obj as ReturnInferenceCacheKey; if (other is null || other.ParameterTypes.Length != this.ParameterTypes.Length || !TypeSymbol.Equals(other.TaskLikeReturnTypeOpt, this.TaskLikeReturnTypeOpt, TypeCompareKind.ConsiderEverything2)) { return false; } for (int i = 0; i < this.ParameterTypes.Length; i++) { if (!other.ParameterTypes[i].Equals(this.ParameterTypes[i], TypeCompareKind.ConsiderEverything) || other.ParameterRefKinds[i] != this.ParameterRefKinds[i]) { return false; } } return true; } public override int GetHashCode() { var value = TaskLikeReturnTypeOpt?.GetHashCode() ?? 0; foreach (var type in ParameterTypes) { value = Hash.Combine(type.Type, value); } return value; } public static ReturnInferenceCacheKey Create(NamedTypeSymbol? delegateType, bool isAsync) { GetFields(delegateType, isAsync, out var parameterTypes, out var parameterRefKinds, out var taskLikeReturnTypeOpt); if (parameterTypes.IsEmpty && parameterRefKinds.IsEmpty && taskLikeReturnTypeOpt is null) { return Empty; } return new ReturnInferenceCacheKey(parameterTypes, parameterRefKinds, taskLikeReturnTypeOpt); } public static void GetFields( NamedTypeSymbol? delegateType, bool isAsync, out ImmutableArray<TypeWithAnnotations> parameterTypes, out ImmutableArray<RefKind> parameterRefKinds, out NamedTypeSymbol? taskLikeReturnTypeOpt) { // delegateType or DelegateInvokeMethod can be null in cases of malformed delegates // in such case we would want something trivial with no parameters parameterTypes = ImmutableArray<TypeWithAnnotations>.Empty; parameterRefKinds = ImmutableArray<RefKind>.Empty; taskLikeReturnTypeOpt = null; MethodSymbol? invoke = DelegateInvokeMethod(delegateType); if (invoke is not null) { int parameterCount = invoke.ParameterCount; if (parameterCount > 0) { var typesBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(parameterCount); var refKindsBuilder = ArrayBuilder<RefKind>.GetInstance(parameterCount); foreach (var p in invoke.Parameters) { refKindsBuilder.Add(p.RefKind); typesBuilder.Add(p.TypeWithAnnotations); } parameterTypes = typesBuilder.ToImmutableAndFree(); parameterRefKinds = refKindsBuilder.ToImmutableAndFree(); } if (isAsync) { var delegateReturnType = invoke.ReturnType as NamedTypeSymbol; if (delegateReturnType?.IsVoidType() == false) { if (delegateReturnType.IsCustomTaskType(out var builderType)) { taskLikeReturnTypeOpt = delegateReturnType.ConstructedFrom; } } } } } } public virtual Binder ParameterBinder(LambdaSymbol lambdaSymbol, Binder binder) { return new WithLambdaParametersBinder(lambdaSymbol, binder); } // UNDONE: [MattWar] // UNDONE: Here we enable the consumer of an unbound lambda that could not be // UNDONE: successfully converted to a best bound lambda to do error recovery // UNDONE: by either picking an existing binding, or by binding the body using // UNDONE: error types for parameter types as necessary. This is not exactly // UNDONE: the strategy we discussed in the design meeting; rather there we // UNDONE: decided to do this more the way we did it in the native compiler: // UNDONE: there we wrote a post-processing pass that searched the tree for // UNDONE: unbound lambdas and did this sort of replacement on them, so that // UNDONE: we never observed an unbound lambda in the tree. // UNDONE: // UNDONE: I think that is a reasonable approach but it is not implemented yet. // UNDONE: When we figure out precisely where that rewriting pass should go, // UNDONE: we can use the gear implemented in this method as an implementation // UNDONE: detail of it. // UNDONE: // UNDONE: Note: that rewriting can now be done in BindToTypeForErrorRecovery. public BoundLambda BindForErrorRecovery() { // It is possible that either (1) we never did a binding, because // we've got code like "var x = (z)=>{int y = 123; M(y, z);};" or // (2) we did a bunch of bindings but none of them turned out to // be the one we wanted. In such a situation we still want // IntelliSense to work on y in the body of the lambda, and // possibly to make a good guess as to what M means even if we // don't know the type of z. if (_errorBinding == null) { Interlocked.CompareExchange(ref _errorBinding, ReallyBindForErrorRecovery(), null); } return _errorBinding; } private BoundLambda ReallyBindForErrorRecovery() { // If we have bindings, we can use heuristics to choose one. // If not, we can assign error types to all the parameters // and bind. return GuessBestBoundLambda(_bindingCache!) ?? rebind(GuessBestBoundLambda(_returnInferenceCache!)) ?? rebind(ReallyInferReturnType(delegateType: null, ImmutableArray<TypeWithAnnotations>.Empty, ImmutableArray<RefKind>.Empty)); // Rebind a lambda to push target conversions through the return/result expressions [return: NotNullIfNotNull("lambda")] BoundLambda? rebind(BoundLambda? lambda) { if (lambda is null) return null; var delegateType = (NamedTypeSymbol?)lambda.Type; ReturnInferenceCacheKey.GetFields(delegateType, IsAsync, out var parameterTypes, out var parameterRefKinds, out _); return ReallyBindForErrorRecovery(delegateType, lambda.InferredReturnType, parameterTypes, parameterRefKinds); } } private BoundLambda ReallyBindForErrorRecovery( NamedTypeSymbol? delegateType, InferredLambdaReturnType inferredReturnType, ImmutableArray<TypeWithAnnotations> parameterTypes, ImmutableArray<RefKind> parameterRefKinds) { var returnType = inferredReturnType.TypeWithAnnotations; var refKind = inferredReturnType.RefKind; if (!returnType.HasType) { Debug.Assert(!inferredReturnType.IsExplicitType); var invokeMethod = DelegateInvokeMethod(delegateType); returnType = DelegateReturnTypeWithAnnotations(invokeMethod, out refKind); if (!returnType.HasType || returnType.Type.ContainsTypeParameter()) { var t = (inferredReturnType.HadExpressionlessReturn || inferredReturnType.NumExpressions == 0) ? this.Binder.Compilation.GetSpecialType(SpecialType.System_Void) : this.Binder.CreateErrorType(); returnType = TypeWithAnnotations.Create(t); refKind = CodeAnalysis.RefKind.None; } } (var lambdaSymbol, var block, var lambdaBodyBinder, var diagnostics) = BindWithParameterAndReturnType(parameterTypes, parameterRefKinds, returnType, refKind); return new BoundLambda( _unboundLambda.Syntax, _unboundLambda, block, diagnostics.ToReadOnlyAndFree(), lambdaBodyBinder, delegateType, new InferredLambdaReturnType(inferredReturnType.NumExpressions, isExplicitType: inferredReturnType.IsExplicitType, inferredReturnType.HadExpressionlessReturn, refKind, returnType, ImmutableArray<DiagnosticInfo>.Empty, ImmutableArray<AssemblySymbol>.Empty)) { WasCompilerGenerated = _unboundLambda.WasCompilerGenerated }; } private static BoundLambda? GuessBestBoundLambda<T>(ImmutableDictionary<T, BoundLambda> candidates) where T : notnull { switch (candidates.Count) { case 0: return null; case 1: return candidates.First().Value; default: // Prefer candidates with fewer diagnostics. IEnumerable<KeyValuePair<T, BoundLambda>> minDiagnosticsGroup = candidates.GroupBy(lambda => lambda.Value.Diagnostics.Diagnostics.Length).OrderBy(group => group.Key).First(); // If multiple candidates have the same number of diagnostics, order them by delegate type name. // It's not great, but it should be stable. return minDiagnosticsGroup .OrderBy(lambda => GetLambdaSortString(lambda.Value.Symbol)) .FirstOrDefault() .Value; } } private static string GetLambdaSortString(LambdaSymbol lambda) { var builder = PooledStringBuilder.GetInstance(); foreach (var parameter in lambda.Parameters) { builder.Builder.Append(parameter.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat)); } if (lambda.ReturnTypeWithAnnotations.HasType) { builder.Builder.Append(lambda.ReturnTypeWithAnnotations.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)); } var result = builder.ToStringAndFree(); return result; } public bool GenerateSummaryErrors(BindingDiagnosticBag diagnostics) { // It is highly likely that "the same" error will be given for two different // bindings of the same lambda but with different values for the parameters // of the error. For example, if we have x=>x.Blah() where x could be int // or string, then the two errors will be "int does not have member Blah" and // "string does not have member Blah", but the locations and errors numbers // will be the same. // // We should first see if there is a set of errors that are "the same" by // this definition that occur in every lambda binding; if there are then // those are the errors we should report. // // If there are no errors that are common to *every* binding then we // can report the complete set of errors produced by every binding. However, // we still wish to avoid duplicates, so we will use the same logic for // building the union as the intersection; two errors with the same code // and location are to be treated as the same error and only reported once, // regardless of how that error is parameterized. // // The question then rears its head: when given two of "the same" error // to report that are nevertheless different in their arguments, which one // do we choose? To the user it hardly matters; either one points to the // right location in source code. But it surely matters to our testing team; // we do not want to be in a position where some small change to our internal // representation of lambdas causes tests to break because errors are reported // differently. // // What we need to do is find a *repeatable* arbitrary way to choose between // two errors; we can for example simply take the one that is lower in alphabetical // order when converted to a string. var convBags = from boundLambda in _bindingCache select boundLambda.Value.Diagnostics; var retBags = from boundLambda in _returnInferenceCache!.Values select boundLambda.Diagnostics; var allBags = convBags.Concat(retBags); FirstAmongEqualsSet<Diagnostic>? intersection = null; foreach (ImmutableBindingDiagnostic<AssemblySymbol> bag in allBags) { if (intersection == null) { intersection = CreateFirstAmongEqualsSet(bag.Diagnostics); } else { intersection.IntersectWith(bag.Diagnostics); } } if (intersection != null) { if (PreventsSuccessfulDelegateConversion(intersection)) { diagnostics.AddRange(intersection); return true; } } FirstAmongEqualsSet<Diagnostic>? union = null; foreach (ImmutableBindingDiagnostic<AssemblySymbol> bag in allBags) { if (union == null) { union = CreateFirstAmongEqualsSet(bag.Diagnostics); } else { union.UnionWith(bag.Diagnostics); } } if (union != null) { if (PreventsSuccessfulDelegateConversion(union)) { diagnostics.AddRange(union); return true; } } return false; } private static bool PreventsSuccessfulDelegateConversion(FirstAmongEqualsSet<Diagnostic> set) { foreach (var diagnostic in set) { if (ErrorFacts.PreventsSuccessfulDelegateConversion((ErrorCode)diagnostic.Code)) { return true; } } return false; } private static FirstAmongEqualsSet<Diagnostic> CreateFirstAmongEqualsSet(ImmutableArray<Diagnostic> bag) { // For the purposes of lambda error reporting we wish to compare // diagnostics for equality only considering their code and location, // but not other factors such as the values supplied for the // parameters of the diagnostic. return new FirstAmongEqualsSet<Diagnostic>( bag, CommonDiagnosticComparer.Instance, CanonicallyCompareDiagnostics); } /// <summary> /// What we need to do is find a *repeatable* arbitrary way to choose between /// two errors; we can for example simply take the one whose arguments are lower in alphabetical /// order when converted to a string. As an optimization, we compare error codes /// first and skip string comparison if they differ. /// </summary> private static int CanonicallyCompareDiagnostics(Diagnostic x, Diagnostic y) { // Optimization: don't bother if (x.Code != y.Code) return x.Code - y.Code; var nx = x.Arguments?.Count ?? 0; var ny = y.Arguments?.Count ?? 0; for (int i = 0, n = Math.Min(nx, ny); i < n; i++) { object? argx = x.Arguments![i]; object? argy = y.Arguments![i]; int argCompare = string.CompareOrdinal(argx?.ToString(), argy?.ToString()); if (argCompare != 0) return argCompare; } return nx - ny; } private sealed class BindingCacheComparer : IEqualityComparer<(NamedTypeSymbol Type, bool IsExpressionTree)> { public static readonly BindingCacheComparer Instance = new BindingCacheComparer(); public bool Equals([AllowNull] (NamedTypeSymbol Type, bool IsExpressionTree) x, [AllowNull] (NamedTypeSymbol Type, bool IsExpressionTree) y) => x.IsExpressionTree == y.IsExpressionTree && Symbol.Equals(x.Type, y.Type, TypeCompareKind.ConsiderEverything); public int GetHashCode([DisallowNull] (NamedTypeSymbol Type, bool IsExpressionTree) obj) => Hash.Combine(obj.Type, obj.IsExpressionTree.GetHashCode()); } } internal sealed class PlainUnboundLambdaState : UnboundLambdaState { private readonly RefKind _returnRefKind; private readonly TypeWithAnnotations _returnType; private readonly ImmutableArray<SyntaxList<AttributeListSyntax>> _parameterAttributes; private readonly ImmutableArray<string> _parameterNames; private readonly ImmutableArray<bool> _parameterIsDiscardOpt; private readonly ImmutableArray<TypeWithAnnotations> _parameterTypesWithAnnotations; private readonly ImmutableArray<RefKind> _parameterRefKinds; private readonly bool _isAsync; private readonly bool _isStatic; internal PlainUnboundLambdaState( Binder binder, RefKind returnRefKind, TypeWithAnnotations returnType, ImmutableArray<SyntaxList<AttributeListSyntax>> parameterAttributes, ImmutableArray<string> parameterNames, ImmutableArray<bool> parameterIsDiscardOpt, ImmutableArray<TypeWithAnnotations> parameterTypesWithAnnotations, ImmutableArray<RefKind> parameterRefKinds, bool isAsync, bool isStatic, bool includeCache) : base(binder, includeCache) { _returnRefKind = returnRefKind; _returnType = returnType; _parameterAttributes = parameterAttributes; _parameterNames = parameterNames; _parameterIsDiscardOpt = parameterIsDiscardOpt; _parameterTypesWithAnnotations = parameterTypesWithAnnotations; _parameterRefKinds = parameterRefKinds; _isAsync = isAsync; _isStatic = isStatic; } public override bool HasNames { get { return !_parameterNames.IsDefault; } } public override bool HasSignature { get { return !_parameterNames.IsDefault; } } public override bool HasExplicitReturnType(out RefKind refKind, out TypeWithAnnotations returnType) { refKind = _returnRefKind; returnType = _returnType; return _returnType.HasType; } public override bool HasExplicitlyTypedParameterList { get { return !_parameterTypesWithAnnotations.IsDefault; } } public override int ParameterCount { get { return _parameterNames.IsDefault ? 0 : _parameterNames.Length; } } public override bool IsAsync { get { return _isAsync; } } public override bool IsStatic => _isStatic; public override MessageID MessageID { get { return this.UnboundLambda.Syntax.Kind() == SyntaxKind.AnonymousMethodExpression ? MessageID.IDS_AnonMethod : MessageID.IDS_Lambda; } } private CSharpSyntaxNode Body { get { return UnboundLambda.Syntax.AnonymousFunctionBody(); } } public override Location ParameterLocation(int index) { Debug.Assert(HasSignature && 0 <= index && index < ParameterCount); var syntax = UnboundLambda.Syntax; switch (syntax.Kind()) { default: case SyntaxKind.SimpleLambdaExpression: return ((SimpleLambdaExpressionSyntax)syntax).Parameter.Identifier.GetLocation(); case SyntaxKind.ParenthesizedLambdaExpression: return ((ParenthesizedLambdaExpressionSyntax)syntax).ParameterList.Parameters[index].Identifier.GetLocation(); case SyntaxKind.AnonymousMethodExpression: return ((AnonymousMethodExpressionSyntax)syntax).ParameterList!.Parameters[index].Identifier.GetLocation(); } } private bool IsExpressionLambda { get { return Body.Kind() != SyntaxKind.Block; } } public override SyntaxList<AttributeListSyntax> ParameterAttributes(int index) { return _parameterAttributes.IsDefault ? default : _parameterAttributes[index]; } public override string ParameterName(int index) { Debug.Assert(!_parameterNames.IsDefault && 0 <= index && index < _parameterNames.Length); return _parameterNames[index]; } public override bool ParameterIsDiscard(int index) { return _parameterIsDiscardOpt.IsDefault ? false : _parameterIsDiscardOpt[index]; } public override RefKind RefKind(int index) { Debug.Assert(0 <= index && index < _parameterTypesWithAnnotations.Length); return _parameterRefKinds.IsDefault ? Microsoft.CodeAnalysis.RefKind.None : _parameterRefKinds[index]; } public override TypeWithAnnotations ParameterTypeWithAnnotations(int index) { Debug.Assert(this.HasExplicitlyTypedParameterList); Debug.Assert(0 <= index && index < _parameterTypesWithAnnotations.Length); return _parameterTypesWithAnnotations[index]; } protected override UnboundLambdaState WithCachingCore(bool includeCache) { return new PlainUnboundLambdaState(Binder, _returnRefKind, _returnType, _parameterAttributes, _parameterNames, _parameterIsDiscardOpt, _parameterTypesWithAnnotations, _parameterRefKinds, _isAsync, _isStatic, includeCache); } protected override BoundExpression? GetLambdaExpressionBody(BoundBlock body) { if (IsExpressionLambda) { var statements = body.Statements; if (statements.Length == 1 && // To simplify Binder.CreateBlockFromExpression (used below), we only reuse by-value return values. statements[0] is BoundReturnStatement { RefKind: Microsoft.CodeAnalysis.RefKind.None, ExpressionOpt: BoundExpression expr }) { return expr; } } return null; } protected override BoundBlock CreateBlockFromLambdaExpressionBody(Binder lambdaBodyBinder, BoundExpression expression, BindingDiagnosticBag diagnostics) { return lambdaBodyBinder.CreateBlockFromExpression((ExpressionSyntax)this.Body, expression, diagnostics); } protected override BoundBlock BindLambdaBody(LambdaSymbol lambdaSymbol, Binder lambdaBodyBinder, BindingDiagnosticBag diagnostics) { if (this.IsExpressionLambda) { return lambdaBodyBinder.BindLambdaExpressionAsBlock((ExpressionSyntax)this.Body, diagnostics); } else { return lambdaBodyBinder.BindEmbeddedBlock((BlockSyntax)this.Body, diagnostics); } } } }
1
dotnet/roslyn
55,125
Don't use DefaultInterpolatedStringHandler in expression trees
Introduces a binder flag to track whether we are currently in an expression tree or not. Fixes https://github.com/dotnet/roslyn/issues/55114.
333fred
2021-07-26T22:08:39Z
2021-07-27T19:33:24Z
5840335153dcca42570a853cdacd06d660fe9596
cfc12ce93ce377c4b9581ccf88403e6740d63977
Don't use DefaultInterpolatedStringHandler in expression trees. Introduces a binder flag to track whether we are currently in an expression tree or not. Fixes https://github.com/dotnet/roslyn/issues/55114.
./src/Compilers/CSharp/Test/Semantic/Semantics/InterpolationTests.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.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Text; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { public class InterpolationTests : CompilingTestBase { [Fact] public void TestSimpleInterp() { string source = @"using System; class Program { public static void Main(string[] args) { var number = 8675309; Console.WriteLine($""Jenny don\'t change your number { number }.""); Console.WriteLine($""Jenny don\'t change your number { number , -12 }.""); Console.WriteLine($""Jenny don\'t change your number { number , 12 }.""); Console.WriteLine($""Jenny don\'t change your number { number :###-####}.""); Console.WriteLine($""Jenny don\'t change your number { number , -12 :###-####}.""); Console.WriteLine($""Jenny don\'t change your number { number , 12 :###-####}.""); Console.WriteLine($""{number}""); } }"; string expectedOutput = @"Jenny don't change your number 8675309. Jenny don't change your number 8675309 . Jenny don't change your number 8675309. Jenny don't change your number 867-5309. Jenny don't change your number 867-5309 . Jenny don't change your number 867-5309. 8675309"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestOnlyInterp() { string source = @"using System; class Program { public static void Main(string[] args) { var number = 8675309; Console.WriteLine($""{number}""); } }"; string expectedOutput = @"8675309"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestDoubleInterp01() { string source = @"using System; class Program { public static void Main(string[] args) { var number = 8675309; Console.WriteLine($""{number}{number}""); } }"; string expectedOutput = @"86753098675309"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestDoubleInterp02() { string source = @"using System; class Program { public static void Main(string[] args) { var number = 8675309; Console.WriteLine($""Jenny don\'t change your number { number :###-####} { number :###-####}.""); } }"; string expectedOutput = @"Jenny don't change your number 867-5309 867-5309."; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestEmptyInterp() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""Jenny don\'t change your number { /*trash*/ }.""); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,73): error CS1733: Expected expression // Console.WriteLine("Jenny don\'t change your number \{ /*trash*/ }."); Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(5, 73) ); } [Fact] public void TestHalfOpenInterp01() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""Jenny don\'t change your number { ""); } }"; // too many diagnostics perhaps, but it starts the right way. CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,63): error CS1010: Newline in constant // Console.WriteLine($"Jenny don\'t change your number { "); Diagnostic(ErrorCode.ERR_NewlineInConst, "").WithLocation(5, 63), // (5,66): error CS8967: Newlines are not allowed inside a non-verbatim interpolated string // Console.WriteLine($"Jenny don\'t change your number { "); Diagnostic(ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString, "").WithLocation(5, 66), // (6,6): error CS1026: ) expected // } Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(6, 6), // (6,6): error CS1002: ; expected // } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 6), // (7,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2)); } [Fact] public void TestHalfOpenInterp02() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""Jenny don\'t change your number { 8675309 // ""); } }"; // too many diagnostics perhaps, but it starts the right way. CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,71): error CS8077: A single-line comment may not be used in an interpolated string. // Console.WriteLine($"Jenny don\'t change your number { 8675309 // "); Diagnostic(ErrorCode.ERR_SingleLineCommentInExpressionHole, "//").WithLocation(5, 71), // (6,6): error CS1026: ) expected // } Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(6, 6), // (6,6): error CS1002: ; expected // } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 6), // (7,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2)); } [Fact] public void TestHalfOpenInterp03() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""Jenny don\'t change your number { 8675309 /* ""); } }"; // too many diagnostics perhaps, but it starts the right way. CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,71): error CS1035: End-of-file found, '*/' expected // Console.WriteLine($"Jenny don\'t change your number { 8675309 /* "); Diagnostic(ErrorCode.ERR_OpenEndedComment, "").WithLocation(5, 71), // (5,77): error CS8967: Newlines are not allowed inside a non-verbatim interpolated string // Console.WriteLine($"Jenny don\'t change your number { 8675309 /* "); Diagnostic(ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString, "").WithLocation(5, 77), // (7,2): error CS1026: ) expected // } Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(7, 2), // (7,2): error CS1002: ; expected // } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 2), // (7,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2), // (7,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2)); } [Fact] public void LambdaInInterp() { string source = @"using System; class Program { static void Main(string[] args) { //Console.WriteLine(""jenny {0:(408) ###-####}"", new object[] { ((Func<int>)(() => { return number; })).Invoke() }); Console.WriteLine($""jenny { ((Func<int>)(() => { return number; })).Invoke() :(408) ###-####}""); } static int number = 8675309; } "; string expectedOutput = @"jenny (408) 867-5309"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OneLiteral() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""Hello"" ); } }"; string expectedOutput = @"Hello"; var verifier = CompileAndVerify(source, expectedOutput: expectedOutput); verifier.VerifyIL("Program.Main", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldstr ""Hello"" IL_0005: call ""void System.Console.WriteLine(string)"" IL_000a: ret } "); } [Fact] public void OneInsert() { string source = @"using System; class Program { static void Main(string[] args) { var hello = $""Hello""; Console.WriteLine( $""{hello}"" ); } }"; string expectedOutput = @"Hello"; var verifier = CompileAndVerify(source, expectedOutput: expectedOutput); verifier.VerifyIL("Program.Main", @" { // Code size 20 (0x14) .maxstack 2 IL_0000: ldstr ""Hello"" IL_0005: dup IL_0006: brtrue.s IL_000e IL_0008: pop IL_0009: ldstr """" IL_000e: call ""void System.Console.WriteLine(string)"" IL_0013: ret } "); } [Fact] public void TwoInserts() { string source = @"using System; class Program { static void Main(string[] args) { var hello = $""Hello""; var world = $""world"" ; Console.WriteLine( $""{hello}, { world }."" ); } }"; string expectedOutput = @"Hello, world."; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TwoInserts02() { string source = @"using System; class Program { static void Main(string[] args) { var hello = $""Hello""; var world = $""world"" ; Console.WriteLine( $@""{ hello }, { world }."" ); } }"; string expectedOutput = @"Hello, world."; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact, WorkItem(306, "https://github.com/dotnet/roslyn/issues/306"), WorkItem(308, "https://github.com/dotnet/roslyn/issues/308")] public void DynamicInterpolation() { string source = @"using System; using System.Linq.Expressions; class Program { static void Main(string[] args) { dynamic nil = null; dynamic a = new string[] {""Hello"", ""world""}; Console.WriteLine($""<{nil}>""); Console.WriteLine($""<{a}>""); } Expression<Func<string>> M(dynamic d) { return () => $""Dynamic: {d}""; } }"; string expectedOutput = @"<> <System.String[]>"; var verifier = CompileAndVerify(source, new[] { CSharpRef }, expectedOutput: expectedOutput).VerifyDiagnostics(); } [Fact] public void UnclosedInterpolation01() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""{"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,31): error CS1010: Newline in constant // Console.WriteLine( $"{" ); Diagnostic(ErrorCode.ERR_NewlineInConst, "").WithLocation(6, 31), // (6,35): error CS8958: Newlines are not allowed inside a non-verbatim interpolated string // Console.WriteLine( $"{" ); Diagnostic(ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString, "").WithLocation(6, 35), // (7,6): error CS1026: ) expected // } Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(7, 6), // (7,6): error CS1002: ; expected // } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 6), // (8,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(8, 2)); } [Fact] public void UnclosedInterpolation02() { string source = @"class Program { static void Main(string[] args) { var x = $"";"; // The precise error messages are not important, but this must be an error. CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,19): error CS1010: Newline in constant // var x = $"; Diagnostic(ErrorCode.ERR_NewlineInConst, ";").WithLocation(5, 19), // (5,20): error CS1002: ; expected // var x = $"; Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(5, 20), // (5,20): error CS1513: } expected // var x = $"; Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 20), // (5,20): error CS1513: } expected // var x = $"; Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 20) ); } [Fact] public void EmptyFormatSpecifier() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""{3:}"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,32): error CS8089: Empty format specifier. // Console.WriteLine( $"{3:}" ); Diagnostic(ErrorCode.ERR_EmptyFormatSpecifier, ":").WithLocation(6, 32) ); } [Fact] public void TrailingSpaceInFormatSpecifier() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""{3:d }"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,32): error CS8088: A format specifier may not contain trailing whitespace. // Console.WriteLine( $"{3:d }" ); Diagnostic(ErrorCode.ERR_TrailingWhitespaceInFormatSpecifier, ":d ").WithLocation(6, 32) ); } [Fact] public void TrailingSpaceInFormatSpecifier02() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $@""{3:d }"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,33): error CS8088: A format specifier may not contain trailing whitespace. // Console.WriteLine( $@"{3:d Diagnostic(ErrorCode.ERR_TrailingWhitespaceInFormatSpecifier, @":d ").WithLocation(6, 33) ); } [Fact] public void MissingInterpolationExpression01() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""{ }"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,32): error CS1733: Expected expression // Console.WriteLine( $"{ }" ); Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(6, 32) ); } [Fact] public void MissingInterpolationExpression02() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $@""{ }"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,33): error CS1733: Expected expression // Console.WriteLine( $@"{ }" ); Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(6, 33) ); } [Fact] public void MissingInterpolationExpression03() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( "; var normal = "$\""; var verbat = "$@\""; // ensure reparsing of interpolated string token is precise in error scenarios (assertions do not fail) Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal + " ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal + "{").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal + "{ ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat + " ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat + "{").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat + "{ ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [Fact] public void MisplacedNewline01() { string source = @"using System; class Program { static void Main(string[] args) { var s = $""{ @"" "" } ""; } }"; // The precise error messages are not important, but this must be an error. Assert.True(SyntaxFactory.ParseSyntaxTree(source).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [Fact] public void MisplacedNewline02() { string source = @"using System; class Program { static void Main(string[] args) { var s = $""{ @"" ""} ""; } }"; // The precise error messages are not important, but this must be an error. Assert.True(SyntaxFactory.ParseSyntaxTree(source).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [Fact] public void PreprocessorInsideInterpolation() { string source = @"class Program { static void Main() { var s = $@""{ #region : #endregion 0 }""; } }"; // The precise error messages are not important, but this must be an error. Assert.True(SyntaxFactory.ParseSyntaxTree(source).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [Fact] public void EscapedCurly() { string source = @"class Program { static void Main() { var s1 = $"" \u007B ""; var s2 = $"" \u007D""; } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,21): error CS8087: A '{' character may only be escaped by doubling '{{' in an interpolated string. // var s1 = $" \u007B "; Diagnostic(ErrorCode.ERR_EscapedCurly, @"\u007B").WithArguments("{").WithLocation(5, 21), // (6,21): error CS8087: A '}' character may only be escaped by doubling '}}' in an interpolated string. // var s2 = $" \u007D"; Diagnostic(ErrorCode.ERR_EscapedCurly, @"\u007D").WithArguments("}").WithLocation(6, 21) ); } [Fact, WorkItem(1119878, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1119878")] public void NoFillIns01() { string source = @"class Program { static void Main() { System.Console.Write($""{{ x }}""); System.Console.WriteLine($@""This is a test""); } }"; string expectedOutput = @"{ x }This is a test"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void BadAlignment() { string source = @"class Program { static void Main() { var s = $""{1,1E10}""; var t = $""{1,(int)1E10}""; } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,22): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // var s = $"{1,1E10}"; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1E10").WithArguments("double", "int").WithLocation(5, 22), // (5,22): error CS0150: A constant value is expected // var s = $"{1,1E10}"; Diagnostic(ErrorCode.ERR_ConstantExpected, "1E10").WithLocation(5, 22), // (6,22): error CS0221: Constant value '10000000000' cannot be converted to a 'int' (use 'unchecked' syntax to override) // var t = $"{1,(int)1E10}"; Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, "(int)1E10").WithArguments("10000000000", "int").WithLocation(6, 22), // (6,22): error CS0150: A constant value is expected // var t = $"{1,(int)1E10}"; Diagnostic(ErrorCode.ERR_ConstantExpected, "(int)1E10").WithLocation(6, 22) ); } [Fact] public void NestedInterpolatedVerbatim() { string source = @"using System; class Program { static void Main(string[] args) { var s = $@""{$@""{1}""}""; Console.WriteLine(s); } }"; string expectedOutput = @"1"; CompileAndVerify(source, expectedOutput: expectedOutput); } // Since the platform type System.FormattableString is not yet in our platforms (at the // time of writing), we explicitly include the required platform types into the sources under test. private const string formattableString = @" /*============================================================ ** ** Class: FormattableString ** ** ** Purpose: implementation of the FormattableString ** class. ** ===========================================================*/ namespace System { /// <summary> /// A composite format string along with the arguments to be formatted. An instance of this /// type may result from the use of the C# or VB language primitive ""interpolated string"". /// </summary> public abstract class FormattableString : IFormattable { /// <summary> /// The composite format string. /// </summary> public abstract string Format { get; } /// <summary> /// Returns an object array that contains zero or more objects to format. Clients should not /// mutate the contents of the array. /// </summary> public abstract object[] GetArguments(); /// <summary> /// The number of arguments to be formatted. /// </summary> public abstract int ArgumentCount { get; } /// <summary> /// Returns one argument to be formatted from argument position <paramref name=""index""/>. /// </summary> public abstract object GetArgument(int index); /// <summary> /// Format to a string using the given culture. /// </summary> public abstract string ToString(IFormatProvider formatProvider); string IFormattable.ToString(string ignored, IFormatProvider formatProvider) { return ToString(formatProvider); } /// <summary> /// Format the given object in the invariant culture. This static method may be /// imported in C# by /// <code> /// using static System.FormattableString; /// </code>. /// Within the scope /// of that import directive an interpolated string may be formatted in the /// invariant culture by writing, for example, /// <code> /// Invariant($""{{ lat = {latitude}; lon = {longitude} }}"") /// </code> /// </summary> public static string Invariant(FormattableString formattable) { if (formattable == null) { throw new ArgumentNullException(""formattable""); } return formattable.ToString(Globalization.CultureInfo.InvariantCulture); } public override string ToString() { return ToString(Globalization.CultureInfo.CurrentCulture); } } } /*============================================================ ** ** Class: FormattableStringFactory ** ** ** Purpose: implementation of the FormattableStringFactory ** class. ** ===========================================================*/ namespace System.Runtime.CompilerServices { /// <summary> /// A factory type used by compilers to create instances of the type <see cref=""FormattableString""/>. /// </summary> public static class FormattableStringFactory { /// <summary> /// Create a <see cref=""FormattableString""/> from a composite format string and object /// array containing zero or more objects to format. /// </summary> public static FormattableString Create(string format, params object[] arguments) { if (format == null) { throw new ArgumentNullException(""format""); } if (arguments == null) { throw new ArgumentNullException(""arguments""); } return new ConcreteFormattableString(format, arguments); } private sealed class ConcreteFormattableString : FormattableString { private readonly string _format; private readonly object[] _arguments; internal ConcreteFormattableString(string format, object[] arguments) { _format = format; _arguments = arguments; } public override string Format { get { return _format; } } public override object[] GetArguments() { return _arguments; } public override int ArgumentCount { get { return _arguments.Length; } } public override object GetArgument(int index) { return _arguments[index]; } public override string ToString(IFormatProvider formatProvider) { return string.Format(formatProvider, Format, _arguments); } } } } "; [Fact] public void TargetType01() { string source = @"using System; class Program { public static void Main(string[] args) { IFormattable f = $""test""; Console.Write(f is System.FormattableString); } }"; CompileAndVerify(source + formattableString, expectedOutput: "True"); } [Fact] public void TargetType02() { string source = @"using System; interface I1 { void M(String s); } interface I2 { void M(FormattableString s); } interface I3 { void M(IFormattable s); } interface I4 : I1, I2 {} interface I5 : I1, I3 {} interface I6 : I2, I3 {} interface I7 : I1, I2, I3 {} class C : I1, I2, I3, I4, I5, I6, I7 { public void M(String s) { Console.Write(1); } public void M(FormattableString s) { Console.Write(2); } public void M(IFormattable s) { Console.Write(3); } } class Program { public static void Main(string[] args) { C c = new C(); ((I1)c).M($""""); ((I2)c).M($""""); ((I3)c).M($""""); ((I4)c).M($""""); ((I5)c).M($""""); ((I6)c).M($""""); ((I7)c).M($""""); ((C)c).M($""""); } }"; CompileAndVerify(source + formattableString, expectedOutput: "12311211"); } [Fact] public void MissingHelper() { string source = @"using System; class Program { public static void Main(string[] args) { IFormattable f = $""test""; } }"; CreateCompilationWithMscorlib40(source).VerifyEmitDiagnostics( // (5,26): error CS0518: Predefined type 'System.Runtime.CompilerServices.FormattableStringFactory' is not defined or imported // IFormattable f = $"test"; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"$""test""").WithArguments("System.Runtime.CompilerServices.FormattableStringFactory").WithLocation(5, 26) ); } [Fact] public void AsyncInterp() { string source = @"using System; using System.Threading.Tasks; class Program { public static void Main(string[] args) { Task<string> hello = Task.FromResult(""Hello""); Task<string> world = Task.FromResult(""world""); M(hello, world).Wait(); } public static async Task M(Task<string> hello, Task<string> world) { Console.WriteLine($""{ await hello }, { await world }!""); } }"; CompileAndVerify( source, references: new[] { MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929 }, expectedOutput: "Hello, world!", targetFramework: TargetFramework.Empty); } [Fact] public void AlignmentExpression() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""X = { 123 , -(3+4) }.""); } }"; CompileAndVerify(source + formattableString, expectedOutput: "X = 123 ."); } [Fact] public void AlignmentMagnitude() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""X = { 123 , (32768) }.""); Console.WriteLine($""X = { 123 , -(32768) }.""); Console.WriteLine($""X = { 123 , (32767) }.""); Console.WriteLine($""X = { 123 , -(32767) }.""); Console.WriteLine($""X = { 123 , int.MaxValue }.""); Console.WriteLine($""X = { 123 , int.MinValue }.""); } }"; CreateCompilation(source).VerifyDiagnostics( // (5,42): warning CS8094: Alignment value 32768 has a magnitude greater than 32767 and may result in a large formatted string. // Console.WriteLine($"X = { 123 , (32768) }."); Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "32768").WithArguments("32768", "32767").WithLocation(5, 42), // (6,41): warning CS8094: Alignment value -32768 has a magnitude greater than 32767 and may result in a large formatted string. // Console.WriteLine($"X = { 123 , -(32768) }."); Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "-(32768)").WithArguments("-32768", "32767").WithLocation(6, 41), // (9,41): warning CS8094: Alignment value 2147483647 has a magnitude greater than 32767 and may result in a large formatted string. // Console.WriteLine($"X = { 123 , int.MaxValue }."); Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "int.MaxValue").WithArguments("2147483647", "32767").WithLocation(9, 41), // (10,41): warning CS8094: Alignment value -2147483648 has a magnitude greater than 32767 and may result in a large formatted string. // Console.WriteLine($"X = { 123 , int.MinValue }."); Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "int.MinValue").WithArguments("-2147483648", "32767").WithLocation(10, 41) ); } [WorkItem(1097388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097388")] [Fact] public void InterpolationExpressionMustBeValue01() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""X = { String }.""); Console.WriteLine($""X = { null }.""); } }"; CreateCompilation(source).VerifyDiagnostics( // (5,35): error CS0119: 'string' is a type, which is not valid in the given context // Console.WriteLine($"X = { String }."); Diagnostic(ErrorCode.ERR_BadSKunknown, "String").WithArguments("string", "type").WithLocation(5, 35) ); } [Fact] public void InterpolationExpressionMustBeValue02() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""X = { x=>3 }.""); Console.WriteLine($""X = { Program.Main }.""); Console.WriteLine($""X = { Program.Main(null) }.""); } }"; CreateCompilation(source).VerifyDiagnostics( // (5,35): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // Console.WriteLine($"X = { x=>3 }."); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x=>3").WithArguments("lambda expression", "object").WithLocation(5, 35), // (6,43): error CS0428: Cannot convert method group 'Main' to non-delegate type 'object'. Did you intend to invoke the method? // Console.WriteLine($"X = { Program.Main }."); Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "object").WithLocation(6, 43), // (7,35): error CS0029: Cannot implicitly convert type 'void' to 'object' // Console.WriteLine($"X = { Program.Main(null) }."); Diagnostic(ErrorCode.ERR_NoImplicitConv, "Program.Main(null)").WithArguments("void", "object").WithLocation(7, 35) ); } [WorkItem(1097428, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097428")] [Fact] public void BadCorelib01() { var text = @"namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } } public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } } public struct Char { } public class String { } internal class Program { public static void Main() { var s = $""X = { 1 } ""; } } }"; CreateEmptyCompilation(text, options: TestOptions.DebugExe) .VerifyEmitDiagnostics(new CodeAnalysis.Emit.EmitOptions(runtimeMetadataVersion: "x.y"), // (15,21): error CS0117: 'string' does not contain a definition for 'Format' // var s = $"X = { 1 } "; Diagnostic(ErrorCode.ERR_NoSuchMember, @"$""X = { 1 } """).WithArguments("string", "Format").WithLocation(15, 21) ); } [WorkItem(1097428, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097428")] [Fact] public void BadCorelib02() { var text = @"namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } } public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } } public struct Char { } public class String { public static Boolean Format(string format, int arg) { return true; } } internal class Program { public static void Main() { var s = $""X = { 1 } ""; } } }"; CreateEmptyCompilation(text, options: TestOptions.DebugExe) .VerifyEmitDiagnostics(new CodeAnalysis.Emit.EmitOptions(runtimeMetadataVersion: "x.y"), // (17,21): error CS0029: Cannot implicitly convert type 'bool' to 'string' // var s = $"X = { 1 } "; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""X = { 1 } """).WithArguments("bool", "string").WithLocation(17, 21) ); } [Fact] public void SillyCoreLib01() { var text = @"namespace System { interface IFormattable { } namespace Runtime.CompilerServices { public static class FormattableStringFactory { public static Bozo Create(string format, int arg) { return new Bozo(); } } } public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } } public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } } public struct Char { } public class String { public static Bozo Format(string format, int arg) { return new Bozo(); } } public class FormattableString { } public class Bozo { public static implicit operator string(Bozo bozo) { return ""zz""; } public static implicit operator FormattableString(Bozo bozo) { return new FormattableString(); } } internal class Program { public static void Main() { var s1 = $""X = { 1 } ""; FormattableString s2 = $""X = { 1 } ""; } } }"; var comp = CreateEmptyCompilation(text, options: Test.Utilities.TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); var compilation = CompileAndVerify(comp, verify: Verification.Fails); compilation.VerifyIL("System.Program.Main", @"{ // Code size 35 (0x23) .maxstack 2 IL_0000: ldstr ""X = {0} "" IL_0005: ldc.i4.1 IL_0006: call ""System.Bozo string.Format(string, int)"" IL_000b: call ""string System.Bozo.op_Implicit(System.Bozo)"" IL_0010: pop IL_0011: ldstr ""X = {0} "" IL_0016: ldc.i4.1 IL_0017: call ""System.Bozo System.Runtime.CompilerServices.FormattableStringFactory.Create(string, int)"" IL_001c: call ""System.FormattableString System.Bozo.op_Implicit(System.Bozo)"" IL_0021: pop IL_0022: ret }"); } [WorkItem(1097386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097386")] [Fact] public void Syntax01() { var text = @"using System; class Program { static void Main(string[] args) { var x = $""{ Math.Abs(value: 1):\}""; var y = x; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,40): error CS8087: A '}' character may only be escaped by doubling '}}' in an interpolated string. // var x = $"{ Math.Abs(value: 1):\}"; Diagnostic(ErrorCode.ERR_EscapedCurly, @"\").WithArguments("}").WithLocation(6, 40), // (6,40): error CS1009: Unrecognized escape sequence // var x = $"{ Math.Abs(value: 1):\}"; Diagnostic(ErrorCode.ERR_IllegalEscape, @"\}").WithLocation(6, 40) ); } [WorkItem(1097941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097941")] [Fact] public void Syntax02() { var text = @"using S = System; class C { void M() { var x = $""{ (S: } }"; // the precise diagnostics do not matter, as long as it is an error and not a crash. Assert.True(SyntaxFactory.ParseSyntaxTree(text).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [WorkItem(1097386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097386")] [Fact] public void Syntax03() { var text = @"using System; class Program { static void Main(string[] args) { var x = $""{ Math.Abs(value: 1):}}""; var y = x; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,18): error CS8076: Missing close delimiter '}' for interpolated expression started with '{'. // var x = $"{ Math.Abs(value: 1):}}"; Diagnostic(ErrorCode.ERR_UnclosedExpressionHole, @"""{").WithLocation(6, 18) ); } [WorkItem(1099105, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1099105")] [Fact] public void NoUnexpandedForm() { string source = @"using System; class Program { public static void Main(string[] args) { string[] arr1 = new string[] { ""xyzzy"" }; object[] arr2 = arr1; Console.WriteLine($""-{null}-""); Console.WriteLine($""-{arr1}-""); Console.WriteLine($""-{arr2}-""); } }"; CompileAndVerify(source + formattableString, expectedOutput: @"-- -System.String[]- -System.String[]-"); } [WorkItem(1097386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097386")] [Fact] public void Dynamic01() { var text = @"class C { const dynamic a = a; string s = $""{0,a}""; }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (3,19): error CS0110: The evaluation of the constant value for 'C.a' involves a circular definition // const dynamic a = a; Diagnostic(ErrorCode.ERR_CircConstValue, "a").WithArguments("C.a").WithLocation(3, 19), // (3,23): error CS0134: 'C.a' is of type 'dynamic'. A const field of a reference type other than string can only be initialized with null. // const dynamic a = a; Diagnostic(ErrorCode.ERR_NotNullConstRefField, "a").WithArguments("C.a", "dynamic").WithLocation(3, 23), // (4,21): error CS0150: A constant value is expected // string s = $"{0,a}"; Diagnostic(ErrorCode.ERR_ConstantExpected, "a").WithLocation(4, 21) ); } [WorkItem(1099238, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1099238")] [Fact] public void Syntax04() { var text = @"using System; using System.Linq.Expressions; class Program { static void Main() { Expression<Func<string>> e = () => $""\u1{0:\u2}""; Console.WriteLine(e); } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (8,46): error CS1009: Unrecognized escape sequence // Expression<Func<string>> e = () => $"\u1{0:\u2}"; Diagnostic(ErrorCode.ERR_IllegalEscape, @"\u1").WithLocation(8, 46), // (8,52): error CS1009: Unrecognized escape sequence // Expression<Func<string>> e = () => $"\u1{0:\u2}"; Diagnostic(ErrorCode.ERR_IllegalEscape, @"\u2").WithLocation(8, 52) ); } [Fact, WorkItem(1098612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1098612")] public void MissingConversionFromFormattableStringToIFormattable() { var text = @"namespace System.Runtime.CompilerServices { public static class FormattableStringFactory { public static FormattableString Create(string format, params object[] arguments) { return null; } } } namespace System { public abstract class FormattableString { } } static class C { static void Main() { System.IFormattable i = $""{""""}""; } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyEmitDiagnostics( // (23,33): error CS0029: Cannot implicitly convert type 'FormattableString' to 'IFormattable' // System.IFormattable i = $"{""}"; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""{""""}""").WithArguments("System.FormattableString", "System.IFormattable").WithLocation(23, 33) ); } [Fact, WorkItem(54702, "https://github.com/dotnet/roslyn/issues/54702")] public void InterpolatedStringHandler_ConcatPreferencesForAllStringElements() { var code = @" using System; Console.WriteLine(TwoComponents()); Console.WriteLine(ThreeComponents()); Console.WriteLine(FourComponents()); Console.WriteLine(FiveComponents()); string TwoComponents() { string s1 = ""1""; string s2 = ""2""; return $""{s1}{s2}""; } string ThreeComponents() { string s1 = ""1""; string s2 = ""2""; string s3 = ""3""; return $""{s1}{s2}{s3}""; } string FourComponents() { string s1 = ""1""; string s2 = ""2""; string s3 = ""3""; string s4 = ""4""; return $""{s1}{s2}{s3}{s4}""; } string FiveComponents() { string s1 = ""1""; string s2 = ""2""; string s3 = ""3""; string s4 = ""4""; string s5 = ""5""; return $""{s1}{s2}{s3}{s4}{s5}""; } "; var handler = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { code, handler }, expectedOutput: @" 12 123 1234 value:1 value:2 value:3 value:4 value:5 "); verifier.VerifyIL("<Program>$.<<Main>$>g__TwoComponents|0_0()", @" { // Code size 18 (0x12) .maxstack 2 .locals init (string V_0) //s2 IL_0000: ldstr ""1"" IL_0005: ldstr ""2"" IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: call ""string string.Concat(string, string)"" IL_0011: ret } "); verifier.VerifyIL("<Program>$.<<Main>$>g__ThreeComponents|0_1()", @" { // Code size 25 (0x19) .maxstack 3 .locals init (string V_0, //s2 string V_1) //s3 IL_0000: ldstr ""1"" IL_0005: ldstr ""2"" IL_000a: stloc.0 IL_000b: ldstr ""3"" IL_0010: stloc.1 IL_0011: ldloc.0 IL_0012: ldloc.1 IL_0013: call ""string string.Concat(string, string, string)"" IL_0018: ret } "); verifier.VerifyIL("<Program>$.<<Main>$>g__FourComponents|0_2()", @" { // Code size 32 (0x20) .maxstack 4 .locals init (string V_0, //s2 string V_1, //s3 string V_2) //s4 IL_0000: ldstr ""1"" IL_0005: ldstr ""2"" IL_000a: stloc.0 IL_000b: ldstr ""3"" IL_0010: stloc.1 IL_0011: ldstr ""4"" IL_0016: stloc.2 IL_0017: ldloc.0 IL_0018: ldloc.1 IL_0019: ldloc.2 IL_001a: call ""string string.Concat(string, string, string, string)"" IL_001f: ret } "); verifier.VerifyIL("<Program>$.<<Main>$>g__FiveComponents|0_3()", @" { // Code size 89 (0x59) .maxstack 3 .locals init (string V_0, //s1 string V_1, //s2 string V_2, //s3 string V_3, //s4 string V_4, //s5 System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_5) IL_0000: ldstr ""1"" IL_0005: stloc.0 IL_0006: ldstr ""2"" IL_000b: stloc.1 IL_000c: ldstr ""3"" IL_0011: stloc.2 IL_0012: ldstr ""4"" IL_0017: stloc.3 IL_0018: ldstr ""5"" IL_001d: stloc.s V_4 IL_001f: ldloca.s V_5 IL_0021: ldc.i4.0 IL_0022: ldc.i4.5 IL_0023: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0028: ldloca.s V_5 IL_002a: ldloc.0 IL_002b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0030: ldloca.s V_5 IL_0032: ldloc.1 IL_0033: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0038: ldloca.s V_5 IL_003a: ldloc.2 IL_003b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0040: ldloca.s V_5 IL_0042: ldloc.3 IL_0043: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0048: ldloca.s V_5 IL_004a: ldloc.s V_4 IL_004c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0051: ldloca.s V_5 IL_0053: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0058: ret } "); } [Theory] [CombinatorialData] public void InterpolatedStringHandler_OverloadsAndBoolReturns(bool useDefaultParameters, bool useBoolReturns, bool constructorBoolArg) { var source = @"int a = 1; System.Console.WriteLine($""base{a}{a,1}{a:X}{a,2:Y}"");"; string interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters, useBoolReturns, constructorBoolArg: constructorBoolArg); string expectedOutput = useDefaultParameters ? @"base value:1,alignment:0:format: value:1,alignment:1:format: value:1,alignment:0:format:X value:1,alignment:2:format:Y" : @"base value:1 value:1,alignment:1 value:1:format:X value:1,alignment:2:format:Y"; string expectedIl = getIl(); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: expectedOutput); verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl); var comp1 = CreateCompilation(interpolatedStringBuilder); foreach (var reference in new[] { comp1.EmitToImageReference(), comp1.ToMetadataReference() }) { var comp2 = CreateCompilation(source, new[] { reference }); verifier = CompileAndVerify(comp2, expectedOutput: expectedOutput); verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl); } string getIl() => (useDefaultParameters, useBoolReturns, constructorBoolArg) switch { (useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: false) => @" { // Code size 80 (0x50) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""base"" IL_0012: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: ldloca.s V_1 IL_0019: ldloc.0 IL_001a: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_001f: ldloca.s V_1 IL_0021: ldloc.0 IL_0022: ldc.i4.1 IL_0023: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)"" IL_0028: ldloca.s V_1 IL_002a: ldloc.0 IL_002b: ldstr ""X"" IL_0030: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)"" IL_0035: ldloca.s V_1 IL_0037: ldloc.0 IL_0038: ldc.i4.2 IL_0039: ldstr ""Y"" IL_003e: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0043: ldloca.s V_1 IL_0045: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_004a: call ""void System.Console.WriteLine(string)"" IL_004f: ret } ", (useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: false) => @" { // Code size 84 (0x54) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""base"" IL_0012: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: ldloca.s V_1 IL_0019: ldloc.0 IL_001a: ldc.i4.0 IL_001b: ldnull IL_001c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0021: ldloca.s V_1 IL_0023: ldloc.0 IL_0024: ldc.i4.1 IL_0025: ldnull IL_0026: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_002b: ldloca.s V_1 IL_002d: ldloc.0 IL_002e: ldc.i4.0 IL_002f: ldstr ""X"" IL_0034: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0039: ldloca.s V_1 IL_003b: ldloc.0 IL_003c: ldc.i4.2 IL_003d: ldstr ""Y"" IL_0042: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0047: ldloca.s V_1 IL_0049: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_004e: call ""void System.Console.WriteLine(string)"" IL_0053: ret } ", (useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: false) => @" { // Code size 92 (0x5c) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""base"" IL_0012: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: brfalse.s IL_004d IL_0019: ldloca.s V_1 IL_001b: ldloc.0 IL_001c: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0021: brfalse.s IL_004d IL_0023: ldloca.s V_1 IL_0025: ldloc.0 IL_0026: ldc.i4.1 IL_0027: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)"" IL_002c: brfalse.s IL_004d IL_002e: ldloca.s V_1 IL_0030: ldloc.0 IL_0031: ldstr ""X"" IL_0036: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)"" IL_003b: brfalse.s IL_004d IL_003d: ldloca.s V_1 IL_003f: ldloc.0 IL_0040: ldc.i4.2 IL_0041: ldstr ""Y"" IL_0046: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_004b: br.s IL_004e IL_004d: ldc.i4.0 IL_004e: pop IL_004f: ldloca.s V_1 IL_0051: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0056: call ""void System.Console.WriteLine(string)"" IL_005b: ret } ", (useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: false) => @" { // Code size 96 (0x60) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""base"" IL_0012: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: brfalse.s IL_0051 IL_0019: ldloca.s V_1 IL_001b: ldloc.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0023: brfalse.s IL_0051 IL_0025: ldloca.s V_1 IL_0027: ldloc.0 IL_0028: ldc.i4.1 IL_0029: ldnull IL_002a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_002f: brfalse.s IL_0051 IL_0031: ldloca.s V_1 IL_0033: ldloc.0 IL_0034: ldc.i4.0 IL_0035: ldstr ""X"" IL_003a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_003f: brfalse.s IL_0051 IL_0041: ldloca.s V_1 IL_0043: ldloc.0 IL_0044: ldc.i4.2 IL_0045: ldstr ""Y"" IL_004a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_004f: br.s IL_0052 IL_0051: ldc.i4.0 IL_0052: pop IL_0053: ldloca.s V_1 IL_0055: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005a: call ""void System.Console.WriteLine(string)"" IL_005f: ret } ", (useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: true) => @" { // Code size 89 (0x59) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.4 IL_0004: ldloca.s V_2 IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_000b: stloc.1 IL_000c: ldloc.2 IL_000d: brfalse.s IL_004a IL_000f: ldloca.s V_1 IL_0011: ldstr ""base"" IL_0016: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_001b: ldloca.s V_1 IL_001d: ldloc.0 IL_001e: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0023: ldloca.s V_1 IL_0025: ldloc.0 IL_0026: ldc.i4.1 IL_0027: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)"" IL_002c: ldloca.s V_1 IL_002e: ldloc.0 IL_002f: ldstr ""X"" IL_0034: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)"" IL_0039: ldloca.s V_1 IL_003b: ldloc.0 IL_003c: ldc.i4.2 IL_003d: ldstr ""Y"" IL_0042: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0047: ldc.i4.1 IL_0048: br.s IL_004b IL_004a: ldc.i4.0 IL_004b: pop IL_004c: ldloca.s V_1 IL_004e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0053: call ""void System.Console.WriteLine(string)"" IL_0058: ret } ", (useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: true) => @" { // Code size 93 (0x5d) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.4 IL_0004: ldloca.s V_2 IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_000b: stloc.1 IL_000c: ldloc.2 IL_000d: brfalse.s IL_004e IL_000f: ldloca.s V_1 IL_0011: ldstr ""base"" IL_0016: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_001b: ldloca.s V_1 IL_001d: ldloc.0 IL_001e: ldc.i4.0 IL_001f: ldnull IL_0020: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0025: ldloca.s V_1 IL_0027: ldloc.0 IL_0028: ldc.i4.1 IL_0029: ldnull IL_002a: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_002f: ldloca.s V_1 IL_0031: ldloc.0 IL_0032: ldc.i4.0 IL_0033: ldstr ""X"" IL_0038: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_003d: ldloca.s V_1 IL_003f: ldloc.0 IL_0040: ldc.i4.2 IL_0041: ldstr ""Y"" IL_0046: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_004b: ldc.i4.1 IL_004c: br.s IL_004f IL_004e: ldc.i4.0 IL_004f: pop IL_0050: ldloca.s V_1 IL_0052: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0057: call ""void System.Console.WriteLine(string)"" IL_005c: ret } ", (useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: true) => @" { // Code size 96 (0x60) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.4 IL_0004: ldloca.s V_2 IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_000b: stloc.1 IL_000c: ldloc.2 IL_000d: brfalse.s IL_0051 IL_000f: ldloca.s V_1 IL_0011: ldstr ""base"" IL_0016: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_001b: brfalse.s IL_0051 IL_001d: ldloca.s V_1 IL_001f: ldloc.0 IL_0020: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0025: brfalse.s IL_0051 IL_0027: ldloca.s V_1 IL_0029: ldloc.0 IL_002a: ldc.i4.1 IL_002b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)"" IL_0030: brfalse.s IL_0051 IL_0032: ldloca.s V_1 IL_0034: ldloc.0 IL_0035: ldstr ""X"" IL_003a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)"" IL_003f: brfalse.s IL_0051 IL_0041: ldloca.s V_1 IL_0043: ldloc.0 IL_0044: ldc.i4.2 IL_0045: ldstr ""Y"" IL_004a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_004f: br.s IL_0052 IL_0051: ldc.i4.0 IL_0052: pop IL_0053: ldloca.s V_1 IL_0055: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005a: call ""void System.Console.WriteLine(string)"" IL_005f: ret } ", (useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: true) => @" { // Code size 100 (0x64) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.4 IL_0004: ldloca.s V_2 IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_000b: stloc.1 IL_000c: ldloc.2 IL_000d: brfalse.s IL_0055 IL_000f: ldloca.s V_1 IL_0011: ldstr ""base"" IL_0016: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_001b: brfalse.s IL_0055 IL_001d: ldloca.s V_1 IL_001f: ldloc.0 IL_0020: ldc.i4.0 IL_0021: ldnull IL_0022: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0027: brfalse.s IL_0055 IL_0029: ldloca.s V_1 IL_002b: ldloc.0 IL_002c: ldc.i4.1 IL_002d: ldnull IL_002e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0033: brfalse.s IL_0055 IL_0035: ldloca.s V_1 IL_0037: ldloc.0 IL_0038: ldc.i4.0 IL_0039: ldstr ""X"" IL_003e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0043: brfalse.s IL_0055 IL_0045: ldloca.s V_1 IL_0047: ldloc.0 IL_0048: ldc.i4.2 IL_0049: ldstr ""Y"" IL_004e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0053: br.s IL_0056 IL_0055: ldc.i4.0 IL_0056: pop IL_0057: ldloca.s V_1 IL_0059: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005e: call ""void System.Console.WriteLine(string)"" IL_0063: ret } ", }; } [Fact] public void UseOfSpanInInterpolationHole_CSharp9() { var source = @" using System; ReadOnlySpan<char> span = stackalloc char[1]; Console.WriteLine($""{span}"");"; var comp = CreateCompilation(new[] { source, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false) }, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,22): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater. // Console.WriteLine($"{span}"); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "span").WithArguments("interpolated string handlers", "10.0").WithLocation(4, 22) ); } [ConditionalTheory(typeof(MonoOrCoreClrOnly))] [CombinatorialData] public void UseOfSpanInInterpolationHole(bool useDefaultParameters, bool useBoolReturns, bool constructorBoolArg) { var source = @" using System; ReadOnlySpan<char> a = ""1""; System.Console.WriteLine($""base{a}{a,1}{a:X}{a,2:Y}"");"; string interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters, useBoolReturns, constructorBoolArg: constructorBoolArg); string expectedOutput = useDefaultParameters ? @"base value:1,alignment:0:format: value:1,alignment:1:format: value:1,alignment:0:format:X value:1,alignment:2:format:Y" : @"base value:1 value:1,alignment:1 value:1:format:X value:1,alignment:2:format:Y"; string expectedIl = getIl(); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: expectedOutput, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular10); verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl); var comp1 = CreateCompilation(interpolatedStringBuilder, targetFramework: TargetFramework.NetCoreApp); foreach (var reference in new[] { comp1.EmitToImageReference(), comp1.ToMetadataReference() }) { var comp2 = CreateCompilation(source, new[] { reference }, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular10); verifier = CompileAndVerify(comp2, expectedOutput: expectedOutput); verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl); } string getIl() => (useDefaultParameters, useBoolReturns, constructorBoolArg) switch { (useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: false) => @" { // Code size 89 (0x59) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldloca.s V_1 IL_000d: ldc.i4.4 IL_000e: ldc.i4.4 IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0014: ldloca.s V_1 IL_0016: ldstr ""base"" IL_001b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0020: ldloca.s V_1 IL_0022: ldloc.0 IL_0023: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_0028: ldloca.s V_1 IL_002a: ldloc.0 IL_002b: ldc.i4.1 IL_002c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)"" IL_0031: ldloca.s V_1 IL_0033: ldloc.0 IL_0034: ldstr ""X"" IL_0039: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)"" IL_003e: ldloca.s V_1 IL_0040: ldloc.0 IL_0041: ldc.i4.2 IL_0042: ldstr ""Y"" IL_0047: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_004c: ldloca.s V_1 IL_004e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0053: call ""void System.Console.WriteLine(string)"" IL_0058: ret } ", (useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: false) => @" { // Code size 93 (0x5d) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldloca.s V_1 IL_000d: ldc.i4.4 IL_000e: ldc.i4.4 IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0014: ldloca.s V_1 IL_0016: ldstr ""base"" IL_001b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0020: ldloca.s V_1 IL_0022: ldloc.0 IL_0023: ldc.i4.0 IL_0024: ldnull IL_0025: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_002a: ldloca.s V_1 IL_002c: ldloc.0 IL_002d: ldc.i4.1 IL_002e: ldnull IL_002f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0034: ldloca.s V_1 IL_0036: ldloc.0 IL_0037: ldc.i4.0 IL_0038: ldstr ""X"" IL_003d: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0042: ldloca.s V_1 IL_0044: ldloc.0 IL_0045: ldc.i4.2 IL_0046: ldstr ""Y"" IL_004b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0050: ldloca.s V_1 IL_0052: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0057: call ""void System.Console.WriteLine(string)"" IL_005c: ret } ", (useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: false) => @" { // Code size 101 (0x65) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldloca.s V_1 IL_000d: ldc.i4.4 IL_000e: ldc.i4.4 IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0014: ldloca.s V_1 IL_0016: ldstr ""base"" IL_001b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0020: brfalse.s IL_0056 IL_0022: ldloca.s V_1 IL_0024: ldloc.0 IL_0025: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_002a: brfalse.s IL_0056 IL_002c: ldloca.s V_1 IL_002e: ldloc.0 IL_002f: ldc.i4.1 IL_0030: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)"" IL_0035: brfalse.s IL_0056 IL_0037: ldloca.s V_1 IL_0039: ldloc.0 IL_003a: ldstr ""X"" IL_003f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)"" IL_0044: brfalse.s IL_0056 IL_0046: ldloca.s V_1 IL_0048: ldloc.0 IL_0049: ldc.i4.2 IL_004a: ldstr ""Y"" IL_004f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0054: br.s IL_0057 IL_0056: ldc.i4.0 IL_0057: pop IL_0058: ldloca.s V_1 IL_005a: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005f: call ""void System.Console.WriteLine(string)"" IL_0064: ret } ", (useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: false) => @" { // Code size 105 (0x69) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldloca.s V_1 IL_000d: ldc.i4.4 IL_000e: ldc.i4.4 IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0014: ldloca.s V_1 IL_0016: ldstr ""base"" IL_001b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0020: brfalse.s IL_005a IL_0022: ldloca.s V_1 IL_0024: ldloc.0 IL_0025: ldc.i4.0 IL_0026: ldnull IL_0027: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_002c: brfalse.s IL_005a IL_002e: ldloca.s V_1 IL_0030: ldloc.0 IL_0031: ldc.i4.1 IL_0032: ldnull IL_0033: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0038: brfalse.s IL_005a IL_003a: ldloca.s V_1 IL_003c: ldloc.0 IL_003d: ldc.i4.0 IL_003e: ldstr ""X"" IL_0043: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0048: brfalse.s IL_005a IL_004a: ldloca.s V_1 IL_004c: ldloc.0 IL_004d: ldc.i4.2 IL_004e: ldstr ""Y"" IL_0053: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0058: br.s IL_005b IL_005a: ldc.i4.0 IL_005b: pop IL_005c: ldloca.s V_1 IL_005e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0063: call ""void System.Console.WriteLine(string)"" IL_0068: ret } ", (useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: true) => @" { // Code size 98 (0x62) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldc.i4.4 IL_000c: ldc.i4.4 IL_000d: ldloca.s V_2 IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_0014: stloc.1 IL_0015: ldloc.2 IL_0016: brfalse.s IL_0053 IL_0018: ldloca.s V_1 IL_001a: ldstr ""base"" IL_001f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0024: ldloca.s V_1 IL_0026: ldloc.0 IL_0027: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_002c: ldloca.s V_1 IL_002e: ldloc.0 IL_002f: ldc.i4.1 IL_0030: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)"" IL_0035: ldloca.s V_1 IL_0037: ldloc.0 IL_0038: ldstr ""X"" IL_003d: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)"" IL_0042: ldloca.s V_1 IL_0044: ldloc.0 IL_0045: ldc.i4.2 IL_0046: ldstr ""Y"" IL_004b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0050: ldc.i4.1 IL_0051: br.s IL_0054 IL_0053: ldc.i4.0 IL_0054: pop IL_0055: ldloca.s V_1 IL_0057: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005c: call ""void System.Console.WriteLine(string)"" IL_0061: ret } ", (useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: true) => @" { // Code size 105 (0x69) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldc.i4.4 IL_000c: ldc.i4.4 IL_000d: ldloca.s V_2 IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_0014: stloc.1 IL_0015: ldloc.2 IL_0016: brfalse.s IL_005a IL_0018: ldloca.s V_1 IL_001a: ldstr ""base"" IL_001f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0024: brfalse.s IL_005a IL_0026: ldloca.s V_1 IL_0028: ldloc.0 IL_0029: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_002e: brfalse.s IL_005a IL_0030: ldloca.s V_1 IL_0032: ldloc.0 IL_0033: ldc.i4.1 IL_0034: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)"" IL_0039: brfalse.s IL_005a IL_003b: ldloca.s V_1 IL_003d: ldloc.0 IL_003e: ldstr ""X"" IL_0043: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)"" IL_0048: brfalse.s IL_005a IL_004a: ldloca.s V_1 IL_004c: ldloc.0 IL_004d: ldc.i4.2 IL_004e: ldstr ""Y"" IL_0053: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0058: br.s IL_005b IL_005a: ldc.i4.0 IL_005b: pop IL_005c: ldloca.s V_1 IL_005e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0063: call ""void System.Console.WriteLine(string)"" IL_0068: ret } ", (useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: true) => @" { // Code size 102 (0x66) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldc.i4.4 IL_000c: ldc.i4.4 IL_000d: ldloca.s V_2 IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_0014: stloc.1 IL_0015: ldloc.2 IL_0016: brfalse.s IL_0057 IL_0018: ldloca.s V_1 IL_001a: ldstr ""base"" IL_001f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0024: ldloca.s V_1 IL_0026: ldloc.0 IL_0027: ldc.i4.0 IL_0028: ldnull IL_0029: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_002e: ldloca.s V_1 IL_0030: ldloc.0 IL_0031: ldc.i4.1 IL_0032: ldnull IL_0033: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0038: ldloca.s V_1 IL_003a: ldloc.0 IL_003b: ldc.i4.0 IL_003c: ldstr ""X"" IL_0041: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0046: ldloca.s V_1 IL_0048: ldloc.0 IL_0049: ldc.i4.2 IL_004a: ldstr ""Y"" IL_004f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0054: ldc.i4.1 IL_0055: br.s IL_0058 IL_0057: ldc.i4.0 IL_0058: pop IL_0059: ldloca.s V_1 IL_005b: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0060: call ""void System.Console.WriteLine(string)"" IL_0065: ret } ", (useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: true) => @" { // Code size 109 (0x6d) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldc.i4.4 IL_000c: ldc.i4.4 IL_000d: ldloca.s V_2 IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_0014: stloc.1 IL_0015: ldloc.2 IL_0016: brfalse.s IL_005e IL_0018: ldloca.s V_1 IL_001a: ldstr ""base"" IL_001f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0024: brfalse.s IL_005e IL_0026: ldloca.s V_1 IL_0028: ldloc.0 IL_0029: ldc.i4.0 IL_002a: ldnull IL_002b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0030: brfalse.s IL_005e IL_0032: ldloca.s V_1 IL_0034: ldloc.0 IL_0035: ldc.i4.1 IL_0036: ldnull IL_0037: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_003c: brfalse.s IL_005e IL_003e: ldloca.s V_1 IL_0040: ldloc.0 IL_0041: ldc.i4.0 IL_0042: ldstr ""X"" IL_0047: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_004c: brfalse.s IL_005e IL_004e: ldloca.s V_1 IL_0050: ldloc.0 IL_0051: ldc.i4.2 IL_0052: ldstr ""Y"" IL_0057: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_005c: br.s IL_005f IL_005e: ldc.i4.0 IL_005f: pop IL_0060: ldloca.s V_1 IL_0062: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0067: call ""void System.Console.WriteLine(string)"" IL_006c: ret } ", }; } [Fact] public void BoolReturns_ShortCircuit() { var source = @" using System; int a = 1; Console.Write($""base{Throw()}{a = 2}""); Console.WriteLine(a); string Throw() => throw new Exception();"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: true, returnExpression: "false"); CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" base 1"); } [Theory] [CombinatorialData] public void BoolOutParameter_ShortCircuits(bool useBoolReturns) { var source = @" using System; int a = 1; Console.WriteLine(a); Console.WriteLine($""{Throw()}{a = 2}""); Console.WriteLine(a); string Throw() => throw new Exception(); "; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: useBoolReturns, constructorBoolArg: true, constructorSuccessResult: false); CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" 1 1"); } [Fact] public void AwaitInHoles_UsesFormat() { var source = @" using System; using System.Threading.Tasks; Console.WriteLine($""base{await Hole()}""); Task<int> Hole() => Task.FromResult(1);"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"base1"); verifier.VerifyIL("<Program>$.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 164 (0xa4) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int <Program>$.<<Main>$>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_003e IL_000a: call ""System.Threading.Tasks.Task<int> <Program>$.<<Main>$>g__Hole|0_0()"" IL_000f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0014: stloc.2 IL_0015: ldloca.s V_2 IL_0017: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_001c: brtrue.s IL_005a IL_001e: ldarg.0 IL_001f: ldc.i4.0 IL_0020: dup IL_0021: stloc.0 IL_0022: stfld ""int <Program>$.<<Main>$>d__0.<>1__state"" IL_0027: ldarg.0 IL_0028: ldloc.2 IL_0029: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1"" IL_002e: ldarg.0 IL_002f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder"" IL_0034: ldloca.s V_2 IL_0036: ldarg.0 IL_0037: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, <Program>$.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref <Program>$.<<Main>$>d__0)"" IL_003c: leave.s IL_00a3 IL_003e: ldarg.0 IL_003f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1"" IL_0044: stloc.2 IL_0045: ldarg.0 IL_0046: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1"" IL_004b: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0051: ldarg.0 IL_0052: ldc.i4.m1 IL_0053: dup IL_0054: stloc.0 IL_0055: stfld ""int <Program>$.<<Main>$>d__0.<>1__state"" IL_005a: ldloca.s V_2 IL_005c: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0061: stloc.1 IL_0062: ldstr ""base{0}"" IL_0067: ldloc.1 IL_0068: box ""int"" IL_006d: call ""string string.Format(string, object)"" IL_0072: call ""void System.Console.WriteLine(string)"" IL_0077: leave.s IL_0090 } catch System.Exception { IL_0079: stloc.3 IL_007a: ldarg.0 IL_007b: ldc.i4.s -2 IL_007d: stfld ""int <Program>$.<<Main>$>d__0.<>1__state"" IL_0082: ldarg.0 IL_0083: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder"" IL_0088: ldloc.3 IL_0089: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_008e: leave.s IL_00a3 } IL_0090: ldarg.0 IL_0091: ldc.i4.s -2 IL_0093: stfld ""int <Program>$.<<Main>$>d__0.<>1__state"" IL_0098: ldarg.0 IL_0099: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder"" IL_009e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00a3: ret } "); } [Fact] public void NoAwaitInHoles_UsesBuilder() { var source = @" using System; using System.Threading.Tasks; var hole = await Hole(); Console.WriteLine($""base{hole}""); Task<int> Hole() => Task.FromResult(1);"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" base value:1"); verifier.VerifyIL("<Program>$.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 185 (0xb9) .maxstack 3 .locals init (int V_0, int V_1, //hole System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int <Program>$.<<Main>$>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_003e IL_000a: call ""System.Threading.Tasks.Task<int> <Program>$.<<Main>$>g__Hole|0_0()"" IL_000f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0014: stloc.2 IL_0015: ldloca.s V_2 IL_0017: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_001c: brtrue.s IL_005a IL_001e: ldarg.0 IL_001f: ldc.i4.0 IL_0020: dup IL_0021: stloc.0 IL_0022: stfld ""int <Program>$.<<Main>$>d__0.<>1__state"" IL_0027: ldarg.0 IL_0028: ldloc.2 IL_0029: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1"" IL_002e: ldarg.0 IL_002f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder"" IL_0034: ldloca.s V_2 IL_0036: ldarg.0 IL_0037: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, <Program>$.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref <Program>$.<<Main>$>d__0)"" IL_003c: leave.s IL_00b8 IL_003e: ldarg.0 IL_003f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1"" IL_0044: stloc.2 IL_0045: ldarg.0 IL_0046: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1"" IL_004b: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0051: ldarg.0 IL_0052: ldc.i4.m1 IL_0053: dup IL_0054: stloc.0 IL_0055: stfld ""int <Program>$.<<Main>$>d__0.<>1__state"" IL_005a: ldloca.s V_2 IL_005c: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0061: stloc.1 IL_0062: ldc.i4.4 IL_0063: ldc.i4.1 IL_0064: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0069: stloc.3 IL_006a: ldloca.s V_3 IL_006c: ldstr ""base"" IL_0071: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0076: ldloca.s V_3 IL_0078: ldloc.1 IL_0079: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_007e: ldloca.s V_3 IL_0080: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0085: call ""void System.Console.WriteLine(string)"" IL_008a: leave.s IL_00a5 } catch System.Exception { IL_008c: stloc.s V_4 IL_008e: ldarg.0 IL_008f: ldc.i4.s -2 IL_0091: stfld ""int <Program>$.<<Main>$>d__0.<>1__state"" IL_0096: ldarg.0 IL_0097: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder"" IL_009c: ldloc.s V_4 IL_009e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00a3: leave.s IL_00b8 } IL_00a5: ldarg.0 IL_00a6: ldc.i4.s -2 IL_00a8: stfld ""int <Program>$.<<Main>$>d__0.<>1__state"" IL_00ad: ldarg.0 IL_00ae: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder"" IL_00b3: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00b8: ret } "); } [Fact] public void NoAwaitInHoles_AwaitInExpression_UsesBuilder() { var source = @" using System; using System.Threading.Tasks; var hole = 2; Test(await M(1), $""base{hole}"", await M(3)); void Test(int i1, string s, int i2) => Console.WriteLine(s); Task<int> M(int i) { Console.WriteLine(i); return Task.FromResult(1); }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" 1 3 base value:2"); verifier.VerifyIL("<Program>$.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 328 (0x148) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int <Program>$.<<Main>$>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0050 IL_000a: ldloc.0 IL_000b: ldc.i4.1 IL_000c: beq IL_00dc IL_0011: ldarg.0 IL_0012: ldc.i4.2 IL_0013: stfld ""int <Program>$.<<Main>$>d__0.<hole>5__2"" IL_0018: ldc.i4.1 IL_0019: call ""System.Threading.Tasks.Task<int> <Program>$.<<Main>$>g__M|0_1(int)"" IL_001e: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0023: stloc.2 IL_0024: ldloca.s V_2 IL_0026: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_002b: brtrue.s IL_006c IL_002d: ldarg.0 IL_002e: ldc.i4.0 IL_002f: dup IL_0030: stloc.0 IL_0031: stfld ""int <Program>$.<<Main>$>d__0.<>1__state"" IL_0036: ldarg.0 IL_0037: ldloc.2 IL_0038: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1"" IL_003d: ldarg.0 IL_003e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder"" IL_0043: ldloca.s V_2 IL_0045: ldarg.0 IL_0046: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, <Program>$.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref <Program>$.<<Main>$>d__0)"" IL_004b: leave IL_0147 IL_0050: ldarg.0 IL_0051: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1"" IL_0056: stloc.2 IL_0057: ldarg.0 IL_0058: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1"" IL_005d: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0063: ldarg.0 IL_0064: ldc.i4.m1 IL_0065: dup IL_0066: stloc.0 IL_0067: stfld ""int <Program>$.<<Main>$>d__0.<>1__state"" IL_006c: ldarg.0 IL_006d: ldloca.s V_2 IL_006f: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0074: stfld ""int <Program>$.<<Main>$>d__0.<>7__wrap2"" IL_0079: ldarg.0 IL_007a: ldc.i4.4 IL_007b: ldc.i4.1 IL_007c: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0081: stloc.3 IL_0082: ldloca.s V_3 IL_0084: ldstr ""base"" IL_0089: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_008e: ldloca.s V_3 IL_0090: ldarg.0 IL_0091: ldfld ""int <Program>$.<<Main>$>d__0.<hole>5__2"" IL_0096: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_009b: ldloca.s V_3 IL_009d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_00a2: stfld ""string <Program>$.<<Main>$>d__0.<>7__wrap3"" IL_00a7: ldc.i4.3 IL_00a8: call ""System.Threading.Tasks.Task<int> <Program>$.<<Main>$>g__M|0_1(int)"" IL_00ad: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_00b2: stloc.2 IL_00b3: ldloca.s V_2 IL_00b5: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_00ba: brtrue.s IL_00f8 IL_00bc: ldarg.0 IL_00bd: ldc.i4.1 IL_00be: dup IL_00bf: stloc.0 IL_00c0: stfld ""int <Program>$.<<Main>$>d__0.<>1__state"" IL_00c5: ldarg.0 IL_00c6: ldloc.2 IL_00c7: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1"" IL_00cc: ldarg.0 IL_00cd: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder"" IL_00d2: ldloca.s V_2 IL_00d4: ldarg.0 IL_00d5: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, <Program>$.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref <Program>$.<<Main>$>d__0)"" IL_00da: leave.s IL_0147 IL_00dc: ldarg.0 IL_00dd: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1"" IL_00e2: stloc.2 IL_00e3: ldarg.0 IL_00e4: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1"" IL_00e9: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_00ef: ldarg.0 IL_00f0: ldc.i4.m1 IL_00f1: dup IL_00f2: stloc.0 IL_00f3: stfld ""int <Program>$.<<Main>$>d__0.<>1__state"" IL_00f8: ldloca.s V_2 IL_00fa: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_00ff: stloc.1 IL_0100: ldarg.0 IL_0101: ldfld ""int <Program>$.<<Main>$>d__0.<>7__wrap2"" IL_0106: ldarg.0 IL_0107: ldfld ""string <Program>$.<<Main>$>d__0.<>7__wrap3"" IL_010c: ldloc.1 IL_010d: call ""void <Program>$.<<Main>$>g__Test|0_0(int, string, int)"" IL_0112: ldarg.0 IL_0113: ldnull IL_0114: stfld ""string <Program>$.<<Main>$>d__0.<>7__wrap3"" IL_0119: leave.s IL_0134 } catch System.Exception { IL_011b: stloc.s V_4 IL_011d: ldarg.0 IL_011e: ldc.i4.s -2 IL_0120: stfld ""int <Program>$.<<Main>$>d__0.<>1__state"" IL_0125: ldarg.0 IL_0126: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder"" IL_012b: ldloc.s V_4 IL_012d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_0132: leave.s IL_0147 } IL_0134: ldarg.0 IL_0135: ldc.i4.s -2 IL_0137: stfld ""int <Program>$.<<Main>$>d__0.<>1__state"" IL_013c: ldarg.0 IL_013d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder"" IL_0142: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_0147: ret } "); } [Fact] public void MissingCreate_01() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public override string ToString() => throw null; public void Dispose() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 2 arguments // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 3 arguments // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "3").WithLocation(1, 5) ); } [Fact] public void MissingCreate_02() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(int literalLength) => throw null; public override string ToString() => throw null; public void Dispose() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 2 arguments // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 3 arguments // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "3").WithLocation(1, 5) ); } [Fact] public void MissingCreate_03() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(ref int literalLength, int formattedCount) => throw null; public override string ToString() => throw null; public void Dispose() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,5): error CS1620: Argument 1 must be passed with the 'ref' keyword // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadArgRef, @"$""{(object)1}""").WithArguments("1", "ref").WithLocation(1, 5) ); } [Theory] [InlineData(null)] [InlineData("public string ToStringAndClear(int literalLength) => throw null;")] [InlineData("public void ToStringAndClear() => throw null;")] [InlineData("public static string ToStringAndClear() => throw null;")] public void MissingWellKnownMethod_ToStringAndClear(string toStringAndClearMethod) { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null; " + toStringAndClearMethod + @" public override string ToString() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics(); comp.VerifyEmitDiagnostics( // (1,5): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear' // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "ToStringAndClear").WithLocation(1, 5) ); } [Fact] public void ObsoleteCreateMethod() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { [System.Obsolete(""Constructor is obsolete"", error: true)] public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null; public void Dispose() => throw null; public override string ToString() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,5): error CS0619: 'DefaultInterpolatedStringHandler.DefaultInterpolatedStringHandler(int, int)' is obsolete: 'Constructor is obsolete' // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.DefaultInterpolatedStringHandler(int, int)", "Constructor is obsolete").WithLocation(1, 5) ); } [Fact] public void ObsoleteAppendLiteralMethod() { var code = @"_ = $""base{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null; public void Dispose() => throw null; public override string ToString() => throw null; [System.Obsolete(""AppendLiteral is obsolete"", error: true)] public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,7): error CS0619: 'DefaultInterpolatedStringHandler.AppendLiteral(string)' is obsolete: 'AppendLiteral is obsolete' // _ = $"base{(object)1}"; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "base").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)", "AppendLiteral is obsolete").WithLocation(1, 7) ); } [Fact] public void ObsoleteAppendFormattedMethod() { var code = @"_ = $""base{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null; public void Dispose() => throw null; public override string ToString() => throw null; public void AppendLiteral(string value) => throw null; [System.Obsolete(""AppendFormatted is obsolete"", error: true)] public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,11): error CS0619: 'DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)' is obsolete: 'AppendFormatted is obsolete' // _ = $"base{(object)1}"; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "{(object)1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)", "AppendFormatted is obsolete").WithLocation(1, 11) ); } private const string UnmanagedCallersOnlyIl = @" .class public auto ansi sealed beforefieldinit System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute extends [mscorlib]System.Attribute { .custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = ( 01 00 40 00 00 00 01 00 54 02 09 49 6e 68 65 72 69 74 65 64 00 ) .field public class [mscorlib]System.Type[] CallConvs .field public string EntryPoint .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { ldarg.0 call instance void [mscorlib]System.Attribute::.ctor() ret } }"; [Fact] public void UnmanagedCallersOnlyAppendFormattedMethod() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" .class public sequential ansi sealed beforefieldinit System.Runtime.CompilerServices.DefaultInterpolatedStringHandler extends [mscorlib]System.ValueType { .custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void [mscorlib]System.ObsoleteAttribute::.ctor(string, bool) = ( 01 00 52 54 79 70 65 73 20 77 69 74 68 20 65 6d 62 65 64 64 65 64 20 72 65 66 65 72 65 6e 63 65 73 20 61 72 65 20 6e 6f 74 20 73 75 70 70 6f 72 74 65 64 20 69 6e 20 74 68 69 73 20 76 65 72 73 69 6f 6e 20 6f 66 20 79 6f 75 72 20 63 6f 6d 70 69 6c 65 72 2e 01 00 00 ) .pack 0 .size 1 .method public hidebysig specialname rtspecialname instance void .ctor ( int32 literalLength, int32 formattedCount ) cil managed { ldnull throw } .method public hidebysig instance void Dispose () cil managed { ldnull throw } .method public hidebysig virtual instance string ToString () cil managed { ldnull throw } .method public hidebysig instance void AppendLiteral ( string 'value' ) cil managed { ldnull throw } .method public hidebysig instance void AppendFormatted<T> ( !!T hole, [opt] int32 'alignment', [opt] string format ) cil managed { .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) .param [2] = int32(0) .param [3] = nullref ldnull throw } } "; var comp = CreateCompilationWithIL(code, ilSource: interpolatedStringBuilder + UnmanagedCallersOnlyIl); comp.VerifyDiagnostics( // (1,7): error CS0570: 'DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)' is not supported by the language // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BindToBogus, "{(object)1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)").WithLocation(1, 7) ); } [Fact] public void UnmanagedCallersOnlyToStringMethod() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" .class public sequential ansi sealed beforefieldinit System.Runtime.CompilerServices.DefaultInterpolatedStringHandler extends [mscorlib]System.ValueType { .custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void [mscorlib]System.ObsoleteAttribute::.ctor(string, bool) = ( 01 00 52 54 79 70 65 73 20 77 69 74 68 20 65 6d 62 65 64 64 65 64 20 72 65 66 65 72 65 6e 63 65 73 20 61 72 65 20 6e 6f 74 20 73 75 70 70 6f 72 74 65 64 20 69 6e 20 74 68 69 73 20 76 65 72 73 69 6f 6e 20 6f 66 20 79 6f 75 72 20 63 6f 6d 70 69 6c 65 72 2e 01 00 00 ) .pack 0 .size 1 .method public hidebysig specialname rtspecialname instance void .ctor ( int32 literalLength, int32 formattedCount ) cil managed { ldnull throw } .method public hidebysig instance string ToStringAndClear () cil managed { .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) ldnull throw } .method public hidebysig instance void AppendLiteral ( string 'value' ) cil managed { ldnull throw } .method public hidebysig instance void AppendFormatted<T> ( !!T hole, [opt] int32 'alignment', [opt] string format ) cil managed { .param [2] = int32(0) .param [3] = nullref ldnull throw } } "; var comp = CreateCompilationWithIL(code, ilSource: interpolatedStringBuilder + UnmanagedCallersOnlyIl); comp.VerifyDiagnostics(); comp.VerifyEmitDiagnostics( // (1,5): error CS0570: 'DefaultInterpolatedStringHandler.ToStringAndClear()' is not supported by the language // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BindToBogus, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()").WithLocation(1, 5) ); } [Fact] public void UnsupportedArgumentType() { var source = @" unsafe { int* i = null; var s = new S(); _ = $""{i}{s}""; } ref struct S { }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: true, useBoolReturns: false); var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, options: TestOptions.UnsafeReleaseExe, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (6,11): error CS0306: The type 'int*' may not be used as a type argument // _ = $"{i}{s}"; Diagnostic(ErrorCode.ERR_BadTypeArgument, "{i}").WithArguments("int*").WithLocation(6, 11), // (6,14): error CS0306: The type 'S' may not be used as a type argument // _ = $"{i}{s}"; Diagnostic(ErrorCode.ERR_BadTypeArgument, "{s}").WithArguments("S").WithLocation(6, 14) ); } [Fact] public void TargetTypedInterpolationHoles() { var source = @" bool b = true; System.Console.WriteLine($""{b switch { true => 1, false => null }}{(!b ? null : 2)}{default}{null}"");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" value:1 value:2 value: value:"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 81 (0x51) .maxstack 3 .locals init (bool V_0, //b object V_1, System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_2 IL_0004: ldc.i4.0 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloc.0 IL_000c: brfalse.s IL_0017 IL_000e: ldc.i4.1 IL_000f: box ""int"" IL_0014: stloc.1 IL_0015: br.s IL_0019 IL_0017: ldnull IL_0018: stloc.1 IL_0019: ldloca.s V_2 IL_001b: ldloc.1 IL_001c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)"" IL_0021: ldloca.s V_2 IL_0023: ldloc.0 IL_0024: brfalse.s IL_002e IL_0026: ldc.i4.2 IL_0027: box ""int"" IL_002c: br.s IL_002f IL_002e: ldnull IL_002f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)"" IL_0034: ldloca.s V_2 IL_0036: ldnull IL_0037: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_003c: ldloca.s V_2 IL_003e: ldnull IL_003f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0044: ldloca.s V_2 IL_0046: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_004b: call ""void System.Console.WriteLine(string)"" IL_0050: ret } "); } [Fact] public void TargetTypedInterpolationHoles_Errors() { var source = @"System.Console.WriteLine($""{(null, default)}{new()}"");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,29): error CS1503: Argument 1: cannot convert from '(<null>, default)' to 'object' // System.Console.WriteLine($"{(null, default)}{new()}"); Diagnostic(ErrorCode.ERR_BadArgType, "(null, default)").WithArguments("1", "(<null>, default)", "object").WithLocation(1, 29), // (1,29): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater. // System.Console.WriteLine($"{(null, default)}{new()}"); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(null, default)").WithArguments("interpolated string handlers", "10.0").WithLocation(1, 29), // (1,46): error CS1729: 'string' does not contain a constructor that takes 0 arguments // System.Console.WriteLine($"{(null, default)}{new()}"); Diagnostic(ErrorCode.ERR_BadCtorArgCount, "new()").WithArguments("string", "0").WithLocation(1, 46) ); } [Fact] public void RefTernary() { var source = @" bool b = true; int i = 1; System.Console.WriteLine($""{(!b ? ref i : ref i)}"");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"value:1"); } [Fact] public void NestedInterpolatedStrings() { var source = @" int i = 1; System.Console.WriteLine($""{$""{i}""}"");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"value:1"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 32 (0x20) .maxstack 3 .locals init (int V_0, //i System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.0 IL_0005: ldc.i4.1 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldloc.0 IL_000e: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0013: ldloca.s V_1 IL_0015: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_001a: call ""void System.Console.WriteLine(string)"" IL_001f: ret } "); } [Fact] public void ExceptionFilter_01() { var source = @" using System; int i = 1; try { Console.WriteLine(""Starting try""); throw new MyException { Prop = i }; } // Test DefaultInterpolatedStringHandler renders specially, so we're actually comparing to ""value:Prop"" plus some whitespace catch (MyException e) when (e.ToString() == $""{i}"".Trim()) { Console.WriteLine(""Caught""); } class MyException : Exception { public int Prop { get; set; } public override string ToString() => ""value:"" + Prop.ToString(); }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" Starting try Caught"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 95 (0x5f) .maxstack 4 .locals init (int V_0, //i System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 .try { IL_0002: ldstr ""Starting try"" IL_0007: call ""void System.Console.WriteLine(string)"" IL_000c: newobj ""MyException..ctor()"" IL_0011: dup IL_0012: ldloc.0 IL_0013: callvirt ""void MyException.Prop.set"" IL_0018: throw } filter { IL_0019: isinst ""MyException"" IL_001e: dup IL_001f: brtrue.s IL_0025 IL_0021: pop IL_0022: ldc.i4.0 IL_0023: br.s IL_004f IL_0025: callvirt ""string object.ToString()"" IL_002a: ldloca.s V_1 IL_002c: ldc.i4.0 IL_002d: ldc.i4.1 IL_002e: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0033: ldloca.s V_1 IL_0035: ldloc.0 IL_0036: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_003b: ldloca.s V_1 IL_003d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0042: callvirt ""string string.Trim()"" IL_0047: call ""bool string.op_Equality(string, string)"" IL_004c: ldc.i4.0 IL_004d: cgt.un IL_004f: endfilter } // end filter { // handler IL_0051: pop IL_0052: ldstr ""Caught"" IL_0057: call ""void System.Console.WriteLine(string)"" IL_005c: leave.s IL_005e } IL_005e: ret } "); } [ConditionalFact(typeof(MonoOrCoreClrOnly), typeof(NoIOperationValidation))] public void ExceptionFilter_02() { var source = @" using System; ReadOnlySpan<char> s = new char[] { 'i' }; try { Console.WriteLine(""Starting try""); throw new MyException { Prop = s.ToString() }; } // Test DefaultInterpolatedStringHandler renders specially, so we're actually comparing to ""value:Prop"" plus some whitespace catch (MyException e) when (e.ToString() == $""{s}"".Trim()) { Console.WriteLine(""Caught""); } class MyException : Exception { public string Prop { get; set; } public override string ToString() => ""value:"" + Prop.ToString(); }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, targetFramework: TargetFramework.NetCoreApp, expectedOutput: @" Starting try Caught"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 122 (0x7a) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //s System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: newarr ""char"" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 105 IL_000a: stelem.i2 IL_000b: call ""System.ReadOnlySpan<char> System.ReadOnlySpan<char>.op_Implicit(char[])"" IL_0010: stloc.0 .try { IL_0011: ldstr ""Starting try"" IL_0016: call ""void System.Console.WriteLine(string)"" IL_001b: newobj ""MyException..ctor()"" IL_0020: dup IL_0021: ldloca.s V_0 IL_0023: constrained. ""System.ReadOnlySpan<char>"" IL_0029: callvirt ""string object.ToString()"" IL_002e: callvirt ""void MyException.Prop.set"" IL_0033: throw } filter { IL_0034: isinst ""MyException"" IL_0039: dup IL_003a: brtrue.s IL_0040 IL_003c: pop IL_003d: ldc.i4.0 IL_003e: br.s IL_006a IL_0040: callvirt ""string object.ToString()"" IL_0045: ldloca.s V_1 IL_0047: ldc.i4.0 IL_0048: ldc.i4.1 IL_0049: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_004e: ldloca.s V_1 IL_0050: ldloc.0 IL_0051: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_0056: ldloca.s V_1 IL_0058: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005d: callvirt ""string string.Trim()"" IL_0062: call ""bool string.op_Equality(string, string)"" IL_0067: ldc.i4.0 IL_0068: cgt.un IL_006a: endfilter } // end filter { // handler IL_006c: pop IL_006d: ldstr ""Caught"" IL_0072: call ""void System.Console.WriteLine(string)"" IL_0077: leave.s IL_0079 } IL_0079: ret } "); } [ConditionalFact(typeof(MonoOrCoreClrOnly), typeof(NoIOperationValidation))] public void ImplicitUserDefinedConversionInHole() { var source = @" using System; S s = default; C c = new C(); Console.WriteLine($""{s}{c}""); ref struct S { public static implicit operator ReadOnlySpan<char>(S s) => ""S converted""; } class C { public static implicit operator ReadOnlySpan<char>(C s) => ""C converted""; }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false); var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:S converted value:C"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 57 (0x39) .maxstack 3 .locals init (S V_0, //s C V_1, //c System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_2) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: newobj ""C..ctor()"" IL_000d: stloc.1 IL_000e: ldloca.s V_2 IL_0010: ldc.i4.0 IL_0011: ldc.i4.2 IL_0012: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0017: ldloca.s V_2 IL_0019: ldloc.0 IL_001a: call ""System.ReadOnlySpan<char> S.op_Implicit(S)"" IL_001f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_0024: ldloca.s V_2 IL_0026: ldloc.1 IL_0027: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<C>(C)"" IL_002c: ldloca.s V_2 IL_002e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0033: call ""void System.Console.WriteLine(string)"" IL_0038: ret } "); } [Fact] public void ExplicitUserDefinedConversionInHole() { var source = @" using System; S s = default; Console.WriteLine($""{s}""); ref struct S { public static explicit operator ReadOnlySpan<char>(S s) => ""S converted""; } "; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false); var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (5,21): error CS0306: The type 'S' may not be used as a type argument // Console.WriteLine($"{s}"); Diagnostic(ErrorCode.ERR_BadTypeArgument, "{s}").WithArguments("S").WithLocation(5, 21) ); } [Fact] public void ImplicitUserDefinedConversionInLiteral() { var source = @" using System; Console.WriteLine($""Text{1}""); public struct CustomStruct { public static implicit operator CustomStruct(string s) => new CustomStruct { S = s }; public string S { get; set; } public override string ToString() => ""literal:"" + S; } namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public void AppendLiteral(CustomStruct s) => _builder.AppendLine(s.ToString()); public void AppendFormatted(object o) => _builder.AppendLine(""value:"" + o.ToString()); } }"; var verifier = CompileAndVerify(source, expectedOutput: @" literal:Text value:1"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 52 (0x34) .maxstack 3 .locals init (System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.1 IL_0004: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldstr ""Text"" IL_0010: call ""CustomStruct CustomStruct.op_Implicit(string)"" IL_0015: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(CustomStruct)"" IL_001a: ldloca.s V_0 IL_001c: ldc.i4.1 IL_001d: box ""int"" IL_0022: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)"" IL_0027: ldloca.s V_0 IL_0029: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_002e: call ""void System.Console.WriteLine(string)"" IL_0033: ret } "); } [Fact] public void ExplicitUserDefinedConversionInLiteral() { var source = @" using System; Console.WriteLine($""Text{1}""); public struct CustomStruct { public static explicit operator CustomStruct(string s) => new CustomStruct { S = s }; public string S { get; set; } public override string ToString() => ""literal:"" + S; } namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public void AppendLiteral(CustomStruct s) => _builder.AppendLine(s.ToString()); public void AppendFormatted(object o) => _builder.AppendLine(""value:"" + o.ToString()); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,21): error CS1503: Argument 1: cannot convert from 'string' to 'CustomStruct' // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_BadArgType, "Text").WithArguments("1", "string", "CustomStruct").WithLocation(4, 21) ); } [Fact] public void InvalidBuilderReturnType() { var source = @" using System; Console.WriteLine($""Text{1}""); namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public int AppendLiteral(string s) => 0; public int AppendFormatted(object o) => 0; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,21): error CS8941: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendLiteral(string)' is malformed. It does not return 'void' or 'bool'. // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "Text").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)").WithLocation(4, 21), // (4,25): error CS8941: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendFormatted(object)' is malformed. It does not return 'void' or 'bool'. // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "{1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)").WithLocation(4, 25) ); } [Fact] public void MixedBuilderReturnTypes_01() { var source = @" using System; Console.WriteLine($""Text{1}""); Console.WriteLine($""{1}Text""); namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public bool AppendLiteral(string s) => true; public void AppendFormatted(object o) { } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,25): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendFormatted(object)' has inconsistent return type. Expected to return 'bool'. // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "{1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)", "bool").WithLocation(4, 25), // (5,24): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendLiteral(string)' has inconsistent return type. Expected to return 'void'. // Console.WriteLine($"{1}Text"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "Text").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)", "void").WithLocation(5, 24) ); } [Fact] public void MixedBuilderReturnTypes_02() { var source = @" using System; Console.WriteLine($""Text{1}""); Console.WriteLine($""{1}Text""); namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public void AppendLiteral(string s) { } public bool AppendFormatted(object o) => true; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,25): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendFormatted(object)' has inconsistent return type. Expected to return 'void'. // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "{1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)", "void").WithLocation(4, 25), // (5,24): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendLiteral(string)' has inconsistent return type. Expected to return 'bool'. // Console.WriteLine($"{1}Text"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "Text").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)", "bool").WithLocation(5, 24) ); } [Fact] public void MixedBuilderReturnTypes_03() { var source = @" using System; Console.WriteLine($""{1}""); namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public bool AppendLiteral(string s) => true; public void AppendFormatted(object o) { _builder.AppendLine(""value:"" + o.ToString()); } } }"; CompileAndVerify(source, expectedOutput: "value:1"); } [Fact] public void MixedBuilderReturnTypes_04() { var source = @" using System; using System.Text; using System.Runtime.CompilerServices; Console.WriteLine((CustomHandler)$""l""); [InterpolatedStringHandler] public class CustomHandler { private readonly StringBuilder _builder; public CustomHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public override string ToString() => _builder.ToString(); public bool AppendFormatted(object o) => true; public void AppendLiteral(string s) { _builder.AppendLine(""literal:"" + s.ToString()); } } "; CompileAndVerify(new[] { source, InterpolatedStringHandlerAttribute }, expectedOutput: "literal:l"); } private static void VerifyInterpolatedStringExpression(CSharpCompilation comp, string handlerType = "CustomHandler") { var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var interpolatedString = tree.GetRoot().DescendantNodes().OfType<InterpolatedStringExpressionSyntax>().Single(); var semanticInfo = model.GetSemanticInfoSummary(interpolatedString); Assert.Equal(SpecialType.System_String, semanticInfo.Type.SpecialType); Assert.Equal(handlerType, semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.InterpolatedStringHandler, semanticInfo.ImplicitConversion.Kind); Assert.True(semanticInfo.ImplicitConversion.Exists); Assert.True(semanticInfo.ImplicitConversion.IsValid); Assert.True(semanticInfo.ImplicitConversion.IsInterpolatedStringHandler); Assert.Null(semanticInfo.ImplicitConversion.Method); // https://github.com/dotnet/roslyn/issues/54505 Assert IConversionOperation.IsImplicit when IOperation is implemented for interpolated strings. } private CompilationVerifier CompileAndVerifyOnCorrectPlatforms(CSharpCompilation compilation, string expectedOutput) => CompileAndVerify( compilation, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expectedOutput : null, verify: ExecutionConditionUtil.IsMonoOrCoreClr ? Verification.Passes : Verification.Skipped); [Theory] [CombinatorialData] public void CustomHandlerLocal([CombinatorialValues("class", "struct")] string type, bool useBoolReturns) { var code = @" CustomHandler builder = $""Literal{1,2:f}""; System.Console.WriteLine(builder.ToString());"; var builder = GetInterpolatedStringCustomHandlerType("CustomHandler", type, useBoolReturns); var comp = CreateCompilation(new[] { code, builder }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" literal:Literal value:1 alignment:2 format:f"); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (type, useBoolReturns) switch { (type: "struct", useBoolReturns: true) => @" { // Code size 67 (0x43) .maxstack 4 .locals init (CustomHandler V_0, //builder CustomHandler V_1) IL_0000: ldloca.s V_1 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_1 IL_000b: ldstr ""Literal"" IL_0010: call ""bool CustomHandler.AppendLiteral(string)"" IL_0015: brfalse.s IL_002c IL_0017: ldloca.s V_1 IL_0019: ldc.i4.1 IL_001a: box ""int"" IL_001f: ldc.i4.2 IL_0020: ldstr ""f"" IL_0025: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_002a: br.s IL_002d IL_002c: ldc.i4.0 IL_002d: pop IL_002e: ldloc.1 IL_002f: stloc.0 IL_0030: ldloca.s V_0 IL_0032: constrained. ""CustomHandler"" IL_0038: callvirt ""string object.ToString()"" IL_003d: call ""void System.Console.WriteLine(string)"" IL_0042: ret } ", (type: "struct", useBoolReturns: false) => @" { // Code size 61 (0x3d) .maxstack 4 .locals init (CustomHandler V_0, //builder CustomHandler V_1) IL_0000: ldloca.s V_1 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_1 IL_000b: ldstr ""Literal"" IL_0010: call ""void CustomHandler.AppendLiteral(string)"" IL_0015: ldloca.s V_1 IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: ldc.i4.2 IL_001e: ldstr ""f"" IL_0023: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0028: ldloc.1 IL_0029: stloc.0 IL_002a: ldloca.s V_0 IL_002c: constrained. ""CustomHandler"" IL_0032: callvirt ""string object.ToString()"" IL_0037: call ""void System.Console.WriteLine(string)"" IL_003c: ret } ", (type: "class", useBoolReturns: true) => @" { // Code size 55 (0x37) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""Literal"" IL_000e: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0013: brfalse.s IL_0029 IL_0015: ldloc.0 IL_0016: ldc.i4.1 IL_0017: box ""int"" IL_001c: ldc.i4.2 IL_001d: ldstr ""f"" IL_0022: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: callvirt ""string object.ToString()"" IL_0031: call ""void System.Console.WriteLine(string)"" IL_0036: ret } ", (type: "class", useBoolReturns: false) => @" { // Code size 47 (0x2f) .maxstack 5 IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: dup IL_0008: ldstr ""Literal"" IL_000d: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0012: dup IL_0013: ldc.i4.1 IL_0014: box ""int"" IL_0019: ldc.i4.2 IL_001a: ldstr ""f"" IL_001f: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0024: callvirt ""string object.ToString()"" IL_0029: call ""void System.Console.WriteLine(string)"" IL_002e: ret } ", _ => throw ExceptionUtilities.Unreachable }; } [Fact] public void CustomHandlerMethodArgument() { var code = @" M($""{1,2:f}Literal""); void M(CustomHandler b) { System.Console.WriteLine(b.ToString()); }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"<top-level-statements-entry-point>", @" { // Code size 50 (0x32) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: call ""void <Program>$.<<Main>$>g__M|0_0(CustomHandler)"" IL_0031: ret } "); } [Fact] public void ExplicitHandlerCast_InCode() { var code = @"System.Console.WriteLine((CustomHandler)$""{1,2:f}Literal"");"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: false) }); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); SyntaxNode syntax = tree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().Single(); var semanticInfo = model.GetSemanticInfoSummary(syntax); Assert.Equal("CustomHandler", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(SpecialType.System_Object, semanticInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind); syntax = ((CastExpressionSyntax)syntax).Expression; Assert.IsType<InterpolatedStringExpressionSyntax>(syntax); semanticInfo = model.GetSemanticInfoSummary(syntax); Assert.Equal(SpecialType.System_String, semanticInfo.Type.SpecialType); Assert.Equal(SpecialType.System_String, semanticInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); // https://github.com/dotnet/roslyn/issues/54505 Assert cast is explicit after IOperation is implemented var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 42 (0x2a) .maxstack 5 IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: dup IL_0008: ldc.i4.1 IL_0009: box ""int"" IL_000e: ldc.i4.2 IL_000f: ldstr ""f"" IL_0014: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0019: dup IL_001a: ldstr ""Literal"" IL_001f: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0024: call ""void System.Console.WriteLine(object)"" IL_0029: ret } "); } [Fact] public void HandlerConversionPreferredOverStringForNonConstant() { var code = @" C.M($""{1,2:f}Literal""); class C { public static void M(CustomHandler b) { System.Console.WriteLine(b.ToString()); } public static void M(string s) { throw null; } } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"<top-level-statements-entry-point>", @" { // Code size 50 (0x32) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: call ""void C.M(CustomHandler)"" IL_0031: ret } "); } [Fact] public void StringPreferredOverHandlerConversionForConstant() { var code = @" C.M($""{""Literal""}""); class C { public static void M(CustomHandler b) { throw null; } public static void M(string s) { System.Console.WriteLine(s); } } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); var verifier = CompileAndVerify(comp, expectedOutput: @"Literal"); verifier.VerifyIL(@"<top-level-statements-entry-point>", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldstr ""Literal"" IL_0005: call ""void C.M(string)"" IL_000a: ret } "); } [Fact] public void HandlerConversionPreferredOverStringForNonConstant_AttributeConstructor() { var code = @" using System; [Attr($""{1}"")] class Attr : Attribute { public Attr(string s) {} public Attr(CustomHandler c) {} } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); comp.VerifyDiagnostics( // (4,2): error CS0181: Attribute constructor parameter 'c' has type 'CustomHandler', which is not a valid attribute parameter type // [Attr($"{1}")] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "Attr").WithArguments("c", "CustomHandler").WithLocation(4, 2) ); VerifyInterpolatedStringExpression(comp); var attr = comp.SourceAssembly.SourceModule.GlobalNamespace.GetTypeMember("Attr"); Assert.Equal("Attr..ctor(CustomHandler c)", attr.GetAttributes().Single().AttributeConstructor.ToTestDisplayString()); } [Fact] public void StringPreferredOverHandlerConversionForConstant_AttributeConstructor() { var code = @" using System; [Attr($""{""Literal""}"")] class Attr : Attribute { public Attr(string s) {} public Attr(CustomHandler c) {} } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); CompileAndVerify(comp, symbolValidator: validate, sourceSymbolValidator: validate); void validate(ModuleSymbol m) { var attr = m.GlobalNamespace.GetTypeMember("Attr"); Assert.Equal("Attr..ctor(System.String s)", attr.GetAttributes().Single().AttributeConstructor.ToTestDisplayString()); } } [Fact] public void MultipleBuilderTypes() { var code = @" C.M($""""); class C { public static void M(CustomHandler1 c) => throw null; public static void M(CustomHandler2 c) => throw null; }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler1", "struct", useBoolReturns: false), GetInterpolatedStringCustomHandlerType("CustomHandler2", "struct", useBoolReturns: false, includeOneTimeHelpers: false) }); comp.VerifyDiagnostics( // (2,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(CustomHandler1)' and 'C.M(CustomHandler2)' // C.M($""); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(CustomHandler1)", "C.M(CustomHandler2)").WithLocation(2, 3) ); } [Fact] public void GenericOverloadResolution_01() { var code = @" using System; C.M($""{1,2:f}Literal""); class C { public static void M<T>(T t) => throw null; public static void M(CustomHandler c) => Console.WriteLine(c); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 50 (0x32) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: call ""void C.M(CustomHandler)"" IL_0031: ret } "); } [Fact] public void GenericOverloadResolution_02() { var code = @" using System; C.M($""{1,2:f}Literal""); class C { public static void M<T>(T t) where T : CustomHandler => throw null; public static void M(CustomHandler c) => Console.WriteLine(c); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 50 (0x32) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: call ""void C.M(CustomHandler)"" IL_0031: ret } "); } [Fact] public void GenericOverloadResolution_03() { var code = @" C.M($""{1,2:f}Literal""); class C { public static void M<T>(T t) where T : CustomHandler => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); comp.VerifyDiagnostics( // (2,3): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'C.M<T>(T)'. There is no implicit reference conversion from 'string' to 'CustomHandler'. // C.M($"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "M").WithArguments("C.M<T>(T)", "CustomHandler", "T", "string").WithLocation(2, 3) ); } [Fact] public void GenericInference_01() { var code = @" C.M($""{1,2:f}Literal"", default(CustomHandler)); C.M(default(CustomHandler), $""{1,2:f}Literal""); class C { public static void M<T>(T t1, T t2) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (2,3): error CS0411: The type arguments for method 'C.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // C.M($"{1,2:f}Literal", default(CustomHandler)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, T)").WithLocation(2, 3), // (3,3): error CS0411: The type arguments for method 'C.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // C.M(default(CustomHandler), $"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, T)").WithLocation(3, 3) ); } [Fact] public void GenericInference_02() { var code = @" using System; C.M(default(CustomHandler), () => $""{1,2:f}Literal""); class C { public static void M<T>(T t1, Func<T> t2) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); comp.VerifyDiagnostics( // (3,3): error CS0411: The type arguments for method 'C.M<T>(T, Func<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // C.M(default(CustomHandler), () => $"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, System.Func<T>)").WithLocation(3, 3) ); } [Fact] public void GenericInference_03() { var code = @" using System; C.M($""{1,2:f}Literal"", default(CustomHandler)); class C { public static void M<T>(T t1, T t2) => Console.WriteLine(t1); } partial class CustomHandler { public static implicit operator CustomHandler(string s) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 51 (0x33) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: ldnull IL_002d: call ""void C.M<CustomHandler>(CustomHandler, CustomHandler)"" IL_0032: ret } "); } [Fact] public void GenericInference_04() { var code = @" using System; C.M(default(CustomHandler), () => $""{1,2:f}Literal""); class C { public static void M<T>(T t1, Func<T> t2) => Console.WriteLine(t2()); } partial class CustomHandler { public static implicit operator CustomHandler(string s) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<Program>$.<>c.<<Main>$>b__0_0()", @" { // Code size 45 (0x2d) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: ret } "); } [Fact] public void LambdaReturnInference_01() { var code = @" using System; Func<CustomHandler> f = () => $""{1,2:f}Literal""; Console.WriteLine(f()); "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"<Program>$.<>c.<<Main>$>b__0_0()", @" { // Code size 45 (0x2d) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: ret } "); } [Fact] public void LambdaReturnInference_02() { var code = @" using System; CultureInfoNormalizer.Normalize(); C.M(() => $""{1,2:f}Literal""); class C { public static void M(Func<string> f) => Console.WriteLine(f()); public static void M(Func<CustomHandler> f) => throw null; } "; // Interpolated string handler conversions are not considered when determining the natural type of an expression: the natural return type of this lambda is string, // so we don't even consider that there is a conversion from interpolated string expression to CustomHandler here (Sections 12.6.3.13 and 12.6.3.15 of the spec). var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); var verifier = CompileAndVerify(comp, expectedOutput: @"1.00Literal"); // No DefaultInterpolatedStringHandler was included in the compilation, so it falls back to string.Format verifier.VerifyIL(@"<Program>$.<>c.<<Main>$>b__0_0()", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: ldstr ""{0,2:f}Literal"" IL_0005: ldc.i4.1 IL_0006: box ""int"" IL_000b: call ""string string.Format(string, object)"" IL_0010: ret } "); } [Fact] public void LambdaReturnInference_03() { // Same as 2, but using a type that isn't allowed in an interpolated string. There is an implicit conversion error on the ref struct // when converting to a string, because S cannot be a component of an interpolated string. This conversion error causes the lambda to // fail to bind as Func<string>, even though the natural return type is string, and the only successful bind is Func<CustomHandler>. var code = @" using System; C.M(() => $""{new S { Field = ""Field"" }}""); static class C { public static void M(Func<string> f) => throw null; public static void M(Func<CustomHandler> f) => Console.WriteLine(f()); } public partial class CustomHandler { public void AppendFormatted(S value) => _builder.AppendLine(""value:"" + value.Field); } public ref struct S { public string Field { get; set; } } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"value:Field"); verifier.VerifyIL(@"<Program>$.<>c.<<Main>$>b__0_0()", @" { // Code size 35 (0x23) .maxstack 4 .locals init (S V_0) IL_0000: ldc.i4.0 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: dup IL_0008: ldloca.s V_0 IL_000a: initobj ""S"" IL_0010: ldloca.s V_0 IL_0012: ldstr ""Field"" IL_0017: call ""void S.Field.set"" IL_001c: ldloc.0 IL_001d: callvirt ""void CustomHandler.AppendFormatted(S)"" IL_0022: ret } "); } [Fact] public void LambdaReturnInference_04() { // Same as 3, but with S added to DefaultInterpolatedStringHandler (which then allows the lambda to be bound as Func<string>, matching the natural return type) var code = @" using System; C.M(() => $""{new S { Field = ""Field"" }}""); static class C { public static void M(Func<string> f) => Console.WriteLine(f()); public static void M(Func<CustomHandler> f) => throw null; } public partial class CustomHandler { public void AppendFormatted(S value) => throw null; } public ref struct S { public string Field { get; set; } } namespace System.Runtime.CompilerServices { public ref partial struct DefaultInterpolatedStringHandler { public void AppendFormatted(S value) => _builder.AppendLine(""value:"" + value.Field); } } "; string[] source = new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: false), GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: true, useBoolReturns: false) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (3,11): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater. // C.M(() => $"{new S { Field = "Field" }}"); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, @"$""{new S { Field = ""Field"" }}""").WithArguments("interpolated string handlers", "10.0").WithLocation(3, 11), // (3,14): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater. // C.M(() => $"{new S { Field = "Field" }}"); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, @"new S { Field = ""Field"" }").WithArguments("interpolated string handlers", "10.0").WithLocation(3, 14) ); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"value:Field"); verifier.VerifyIL(@"<Program>$.<>c.<<Main>$>b__0_0()", @" { // Code size 45 (0x2d) .maxstack 3 .locals init (System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_0, S V_1) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.0 IL_0003: ldc.i4.1 IL_0004: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldloca.s V_1 IL_000d: initobj ""S"" IL_0013: ldloca.s V_1 IL_0015: ldstr ""Field"" IL_001a: call ""void S.Field.set"" IL_001f: ldloc.1 IL_0020: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(S)"" IL_0025: ldloca.s V_0 IL_0027: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_002c: ret } "); } [Fact] public void LambdaReturnInference_05() { var code = @" using System; C.M(b => { if (b) return default(CustomHandler); else return $""{1,2:f}Literal""; }); static class C { public static void M(Func<bool, string> f) => throw null; public static void M(Func<bool, CustomHandler> f) => Console.WriteLine(f(false)); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"<Program>$.<>c.<<Main>$>b__0_0(bool)", @" { // Code size 55 (0x37) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldarg.1 IL_0001: brfalse.s IL_000d IL_0003: ldloca.s V_0 IL_0005: initobj ""CustomHandler"" IL_000b: ldloc.0 IL_000c: ret IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: ret } "); } [Fact] public void LambdaReturnInference_06() { // Same as 5, but with an implicit conversion from the builder type to string. This implicit conversion // means that a best common type can be inferred for all branches of the lambda expression (Section 12.6.3.15 of the spec) // and because there is a best common type, the inferred return type of the lambda is string. Since the inferred return type // has an identity conversion to the return type of Func<bool, string>, that is preferred. var code = @" using System; CultureInfoNormalizer.Normalize(); C.M(b => { if (b) return default(CustomHandler); else return $""{1,2:f}Literal""; }); static class C { public static void M(Func<bool, string> f) => Console.WriteLine(f(false)); public static void M(Func<bool, CustomHandler> f) => throw null; } public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"1.00Literal"); verifier.VerifyIL(@"<Program>$.<>c.<<Main>$>b__0_0(bool)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (CustomHandler V_0) IL_0000: ldarg.1 IL_0001: brfalse.s IL_0012 IL_0003: ldloca.s V_0 IL_0005: initobj ""CustomHandler"" IL_000b: ldloc.0 IL_000c: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0011: ret IL_0012: ldstr ""{0,2:f}Literal"" IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: call ""string string.Format(string, object)"" IL_0022: ret } "); } [Fact] public void LambdaReturnInference_07() { // Same as 5, but with an implicit conversion from string to the builder type. var code = @" using System; C.M(b => { if (b) return default(CustomHandler); else return $""{1,2:f}Literal""; }); static class C { public static void M(Func<bool, string> f) => Console.WriteLine(f(false)); public static void M(Func<bool, CustomHandler> f) => Console.WriteLine(f(false)); } public partial struct CustomHandler { public static implicit operator CustomHandler(string s) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"<Program>$.<>c.<<Main>$>b__0_0(bool)", @" { // Code size 55 (0x37) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldarg.1 IL_0001: brfalse.s IL_000d IL_0003: ldloca.s V_0 IL_0005: initobj ""CustomHandler"" IL_000b: ldloc.0 IL_000c: ret IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: ret } "); } [Fact] public void LambdaReturnInference_08() { // Same as 5, but with an implicit conversion from the builder type to string and from string to the builder type. var code = @" using System; C.M(b => { if (b) return default(CustomHandler); else return $""{1,2:f}Literal""; }); static class C { public static void M(Func<bool, string> f) => Console.WriteLine(f(false)); public static void M(Func<bool, CustomHandler> f) => throw null; } public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; public static implicit operator CustomHandler(string c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (3,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(Func<bool, string>)' and 'C.M(Func<bool, CustomHandler>)' // C.M(b => Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(System.Func<bool, string>)", "C.M(System.Func<bool, CustomHandler>)").WithLocation(3, 3) ); } [Fact] public void LambdaInference_AmbiguousInOlderLangVersions() { var code = @" using System; C.M(param => { param = $""{1}""; }); static class C { public static void M(Action<string> f) => throw null; public static void M(Action<CustomHandler> f) => throw null; } "; var source = new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); // This successful emit is being caused by https://github.com/dotnet/roslyn/issues/53761, along with the duplicate diagnostics in LambdaReturnInference_04 // We should not be changing binding behavior based on LangVersion. comp.VerifyEmitDiagnostics(); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (3,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(Action<string>)' and 'C.M(Action<CustomHandler>)' // C.M(param => Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(System.Action<string>)", "C.M(System.Action<CustomHandler>)").WithLocation(3, 3) ); } [Fact] public void TernaryTypes_01() { var code = @" using System; var x = (bool)(object)false ? default(CustomHandler) : $""{1,2:f}Literal""; Console.WriteLine(x); "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 76 (0x4c) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brtrue.s IL_0038 IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: br.s IL_0041 IL_0038: ldloca.s V_0 IL_003a: initobj ""CustomHandler"" IL_0040: ldloc.0 IL_0041: box ""CustomHandler"" IL_0046: call ""void System.Console.WriteLine(object)"" IL_004b: ret } "); } [Fact] public void TernaryTypes_02() { // Same as 01, but with a conversion from CustomHandler to string. The rules here are similar to LambdaReturnInference_06 var code = @" using System; CultureInfoNormalizer.Normalize(); var x = (bool)(object)false ? default(CustomHandler) : $""{1,2:f}Literal""; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"1.00Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 56 (0x38) .maxstack 2 .locals init (CustomHandler V_0) IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldc.i4.0 IL_0006: box ""bool"" IL_000b: unbox.any ""bool"" IL_0010: brtrue.s IL_0024 IL_0012: ldstr ""{0,2:f}Literal"" IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: call ""string string.Format(string, object)"" IL_0022: br.s IL_0032 IL_0024: ldloca.s V_0 IL_0026: initobj ""CustomHandler"" IL_002c: ldloc.0 IL_002d: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0032: call ""void System.Console.WriteLine(string)"" IL_0037: ret } "); } [Fact] public void TernaryTypes_03() { // Same as 02, but with a target-type var code = @" using System; CustomHandler x = (bool)(object)false ? default(CustomHandler) : $""{1,2:f}Literal""; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,19): error CS0029: Cannot implicitly convert type 'string' to 'CustomHandler' // CustomHandler x = (bool)(object)false ? default(CustomHandler) : $"{1,2:f}Literal"; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"(bool)(object)false ? default(CustomHandler) : $""{1,2:f}Literal""").WithArguments("string", "CustomHandler").WithLocation(4, 19) ); } [Fact] public void TernaryTypes_04() { // Same 01, but with a conversion from string to CustomHandler. The rules here are similar to LambdaReturnInference_07 var code = @" using System; var x = (bool)(object)false ? default(CustomHandler) : $""{1,2:f}Literal""; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 76 (0x4c) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brtrue.s IL_0038 IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: br.s IL_0041 IL_0038: ldloca.s V_0 IL_003a: initobj ""CustomHandler"" IL_0040: ldloc.0 IL_0041: box ""CustomHandler"" IL_0046: call ""void System.Console.WriteLine(object)"" IL_004b: ret } "); } [Fact] public void TernaryTypes_05() { // Same 01, but with a conversion from string to CustomHandler and CustomHandler to string. var code = @" using System; var x = (bool)(object)false ? default(CustomHandler) : $""{1,2:f}Literal""; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,9): error CS0172: Type of conditional expression cannot be determined because 'CustomHandler' and 'string' implicitly convert to one another // var x = (bool)(object)false ? default(CustomHandler) : $"{1,2:f}Literal"; Diagnostic(ErrorCode.ERR_AmbigQM, @"(bool)(object)false ? default(CustomHandler) : $""{1,2:f}Literal""").WithArguments("CustomHandler", "string").WithLocation(4, 9) ); } [Fact] public void TernaryTypes_06() { // Same 05, but with a target type var code = @" using System; CustomHandler x = (bool)(object)false ? default(CustomHandler) : $""{1,2:f}Literal""; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; public static implicit operator string(CustomHandler c) => c.ToString(); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 76 (0x4c) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brtrue.s IL_0038 IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: br.s IL_0041 IL_0038: ldloca.s V_0 IL_003a: initobj ""CustomHandler"" IL_0040: ldloc.0 IL_0041: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0046: call ""void System.Console.WriteLine(string)"" IL_004b: ret } "); } [Fact] public void SwitchTypes_01() { // Switch expressions infer a best type based on _types_, not based on expressions (section 12.6.3.15 of the spec). Because this is based on types // and not on expression conversions, no best type can be found for this switch expression. var code = @" using System; var x = (bool)(object)false switch { true => default(CustomHandler), false => $""{1,2:f}Literal"" }; Console.WriteLine(x); "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,29): error CS8506: No best type was found for the switch expression. // var x = (bool)(object)false switch { true => default(CustomHandler), false => $"{1,2:f}Literal" }; Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(4, 29) ); } [Fact] public void SwitchTypes_02() { // Same as 01, but with a conversion from CustomHandler. This allows the switch expression to infer a best-common type, which is string. var code = @" using System; CultureInfoNormalizer.Normalize(); var x = (bool)(object)false switch { true => default(CustomHandler), false => $""{1,2:f}Literal"" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"1.00Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 59 (0x3b) .maxstack 2 .locals init (string V_0, CustomHandler V_1) IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldc.i4.0 IL_0006: box ""bool"" IL_000b: unbox.any ""bool"" IL_0010: brfalse.s IL_0023 IL_0012: ldloca.s V_1 IL_0014: initobj ""CustomHandler"" IL_001a: ldloc.1 IL_001b: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0020: stloc.0 IL_0021: br.s IL_0034 IL_0023: ldstr ""{0,2:f}Literal"" IL_0028: ldc.i4.1 IL_0029: box ""int"" IL_002e: call ""string string.Format(string, object)"" IL_0033: stloc.0 IL_0034: ldloc.0 IL_0035: call ""void System.Console.WriteLine(string)"" IL_003a: ret } "); } [Fact] public void SwitchTypes_03() { // Same 02, but with a target-type. The natural type will fail to compile, so the switch will use a target type (unlike TernaryTypes_03, which fails to compile). var code = @" using System; CustomHandler x = (bool)(object)false switch { true => default(CustomHandler), false => $""{1,2:f}Literal"" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => c.ToString(); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 79 (0x4f) .maxstack 4 .locals init (CustomHandler V_0, CustomHandler V_1) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brfalse.s IL_0019 IL_000d: ldloca.s V_1 IL_000f: initobj ""CustomHandler"" IL_0015: ldloc.1 IL_0016: stloc.0 IL_0017: br.s IL_0043 IL_0019: ldloca.s V_1 IL_001b: ldc.i4.7 IL_001c: ldc.i4.1 IL_001d: call ""CustomHandler..ctor(int, int)"" IL_0022: ldloca.s V_1 IL_0024: ldc.i4.1 IL_0025: box ""int"" IL_002a: ldc.i4.2 IL_002b: ldstr ""f"" IL_0030: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0035: ldloca.s V_1 IL_0037: ldstr ""Literal"" IL_003c: call ""void CustomHandler.AppendLiteral(string)"" IL_0041: ldloc.1 IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0049: call ""void System.Console.WriteLine(string)"" IL_004e: ret } "); } [Fact] public void SwitchTypes_04() { // Same as 01, but with a conversion to CustomHandler. This allows the switch expression to infer a best-common type, which is CustomHandler. var code = @" using System; var x = (bool)(object)false switch { true => default(CustomHandler), false => $""{1,2:f}Literal"" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 79 (0x4f) .maxstack 4 .locals init (CustomHandler V_0, CustomHandler V_1) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brfalse.s IL_0019 IL_000d: ldloca.s V_1 IL_000f: initobj ""CustomHandler"" IL_0015: ldloc.1 IL_0016: stloc.0 IL_0017: br.s IL_0043 IL_0019: ldloca.s V_1 IL_001b: ldc.i4.7 IL_001c: ldc.i4.1 IL_001d: call ""CustomHandler..ctor(int, int)"" IL_0022: ldloca.s V_1 IL_0024: ldc.i4.1 IL_0025: box ""int"" IL_002a: ldc.i4.2 IL_002b: ldstr ""f"" IL_0030: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0035: ldloca.s V_1 IL_0037: ldstr ""Literal"" IL_003c: call ""void CustomHandler.AppendLiteral(string)"" IL_0041: ldloc.1 IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: box ""CustomHandler"" IL_0049: call ""void System.Console.WriteLine(object)"" IL_004e: ret } "); } [Fact] public void SwitchTypes_05() { // Same as 01, but with conversions in both directions. No best common type can be found. var code = @" using System; var x = (bool)(object)false switch { true => default(CustomHandler), false => $""{1,2:f}Literal"" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,29): error CS8506: No best type was found for the switch expression. // var x = (bool)(object)false switch { true => default(CustomHandler), false => $"{1,2:f}Literal" }; Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(4, 29) ); } [Fact] public void SwitchTypes_06() { // Same as 05, but with a target type. var code = @" using System; CustomHandler x = (bool)(object)false switch { true => default(CustomHandler), false => $""{1,2:f}Literal"" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; public static implicit operator string(CustomHandler c) => c.ToString(); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 79 (0x4f) .maxstack 4 .locals init (CustomHandler V_0, CustomHandler V_1) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brfalse.s IL_0019 IL_000d: ldloca.s V_1 IL_000f: initobj ""CustomHandler"" IL_0015: ldloc.1 IL_0016: stloc.0 IL_0017: br.s IL_0043 IL_0019: ldloca.s V_1 IL_001b: ldc.i4.7 IL_001c: ldc.i4.1 IL_001d: call ""CustomHandler..ctor(int, int)"" IL_0022: ldloca.s V_1 IL_0024: ldc.i4.1 IL_0025: box ""int"" IL_002a: ldc.i4.2 IL_002b: ldstr ""f"" IL_0030: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0035: ldloca.s V_1 IL_0037: ldstr ""Literal"" IL_003c: call ""void CustomHandler.AppendLiteral(string)"" IL_0041: ldloc.1 IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0049: call ""void System.Console.WriteLine(string)"" IL_004e: ret } "); } [Fact] public void PassAsRefWithoutKeyword_01() { var code = @" M($""{1,2:f}Literal""); void M(ref CustomHandler c) => System.Console.WriteLine(c);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 48 (0x30) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_0 IL_002a: call ""void <Program>$.<<Main>$>g__M|0_0(ref CustomHandler)"" IL_002f: ret } "); } [Fact] public void PassAsRefWithoutKeyword_02() { var code = @" M($""{1,2:f}Literal""); M(ref $""{1,2:f}Literal""); void M(ref CustomHandler c) => System.Console.WriteLine(c);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (2,3): error CS1620: Argument 1 must be passed with the 'ref' keyword // M($"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_BadArgRef, @"$""{1,2:f}Literal""").WithArguments("1", "ref").WithLocation(2, 3), // (3,7): error CS1510: A ref or out value must be an assignable variable // M(ref $"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_RefLvalueExpected, @"$""{1,2:f}Literal""").WithLocation(3, 7) ); } [Fact] public void PassAsRefWithoutKeyword_03() { var code = @" M($""{1,2:f}Literal""); void M(in CustomHandler c) => System.Console.WriteLine(c);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 45 (0x2d) .maxstack 5 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: dup IL_0008: ldc.i4.1 IL_0009: box ""int"" IL_000e: ldc.i4.2 IL_000f: ldstr ""f"" IL_0014: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0019: dup IL_001a: ldstr ""Literal"" IL_001f: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0024: stloc.0 IL_0025: ldloca.s V_0 IL_0027: call ""void <Program>$.<<Main>$>g__M|0_0(in CustomHandler)"" IL_002c: ret } "); } [Fact] public void PassAsRefWithoutKeyword_04() { var code = @" M($""{1,2:f}Literal""); void M(in CustomHandler c) => System.Console.WriteLine(c);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 48 (0x30) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_0 IL_002a: call ""void <Program>$.<<Main>$>g__M|0_0(in CustomHandler)"" IL_002f: ret } "); } [Theory] [CombinatorialData] public void RefOverloadResolution_Struct([CombinatorialValues("in", "ref")] string refKind) { var code = @" C.M($""{1,2:f}Literal""); class C { public static void M(CustomHandler c) => System.Console.WriteLine(c); public static void M(" + refKind + @" CustomHandler c) => System.Console.WriteLine(c); }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 47 (0x2f) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloc.0 IL_0029: call ""void C.M(CustomHandler)"" IL_002e: ret } "); } [Theory] [CombinatorialData] public void RefOverloadResolution_Class([CombinatorialValues("in", "ref")] string refKind) { var code = @" C.M($""{1,2:f}Literal""); class C { public static void M(CustomHandler c) => System.Console.WriteLine(c); public static void M(" + refKind + @" CustomHandler c) => System.Console.WriteLine(c); }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 47 (0x2f) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloc.0 IL_0029: call ""void C.M(CustomHandler)"" IL_002e: ret } "); } [Fact] public void RefOverloadResolution_MultipleBuilderTypes() { var code = @" C.M($""{1,2:f}Literal""); class C { public static void M(CustomHandler1 c) => System.Console.WriteLine(c); public static void M(ref CustomHandler2 c) => throw null; }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler1", "struct", useBoolReturns: false), GetInterpolatedStringCustomHandlerType("CustomHandler2", "struct", useBoolReturns: false, includeOneTimeHelpers: false) }); VerifyInterpolatedStringExpression(comp, "CustomHandler1"); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 47 (0x2f) .maxstack 4 .locals init (CustomHandler1 V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler1..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler1.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler1.AppendLiteral(string)"" IL_0028: ldloc.0 IL_0029: call ""void C.M(CustomHandler1)"" IL_002e: ret } "); } private const string InterpolatedStringHandlerAttributesVB = @" Namespace System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Class Or AttributeTargets.Struct, AllowMultiple:=False, Inherited:=False)> Public NotInheritable Class InterpolatedStringHandlerAttribute Inherits Attribute End Class <AttributeUsage(AttributeTargets.Parameter, AllowMultiple:=False, Inherited:=False)> Public NotInheritable Class InterpolatedStringHandlerArgumentAttribute Inherits Attribute Public Sub New(argument As String) Arguments = { argument } End Sub Public Sub New(ParamArray arguments() as String) Me.Arguments = arguments End Sub Public ReadOnly Property Arguments As String() End Class End Namespace "; [Fact] public void InterpolatedStringHandlerArgumentAttributeError_NonHandlerType() { var code = @" using System.Runtime.CompilerServices; C.M($""""); class C { public static void M([InterpolatedStringHandlerArgumentAttribute] string s) {} } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute }); comp.VerifyDiagnostics( // (8,27): error CS8946: 'string' is not an interpolated string handler type. // public static void M([InterpolatedStringHandlerArgumentAttribute] string s) {} Diagnostic(ErrorCode.ERR_TypeIsNotAnInterpolatedStringHandlerType, "InterpolatedStringHandlerArgumentAttribute").WithArguments("string").WithLocation(8, 27) ); var sParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", sParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(sParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(sParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_NonHandlerType_Metadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i as Integer, <InterpolatedStringHandlerArgument(""i"")> c As String) End Sub End Class "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); // Note: there is no compilation error here because the natural type of a string is still string, and // we just bind to that method without checking the handler attribute. var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics(); var sParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", sParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(sParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(sParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_InvalidArgument() { var code = @" using System.Runtime.CompilerServices; C.M($""""); class C { public static void M([InterpolatedStringHandlerArgumentAttribute(1)] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (8,70): error CS1503: Argument 1: cannot convert from 'int' to 'string' // public static void M([InterpolatedStringHandlerArgumentAttribute(1)] CustomHandler c) {} Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "string").WithLocation(8, 70) ); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.False(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_01() { var code = @" using System.Runtime.CompilerServices; C.M($""""); class C { public static void M([InterpolatedStringHandlerArgumentAttribute(""NonExistant"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 5), // (8,27): error CS8945: 'NonExistant' is not a valid parameter name from 'C.M(CustomHandler)'. // public static void M([InterpolatedStringHandlerArgumentAttribute("NonExistant")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""NonExistant"")").WithArguments("NonExistant", "C.M(CustomHandler)").WithLocation(8, 27) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_01_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(<InterpolatedStringHandlerArgument(""NonExistant"")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 5) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_02() { var code = @" using System.Runtime.CompilerServices; C.M(1, $""""); class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"", ""NonExistant"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8), // (8,34): error CS8945: 'NonExistant' is not a valid parameter name from 'C.M(int, CustomHandler)'. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("i", "NonExistant")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""i"", ""NonExistant"")").WithArguments("NonExistant", "C.M(int, CustomHandler)").WithLocation(8, 34) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_02_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument(""i"", ""NonExistant"")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_03() { var code = @" using System.Runtime.CompilerServices; C.M(1, $""""); class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""NonExistant1"", ""NonExistant2"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8), // (8,34): error CS8945: 'NonExistant1' is not a valid parameter name from 'C.M(int, CustomHandler)'. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("NonExistant1", "NonExistant2")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""NonExistant1"", ""NonExistant2"")").WithArguments("NonExistant1", "C.M(int, CustomHandler)").WithLocation(8, 34), // (8,34): error CS8945: 'NonExistant2' is not a valid parameter name from 'C.M(int, CustomHandler)'. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("NonExistant1", "NonExistant2")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""NonExistant1"", ""NonExistant2"")").WithArguments("NonExistant2", "C.M(int, CustomHandler)").WithLocation(8, 34) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_03_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument(""NonExistant1"", ""NonExistant2"")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_ReferenceSelf() { var code = @" using System.Runtime.CompilerServices; C.M(1, $""""); class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""c"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8), // (8,34): error CS8948: InterpolatedStringHandlerArgumentAttribute arguments cannot refer to the parameter the attribute is used on. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("c")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_CannotUseSelfAsInterpolatedStringHandlerArgument, @"InterpolatedStringHandlerArgumentAttribute(""c"")").WithLocation(8, 34) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_ReferencesSelf_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(<InterpolatedStringHandlerArgument(""c"")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 5) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_NullConstant() { var code = @" using System.Runtime.CompilerServices; C.M(1, $""""); class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(new string[] { null })] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8), // (8,34): error CS8943: 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. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(new string[] { null })] CustomHandler c) {} Diagnostic(ErrorCode.ERR_NullInvalidInterpolatedStringHandlerArgumentName, "InterpolatedStringHandlerArgumentAttribute(new string[] { null })").WithLocation(8, 34) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_NullConstant_FromMetadata_01() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument({ Nothing })> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_NullConstant_FromMetadata_02() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument({ Nothing, ""i"" })> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_NullConstant_FromMetadata_03() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument(CStr(Nothing))> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_ThisOnStaticMethod() { var code = @" using System.Runtime.CompilerServices; C.M($""""); class C { public static void M([InterpolatedStringHandlerArgumentAttribute("""")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 5), // (8,27): error CS8944: 'C.M(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument. // public static void M([InterpolatedStringHandlerArgumentAttribute("")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute("""")").WithArguments("C.M(CustomHandler)").WithLocation(8, 27) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"{""""}")] [InlineData(@"""""")] public void InterpolatedStringHandlerArgumentAttributeError_ThisOnStaticMethod_FromMetadata(string arg) { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(<InterpolatedStringHandlerArgument(" + arg + @")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 5) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_ThisOnConstructor() { var code = @" using System.Runtime.CompilerServices; _ = new C($""""); class C { public C([InterpolatedStringHandlerArgumentAttribute("""")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,11): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // _ = new C($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 11), // (8,15): error CS8944: 'C.C(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument. // public C([InterpolatedStringHandlerArgumentAttribute("")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute("""")").WithArguments("C.C(CustomHandler)").WithLocation(8, 15) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod(".ctor").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"{""""}")] [InlineData(@"""""")] public void InterpolatedStringHandlerArgumentAttributeError_ThisOnConstructor_FromMetadata(string arg) { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Sub New(<InterpolatedStringHandlerArgument(" + arg + @")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"_ = new C($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,11): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // _ = new C($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 11), // (1,11): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // _ = new C($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 11), // (1,11): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // _ = new C($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 11) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod(".ctor").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerAttributeArgumentError_SubstitutedTypeSymbol() { var code = @" using System.Runtime.CompilerServices; C<CustomHandler>.M($""""); public class C<T> { public static void M([InterpolatedStringHandlerArgumentAttribute] T t) { } } "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, customHandler }); comp.VerifyDiagnostics( // (4,20): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C<CustomHandler>.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 20), // (8,27): error CS8946: 'T' is not an interpolated string handler type. // public static void M([InterpolatedStringHandlerArgumentAttribute] T t) { } Diagnostic(ErrorCode.ERR_TypeIsNotAnInterpolatedStringHandlerType, "InterpolatedStringHandlerArgumentAttribute").WithArguments("T").WithLocation(8, 27) ); var c = comp.SourceModule.GlobalNamespace.GetTypeMember("C"); var handler = comp.SourceModule.GlobalNamespace.GetTypeMember("CustomHandler"); var substitutedC = c.WithTypeArguments(ImmutableArray.Create(TypeWithAnnotations.Create(handler))); var cParam = substitutedC.GetMethod("M").Parameters.Single(); Assert.IsType<SubstitutedParameterSymbol>(cParam); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_SubstitutedTypeSymbol_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C(Of T) Public Shared Sub M(<InterpolatedStringHandlerArgument()> c As T) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C<CustomHandler>.M($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,20): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C<CustomHandler>.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 20), // (1,20): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C<CustomHandler>.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 20), // (1,20): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C<CustomHandler>.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 20) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C`1").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData("")] [InlineData(", out bool success")] public void InterpolatedStringHandlerArgumentAttributeWarn_ParameterAfterHandler(string extraConstructorArg) { var code = @" using System; using System.Runtime.CompilerServices; public class C { public static void M([InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c, int i) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var goodCode = @" int i = 10; C.M(i: i, c: $""text""); "; var comp = CreateCompilation(new[] { code, goodCode, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate, expectedOutput: @" i:10 literal:text "); verifier.VerifyDiagnostics( // (6,27): warning CS8947: Parameter i occurs after CustomHandler 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. // public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, int i) => Console.WriteLine(c.ToString()); Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(6, 27) ); verifyIL(verifier); var badCode = @"C.M($"""", 1);"; comp = CreateCompilation(new[] { code, badCode, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (1,10): error CS8950: Parameter 'i' is an argument to the interpolated string handler conversion on parameter 'c', but is specified after the interpolated string constant. Reorder the arguments to move 'i' before 'c'. // C.M($"", 1); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentLocatedAfterInterpolatedString, "1").WithArguments("i", "c").WithLocation(1, 10), // (6,27): warning CS8947: Parameter i occurs after CustomHandler 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. // public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, int i) => Console.WriteLine(c.ToString()); Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(6, 27) ); static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.First(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(1, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); Assert.False(cParam.HasInterpolatedStringHandlerArgumentError); } void verifyIL(CompilationVerifier verifier) { verifier.VerifyIL("<top-level-statements-entry-point>", extraConstructorArg == "" ? @" { // Code size 36 (0x24) .maxstack 4 .locals init (int V_0, int V_1, CustomHandler V_2) IL_0000: ldc.i4.s 10 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: stloc.1 IL_0005: ldloca.s V_2 IL_0007: ldc.i4.4 IL_0008: ldc.i4.0 IL_0009: ldloc.0 IL_000a: call ""CustomHandler..ctor(int, int, int)"" IL_000f: ldloca.s V_2 IL_0011: ldstr ""text"" IL_0016: call ""bool CustomHandler.AppendLiteral(string)"" IL_001b: pop IL_001c: ldloc.2 IL_001d: ldloc.1 IL_001e: call ""void C.M(CustomHandler, int)"" IL_0023: ret } " : @" { // Code size 43 (0x2b) .maxstack 4 .locals init (int V_0, int V_1, CustomHandler V_2, bool V_3) IL_0000: ldc.i4.s 10 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: stloc.1 IL_0005: ldc.i4.4 IL_0006: ldc.i4.0 IL_0007: ldloc.0 IL_0008: ldloca.s V_3 IL_000a: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000f: stloc.2 IL_0010: ldloc.3 IL_0011: brfalse.s IL_0021 IL_0013: ldloca.s V_2 IL_0015: ldstr ""text"" IL_001a: call ""bool CustomHandler.AppendLiteral(string)"" IL_001f: br.s IL_0022 IL_0021: ldc.i4.0 IL_0022: pop IL_0023: ldloc.2 IL_0024: ldloc.1 IL_0025: call ""void C.M(CustomHandler, int)"" IL_002a: ret } "); } } [Fact] public void InterpolatedStringHandlerArgumentAttributeWarn_ParameterAfterHandler_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(<InterpolatedStringHandlerArgument(""i"")> c As CustomHandler, i As Integer) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation("", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics(); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.First(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(1, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); Assert.False(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_OptionalNotSpecifiedAtCallsite() { var code = @" using System.Runtime.CompilerServices; C.M($""""); public class C { public static void M([InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c, int i = 0) { } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount) { } } "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, customHandler }); comp.VerifyDiagnostics( // (4,5): error CS8951: Parameter 'i' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter 'c'. Specify the value of 'i' before 'c'. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified, @"$""""").WithArguments("i", "c").WithLocation(4, 5), // (8,27): warning CS8947: Parameter i occurs after CustomHandler 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. // public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, params int[] i) { } Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(8, 27) ); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_ParamsNotSpecifiedAtCallsite() { var code = @" using System.Runtime.CompilerServices; C.M($""""); public class C { public static void M([InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c, params int[] i) { } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int[] i) : this(literalLength, formattedCount) { } } "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, customHandler }); comp.VerifyDiagnostics( // (4,5): error CS8951: Parameter 'i' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter 'c'. Specify the value of 'i' before 'c'. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified, @"$""""").WithArguments("i", "c").WithLocation(4, 5), // (8,27): warning CS8947: Parameter i occurs after CustomHandler 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. // public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, params int[] i) { } Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(8, 27) ); } [Fact] public void InterpolatedStringHandlerArgumentAttribute_MissingConstructor() { var code = @" using System.Runtime.CompilerServices; public class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); // https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback. var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate).VerifyDiagnostics(); CreateCompilation(@"C.M(1, $"""");", new[] { comp.ToMetadataReference() }).VerifyDiagnostics( // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 4 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "4").WithLocation(1, 8) ); static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); Assert.False(cParam.HasInterpolatedStringHandlerArgumentError); } } [Fact] public void InterpolatedStringHandlerArgumentAttribute_InaccessibleConstructor_01() { var code = @" using System.Runtime.CompilerServices; public class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) {} } public partial struct CustomHandler { private CustomHandler(int literalLength, int formattedCount, int i) : this() {} static void InCustomHandler() { C.M(1, $""""); } } "; var executableCode = @"C.M(1, $"""");"; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (1,8): error CS0122: 'CustomHandler.CustomHandler(int, int, int)' is inaccessible due to its protection level // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadAccess, @"$""""").WithArguments("CustomHandler.CustomHandler(int, int, int)").WithLocation(1, 8) ); var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); // https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback. CompileAndVerify(dependency, symbolValidator: validate, sourceSymbolValidator: validate).VerifyDiagnostics(); comp = CreateCompilation(executableCode, new[] { dependency.EmitToImageReference() }); comp.VerifyDiagnostics( // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 4 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "4").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); comp = CreateCompilation(executableCode, new[] { dependency.ToMetadataReference() }); comp.VerifyDiagnostics( // (1,8): error CS0122: 'CustomHandler.CustomHandler(int, int, int)' is inaccessible due to its protection level // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadAccess, @"$""""").WithArguments("CustomHandler.CustomHandler(int, int, int)").WithLocation(1, 8) ); static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); } } private void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes(string mRef, string customHandlerRef, params DiagnosticDescription[] expectedDiagnostics) { var code = @" using System.Runtime.CompilerServices; int i = 0; C.M(" + mRef + @" i, $""""); public class C { public static void M(" + mRef + @" int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) { " + (mRef == "out" ? "i = 0;" : "") + @" } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, " + customHandlerRef + @" int i) : this() { " + (customHandlerRef == "out" ? "i = 0;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics(expectedDiagnostics); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); } [Fact] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_RefNone() { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("ref", "", // (5,9): error CS1615: Argument 3 may not be passed with the 'ref' keyword // C.M(ref i, $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "ref").WithLocation(5, 9)); } [Fact] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_RefOut() { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("ref", "out", // (5,9): error CS1620: Argument 3 must be passed with the 'out' keyword // C.M(ref i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "out").WithLocation(5, 9)); } [Fact] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_RefIn() { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("ref", "in", // (5,9): error CS1615: Argument 3 may not be passed with the 'ref' keyword // C.M(ref i, $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "ref").WithLocation(5, 9)); } [Fact] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_InNone() { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("in", "", // (5,8): error CS1615: Argument 3 may not be passed with the 'in' keyword // C.M(in i, $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "in").WithLocation(5, 8)); } [Fact] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_InOut() { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("in", "out", // (5,8): error CS1620: Argument 3 must be passed with the 'out' keyword // C.M(in i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "out").WithLocation(5, 8)); } [Fact] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_InRef() { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("in", "ref", // (5,8): error CS1620: Argument 3 must be passed with the 'ref' keyword // C.M(in i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "ref").WithLocation(5, 8)); } [Fact] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_OutNone() { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("out", "", // (5,9): error CS1615: Argument 3 may not be passed with the 'out' keyword // C.M(out i, $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "out").WithLocation(5, 9)); } [Fact] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_OutRef() { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("out", "ref", // (5,9): error CS1620: Argument 3 must be passed with the 'ref' keyword // C.M(out i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "ref").WithLocation(5, 9)); } [Fact] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_NoneRef() { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("", "ref", // (5,6): error CS1620: Argument 3 must be passed with the 'ref' keyword // C.M( i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "ref").WithLocation(5, 6)); } [Fact] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_NoneOut() { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("", "out", // (5,6): error CS1620: Argument 3 must be passed with the 'out' keyword // C.M( i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "out").WithLocation(5, 6)); } [Theory] [InlineData("")] [InlineData(", out bool success")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedType(string extraConstructorArg) { var code = @" using System.Runtime.CompilerServices; public class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) {} } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s" + extraConstructorArg + @") : this() { " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var executableCode = @"C.M(1, $"""");"; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var expectedDiagnostics = extraConstructorArg == "" ? new DiagnosticDescription[] { // (1,5): error CS1503: Argument 3: cannot convert from 'int' to 'string' // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("3", "int", "string").WithLocation(1, 5) } : new DiagnosticDescription[] { // (1,5): error CS1503: Argument 3: cannot convert from 'int' to 'string' // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("3", "int", "string").WithLocation(1, 5), // (1,8): error CS7036: There is no argument given that corresponds to the required formal parameter 'success' of 'CustomHandler.CustomHandler(int, int, string, out bool)' // C.M(1, $""); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, @"$""""").WithArguments("success", "CustomHandler.CustomHandler(int, int, string, out bool)").WithLocation(1, 8) }; var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics(expectedDiagnostics); // https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback. var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); CompileAndVerify(dependency, symbolValidator: validate, sourceSymbolValidator: validate).VerifyDiagnostics(); foreach (var d in new[] { dependency.EmitToImageReference(), dependency.ToMetadataReference() }) { comp = CreateCompilation(executableCode, new[] { d }); comp.VerifyDiagnostics(expectedDiagnostics); } static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); } } [Theory] [InlineData("")] [InlineData(", out bool success")] public void InterpolatedStringHandlerArgumentAttribute_SingleArg(string extraConstructorArg) { var code = @" using System.Runtime.CompilerServices; public class C { public static string M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) => c.ToString(); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var executableCode = @" using System; int i = 10; Console.WriteLine(C.M(i, $""2"")); "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" i:10 literal:2"); verifier.VerifyDiagnostics(); verifyIL(extraConstructorArg, verifier); var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); foreach (var d in new[] { dependency.EmitToImageReference(), dependency.ToMetadataReference() }) { verifier = CompileAndVerify(executableCode, new[] { d }, expectedOutput: @" i:10 literal:2"); verifier.VerifyDiagnostics(); verifyIL(extraConstructorArg, verifier); } static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); } static void verifyIL(string extraConstructorArg, CompilationVerifier verifier) { verifier.VerifyIL("<top-level-statements-entry-point>", extraConstructorArg == "" ? @" { // Code size 39 (0x27) .maxstack 5 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.s 10 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldloca.s V_1 IL_0006: ldc.i4.1 IL_0007: ldc.i4.0 IL_0008: ldloc.0 IL_0009: call ""CustomHandler..ctor(int, int, int)"" IL_000e: ldloca.s V_1 IL_0010: ldstr ""2"" IL_0015: call ""bool CustomHandler.AppendLiteral(string)"" IL_001a: pop IL_001b: ldloc.1 IL_001c: call ""string C.M(int, CustomHandler)"" IL_0021: call ""void System.Console.WriteLine(string)"" IL_0026: ret } " : @" { // Code size 46 (0x2e) .maxstack 5 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: ldc.i4.s 10 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldc.i4.1 IL_0005: ldc.i4.0 IL_0006: ldloc.0 IL_0007: ldloca.s V_2 IL_0009: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000e: stloc.1 IL_000f: ldloc.2 IL_0010: brfalse.s IL_0020 IL_0012: ldloca.s V_1 IL_0014: ldstr ""2"" IL_0019: call ""bool CustomHandler.AppendLiteral(string)"" IL_001e: br.s IL_0021 IL_0020: ldc.i4.0 IL_0021: pop IL_0022: ldloc.1 IL_0023: call ""string C.M(int, CustomHandler)"" IL_0028: call ""void System.Console.WriteLine(string)"" IL_002d: ret } "); } } [Theory] [InlineData("")] [InlineData(", out bool success")] public void InterpolatedStringHandlerArgumentAttribute_MultipleArgs(string extraConstructorArg) { var code = @" using System; using System.Runtime.CompilerServices; public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i, string s" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); _builder.AppendLine(""s:"" + s); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var executableCode = @" int i = 10; string s = ""arg""; C.M(i, s, $""literal""); "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler }); string expectedOutput = @" i:10 s:arg literal:literal "; var verifier = base.CompileAndVerify((Compilation)comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: expectedOutput); verifier.VerifyDiagnostics(); verifyIL(extraConstructorArg, verifier); var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); foreach (var d in new[] { dependency.EmitToImageReference(), dependency.ToMetadataReference() }) { verifier = CompileAndVerify(executableCode, new[] { d }, expectedOutput: expectedOutput); verifier.VerifyDiagnostics(); verifyIL(extraConstructorArg, verifier); } static void validator(ModuleSymbol verifier) { var cParam = verifier.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } static void verifyIL(string extraConstructorArg, CompilationVerifier verifier) { verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 44 (0x2c) .maxstack 7 .locals init (string V_0, //s int V_1, string V_2, CustomHandler V_3) IL_0000: ldc.i4.s 10 IL_0002: ldstr ""arg"" IL_0007: stloc.0 IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldloc.0 IL_000b: stloc.2 IL_000c: ldloc.2 IL_000d: ldloca.s V_3 IL_000f: ldc.i4.7 IL_0010: ldc.i4.0 IL_0011: ldloc.1 IL_0012: ldloc.2 IL_0013: call ""CustomHandler..ctor(int, int, int, string)"" IL_0018: ldloca.s V_3 IL_001a: ldstr ""literal"" IL_001f: call ""bool CustomHandler.AppendLiteral(string)"" IL_0024: pop IL_0025: ldloc.3 IL_0026: call ""void C.M(int, string, CustomHandler)"" IL_002b: ret } " : @" { // Code size 52 (0x34) .maxstack 7 .locals init (string V_0, //s int V_1, string V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.s 10 IL_0002: ldstr ""arg"" IL_0007: stloc.0 IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldloc.0 IL_000b: stloc.2 IL_000c: ldloc.2 IL_000d: ldc.i4.7 IL_000e: ldc.i4.0 IL_000f: ldloc.1 IL_0010: ldloc.2 IL_0011: ldloca.s V_4 IL_0013: newobj ""CustomHandler..ctor(int, int, int, string, out bool)"" IL_0018: stloc.3 IL_0019: ldloc.s V_4 IL_001b: brfalse.s IL_002b IL_001d: ldloca.s V_3 IL_001f: ldstr ""literal"" IL_0024: call ""bool CustomHandler.AppendLiteral(string)"" IL_0029: br.s IL_002c IL_002b: ldc.i4.0 IL_002c: pop IL_002d: ldloc.3 IL_002e: call ""void C.M(int, string, CustomHandler)"" IL_0033: ret } "); } } [Theory] [InlineData("")] [InlineData(", out bool success")] public void InterpolatedStringHandlerArgumentAttribute_RefKindsMatch(string extraConstructorArg) { var code = @" using System; using System.Runtime.CompilerServices; int i = 1; string s = null; object o; C.M(i, ref s, out o, $""literal""); Console.WriteLine(s); Console.WriteLine(o); public class C { public static void M(in int i, ref string s, out object o, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"", ""o"")] CustomHandler c) { Console.WriteLine(s); o = ""o in M""; s = ""s in M""; Console.Write(c.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, in int i, ref string s, out object o" + extraConstructorArg + @") : this(literalLength, formattedCount) { o = null; s = ""s in constructor""; _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" s in constructor i:1 literal:literal s in M o in M "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 67 (0x43) .maxstack 8 .locals init (int V_0, //i string V_1, //s object V_2, //o int& V_3, string& V_4, object& V_5, CustomHandler V_6) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldnull IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: stloc.3 IL_0007: ldloc.3 IL_0008: ldloca.s V_1 IL_000a: stloc.s V_4 IL_000c: ldloc.s V_4 IL_000e: ldloca.s V_2 IL_0010: stloc.s V_5 IL_0012: ldloc.s V_5 IL_0014: ldc.i4.7 IL_0015: ldc.i4.0 IL_0016: ldloc.3 IL_0017: ldloc.s V_4 IL_0019: ldloc.s V_5 IL_001b: newobj ""CustomHandler..ctor(int, int, in int, ref string, out object)"" IL_0020: stloc.s V_6 IL_0022: ldloca.s V_6 IL_0024: ldstr ""literal"" IL_0029: call ""bool CustomHandler.AppendLiteral(string)"" IL_002e: pop IL_002f: ldloc.s V_6 IL_0031: call ""void C.M(in int, ref string, out object, CustomHandler)"" IL_0036: ldloc.1 IL_0037: call ""void System.Console.WriteLine(string)"" IL_003c: ldloc.2 IL_003d: call ""void System.Console.WriteLine(object)"" IL_0042: ret } " : @" { // Code size 76 (0x4c) .maxstack 9 .locals init (int V_0, //i string V_1, //s object V_2, //o int& V_3, string& V_4, object& V_5, CustomHandler V_6, bool V_7) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldnull IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: stloc.3 IL_0007: ldloc.3 IL_0008: ldloca.s V_1 IL_000a: stloc.s V_4 IL_000c: ldloc.s V_4 IL_000e: ldloca.s V_2 IL_0010: stloc.s V_5 IL_0012: ldloc.s V_5 IL_0014: ldc.i4.7 IL_0015: ldc.i4.0 IL_0016: ldloc.3 IL_0017: ldloc.s V_4 IL_0019: ldloc.s V_5 IL_001b: ldloca.s V_7 IL_001d: newobj ""CustomHandler..ctor(int, int, in int, ref string, out object, out bool)"" IL_0022: stloc.s V_6 IL_0024: ldloc.s V_7 IL_0026: brfalse.s IL_0036 IL_0028: ldloca.s V_6 IL_002a: ldstr ""literal"" IL_002f: call ""bool CustomHandler.AppendLiteral(string)"" IL_0034: br.s IL_0037 IL_0036: ldc.i4.0 IL_0037: pop IL_0038: ldloc.s V_6 IL_003a: call ""void C.M(in int, ref string, out object, CustomHandler)"" IL_003f: ldloc.1 IL_0040: call ""void System.Console.WriteLine(string)"" IL_0045: ldloc.2 IL_0046: call ""void System.Console.WriteLine(object)"" IL_004b: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(3).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 1, 2 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [InlineData("")] [InlineData(", out bool success")] public void InterpolatedStringHandlerArgumentAttribute_ReorderedAttributePositions(string extraConstructorArg) { var code = @" using System; using System.Runtime.CompilerServices; C.M(GetInt(), GetString(), $""literal""); int GetInt() { Console.WriteLine(""GetInt""); return 10; } string GetString() { Console.WriteLine(""GetString""); return ""str""; } public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""s"", ""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s, int i" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""s:"" + s); _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" GetInt GetString s:str i:10 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 45 (0x2d) .maxstack 7 .locals init (string V_0, int V_1, CustomHandler V_2) IL_0000: call ""int <Program>$.<<Main>$>g__GetInt|0_0()"" IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: call ""string <Program>$.<<Main>$>g__GetString|0_1()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: ldloca.s V_2 IL_0010: ldc.i4.7 IL_0011: ldc.i4.0 IL_0012: ldloc.0 IL_0013: ldloc.1 IL_0014: call ""CustomHandler..ctor(int, int, string, int)"" IL_0019: ldloca.s V_2 IL_001b: ldstr ""literal"" IL_0020: call ""bool CustomHandler.AppendLiteral(string)"" IL_0025: pop IL_0026: ldloc.2 IL_0027: call ""void C.M(int, string, CustomHandler)"" IL_002c: ret } " : @" { // Code size 52 (0x34) .maxstack 7 .locals init (string V_0, int V_1, CustomHandler V_2, bool V_3) IL_0000: call ""int <Program>$.<<Main>$>g__GetInt|0_0()"" IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: call ""string <Program>$.<<Main>$>g__GetString|0_1()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: ldc.i4.7 IL_000f: ldc.i4.0 IL_0010: ldloc.0 IL_0011: ldloc.1 IL_0012: ldloca.s V_3 IL_0014: newobj ""CustomHandler..ctor(int, int, string, int, out bool)"" IL_0019: stloc.2 IL_001a: ldloc.3 IL_001b: brfalse.s IL_002b IL_001d: ldloca.s V_2 IL_001f: ldstr ""literal"" IL_0024: call ""bool CustomHandler.AppendLiteral(string)"" IL_0029: br.s IL_002c IL_002b: ldc.i4.0 IL_002c: pop IL_002d: ldloc.2 IL_002e: call ""void C.M(int, string, CustomHandler)"" IL_0033: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 1, 0 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [InlineData("")] [InlineData(", out bool success")] public void InterpolatedStringHandlerArgumentAttribute_ParametersReordered(string extraConstructorArg) { var code = @" using System; using System.Runtime.CompilerServices; GetC().M(s: GetString(), i: GetInt(), c: $""literal""); C GetC() { Console.WriteLine(""GetC""); return new C { Field = 5 }; } int GetInt() { Console.WriteLine(""GetInt""); return 10; } string GetString() { Console.WriteLine(""GetString""); return ""str""; } public class C { public int Field; public void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""s"", """", ""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s, C c, int i" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""s:"" + s); _builder.AppendLine(""c.Field:"" + c.Field.ToString()); _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" GetC GetString GetInt s:str c.Field:5 i:10 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 56 (0x38) .maxstack 9 .locals init (string V_0, C V_1, int V_2, string V_3, CustomHandler V_4) IL_0000: call ""C <Program>$.<<Main>$>g__GetC|0_0()"" IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: call ""string <Program>$.<<Main>$>g__GetString|0_2()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: stloc.3 IL_000f: call ""int <Program>$.<<Main>$>g__GetInt|0_1()"" IL_0014: stloc.2 IL_0015: ldloc.2 IL_0016: ldloc.3 IL_0017: ldloca.s V_4 IL_0019: ldc.i4.7 IL_001a: ldc.i4.0 IL_001b: ldloc.0 IL_001c: ldloc.1 IL_001d: ldloc.2 IL_001e: call ""CustomHandler..ctor(int, int, string, C, int)"" IL_0023: ldloca.s V_4 IL_0025: ldstr ""literal"" IL_002a: call ""bool CustomHandler.AppendLiteral(string)"" IL_002f: pop IL_0030: ldloc.s V_4 IL_0032: callvirt ""void C.M(int, string, CustomHandler)"" IL_0037: ret } " : @" { // Code size 65 (0x41) .maxstack 9 .locals init (string V_0, C V_1, int V_2, string V_3, CustomHandler V_4, bool V_5) IL_0000: call ""C <Program>$.<<Main>$>g__GetC|0_0()"" IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: call ""string <Program>$.<<Main>$>g__GetString|0_2()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: stloc.3 IL_000f: call ""int <Program>$.<<Main>$>g__GetInt|0_1()"" IL_0014: stloc.2 IL_0015: ldloc.2 IL_0016: ldloc.3 IL_0017: ldc.i4.7 IL_0018: ldc.i4.0 IL_0019: ldloc.0 IL_001a: ldloc.1 IL_001b: ldloc.2 IL_001c: ldloca.s V_5 IL_001e: newobj ""CustomHandler..ctor(int, int, string, C, int, out bool)"" IL_0023: stloc.s V_4 IL_0025: ldloc.s V_5 IL_0027: brfalse.s IL_0037 IL_0029: ldloca.s V_4 IL_002b: ldstr ""literal"" IL_0030: call ""bool CustomHandler.AppendLiteral(string)"" IL_0035: br.s IL_0038 IL_0037: ldc.i4.0 IL_0038: pop IL_0039: ldloc.s V_4 IL_003b: callvirt ""void C.M(int, string, CustomHandler)"" IL_0040: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 1, -1, 0 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [InlineData("")] [InlineData(", out bool success")] public void InterpolatedStringHandlerArgumentAttribute_Duplicated(string extraConstructorArg) { var code = @" using System; using System.Runtime.CompilerServices; C.M(GetInt(), """", $""literal""); int GetInt() { Console.WriteLine(""GetInt""); return 10; } public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i1, int i2" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i1:"" + i1.ToString()); _builder.AppendLine(""i2:"" + i2.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" GetInt i1:10 i2:10 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 43 (0x2b) .maxstack 7 .locals init (int V_0, CustomHandler V_1) IL_0000: call ""int <Program>$.<<Main>$>g__GetInt|0_0()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr """" IL_000c: ldloca.s V_1 IL_000e: ldc.i4.7 IL_000f: ldc.i4.0 IL_0010: ldloc.0 IL_0011: ldloc.0 IL_0012: call ""CustomHandler..ctor(int, int, int, int)"" IL_0017: ldloca.s V_1 IL_0019: ldstr ""literal"" IL_001e: call ""bool CustomHandler.AppendLiteral(string)"" IL_0023: pop IL_0024: ldloc.1 IL_0025: call ""void C.M(int, string, CustomHandler)"" IL_002a: ret } " : @" { // Code size 50 (0x32) .maxstack 7 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: call ""int <Program>$.<<Main>$>g__GetInt|0_0()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr """" IL_000c: ldc.i4.7 IL_000d: ldc.i4.0 IL_000e: ldloc.0 IL_000f: ldloc.0 IL_0010: ldloca.s V_2 IL_0012: newobj ""CustomHandler..ctor(int, int, int, int, out bool)"" IL_0017: stloc.1 IL_0018: ldloc.2 IL_0019: brfalse.s IL_0029 IL_001b: ldloca.s V_1 IL_001d: ldstr ""literal"" IL_0022: call ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.1 IL_002c: call ""void C.M(int, string, CustomHandler)"" IL_0031: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 0 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [InlineData("")] [InlineData(", out bool success")] public void InterpolatedStringHandlerArgumentAttribute_EmptyWithMatchingConstructor(string extraConstructorArg) { var code = @" using System; using System.Runtime.CompilerServices; C.M(1, """", $""""); public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute()] CustomHandler c) => Console.WriteLine(c.ToString()); } [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount" + extraConstructorArg + @") { " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: "CustomHandler").VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 19 (0x13) .maxstack 4 IL_0000: ldc.i4.1 IL_0001: ldstr """" IL_0006: ldc.i4.0 IL_0007: ldc.i4.0 IL_0008: newobj ""CustomHandler..ctor(int, int)"" IL_000d: call ""void C.M(int, string, CustomHandler)"" IL_0012: ret } " : @" { // Code size 21 (0x15) .maxstack 5 .locals init (bool V_0) IL_0000: ldc.i4.1 IL_0001: ldstr """" IL_0006: ldc.i4.0 IL_0007: ldc.i4.0 IL_0008: ldloca.s V_0 IL_000a: newobj ""CustomHandler..ctor(int, int, out bool)"" IL_000f: call ""void C.M(int, string, CustomHandler)"" IL_0014: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [InlineData("")] [InlineData(", out bool success")] public void InterpolatedStringHandlerArgumentAttribute_EmptyWithoutMatchingConstructor(string extraConstructorArg) { var code = @" using System.Runtime.CompilerServices; public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute()] CustomHandler c) { } } [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i" + extraConstructorArg + @") { " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }); // https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback. CompileAndVerify(comp, symbolValidator: validate, sourceSymbolValidator: validate).VerifyDiagnostics(); CreateCompilation(@"C.M(1, """", $"""");", new[] { comp.EmitToImageReference() }).VerifyDiagnostics( (extraConstructorArg == "") ? new[] { // (1,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'CustomHandler.CustomHandler(int, int, int)' // C.M(1, "", $""); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, @"$""""").WithArguments("i", "CustomHandler.CustomHandler(int, int, int)").WithLocation(1, 12), // (1,12): error CS1615: Argument 3 may not be passed with the 'out' keyword // C.M(1, "", $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, @"$""""").WithArguments("3", "out").WithLocation(1, 12) } : new[] { // (1,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'CustomHandler.CustomHandler(int, int, int, out bool)' // C.M(1, "", $""); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, @"$""""").WithArguments("i", "CustomHandler.CustomHandler(int, int, int, out bool)").WithLocation(1, 12), // (1,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'success' of 'CustomHandler.CustomHandler(int, int, int, out bool)' // C.M(1, "", $""); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, @"$""""").WithArguments("success", "CustomHandler.CustomHandler(int, int, int, out bool)").WithLocation(1, 12) } ); static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [InlineData("")] [InlineData(", out bool success")] public void InterpolatedStringHandlerArgumentAttribute_OnIndexerRvalue(string extraConstructorArg) { var code = @" using System; using System.Runtime.CompilerServices; var c = new C(); Console.WriteLine(c[10, ""str"", $""literal""]); public class C { public string this[int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"")] CustomHandler c] { get => c.ToString(); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i1, string s" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i1:"" + i1.ToString()); _builder.AppendLine(""s:"" + s); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" i1:10 s:str literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 52 (0x34) .maxstack 8 .locals init (int V_0, string V_1, CustomHandler V_2) IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.s 10 IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""str"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldloca.s V_2 IL_0012: ldc.i4.7 IL_0013: ldc.i4.0 IL_0014: ldloc.0 IL_0015: ldloc.1 IL_0016: call ""CustomHandler..ctor(int, int, int, string)"" IL_001b: ldloca.s V_2 IL_001d: ldstr ""literal"" IL_0022: call ""bool CustomHandler.AppendLiteral(string)"" IL_0027: pop IL_0028: ldloc.2 IL_0029: callvirt ""string C.this[int, string, CustomHandler].get"" IL_002e: call ""void System.Console.WriteLine(string)"" IL_0033: ret } " : @" { // Code size 59 (0x3b) .maxstack 8 .locals init (int V_0, string V_1, CustomHandler V_2, bool V_3) IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.s 10 IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""str"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldc.i4.7 IL_0011: ldc.i4.0 IL_0012: ldloc.0 IL_0013: ldloc.1 IL_0014: ldloca.s V_3 IL_0016: newobj ""CustomHandler..ctor(int, int, int, string, out bool)"" IL_001b: stloc.2 IL_001c: ldloc.3 IL_001d: brfalse.s IL_002d IL_001f: ldloca.s V_2 IL_0021: ldstr ""literal"" IL_0026: call ""bool CustomHandler.AppendLiteral(string)"" IL_002b: br.s IL_002e IL_002d: ldc.i4.0 IL_002e: pop IL_002f: ldloc.2 IL_0030: callvirt ""string C.this[int, string, CustomHandler].get"" IL_0035: call ""void System.Console.WriteLine(string)"" IL_003a: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetIndexer<PropertySymbol>("Item").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [InlineData("")] [InlineData(", out bool success")] public void InterpolatedStringHandlerArgumentAttribute_OnIndexerLvalue(string extraConstructorArg) { var code = @" using System; using System.Runtime.CompilerServices; var c = new C(); c[10, ""str"", $""literal""] = """"; public class C { public string this[int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"")] CustomHandler c] { set => Console.WriteLine(c.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i1, string s" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i1:"" + i1.ToString()); _builder.AppendLine(""s:"" + s); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" i1:10 s:str literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 52 (0x34) .maxstack 8 .locals init (int V_0, string V_1, CustomHandler V_2) IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.s 10 IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""str"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldloca.s V_2 IL_0012: ldc.i4.7 IL_0013: ldc.i4.0 IL_0014: ldloc.0 IL_0015: ldloc.1 IL_0016: call ""CustomHandler..ctor(int, int, int, string)"" IL_001b: ldloca.s V_2 IL_001d: ldstr ""literal"" IL_0022: call ""bool CustomHandler.AppendLiteral(string)"" IL_0027: pop IL_0028: ldloc.2 IL_0029: ldstr """" IL_002e: callvirt ""void C.this[int, string, CustomHandler].set"" IL_0033: ret } " : @" { // Code size 59 (0x3b) .maxstack 8 .locals init (int V_0, string V_1, CustomHandler V_2, bool V_3) IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.s 10 IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""str"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldc.i4.7 IL_0011: ldc.i4.0 IL_0012: ldloc.0 IL_0013: ldloc.1 IL_0014: ldloca.s V_3 IL_0016: newobj ""CustomHandler..ctor(int, int, int, string, out bool)"" IL_001b: stloc.2 IL_001c: ldloc.3 IL_001d: brfalse.s IL_002d IL_001f: ldloca.s V_2 IL_0021: ldstr ""literal"" IL_0026: call ""bool CustomHandler.AppendLiteral(string)"" IL_002b: br.s IL_002e IL_002d: ldc.i4.0 IL_002e: pop IL_002f: ldloc.2 IL_0030: ldstr """" IL_0035: callvirt ""void C.this[int, string, CustomHandler].set"" IL_003a: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetIndexer<PropertySymbol>("Item").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [InlineData("")] [InlineData(", out bool success")] public void InterpolatedStringHandlerArgumentAttribute_ThisParameter(string extraConstructorArg) { var code = @" using System; using System.Runtime.CompilerServices; (new C(5)).M((int)10, ""str"", $""literal""); public class C { public int Prop { get; } public C(int i) => Prop = i; public void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", """", ""s"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i1, C c, string s" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i1:"" + i1.ToString()); _builder.AppendLine(""c.Prop:"" + c.Prop.ToString()); _builder.AppendLine(""s:"" + s); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" i1:10 c.Prop:5 s:str literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 51 (0x33) .maxstack 9 .locals init (int V_0, C V_1, string V_2, CustomHandler V_3) IL_0000: ldc.i4.5 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.1 IL_0007: ldloc.1 IL_0008: ldc.i4.s 10 IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: ldstr ""str"" IL_0011: stloc.2 IL_0012: ldloc.2 IL_0013: ldloca.s V_3 IL_0015: ldc.i4.7 IL_0016: ldc.i4.0 IL_0017: ldloc.0 IL_0018: ldloc.1 IL_0019: ldloc.2 IL_001a: call ""CustomHandler..ctor(int, int, int, C, string)"" IL_001f: ldloca.s V_3 IL_0021: ldstr ""literal"" IL_0026: call ""bool CustomHandler.AppendLiteral(string)"" IL_002b: pop IL_002c: ldloc.3 IL_002d: callvirt ""void C.M(int, string, CustomHandler)"" IL_0032: ret } " : @" { // Code size 59 (0x3b) .maxstack 9 .locals init (int V_0, C V_1, string V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.5 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.1 IL_0007: ldloc.1 IL_0008: ldc.i4.s 10 IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: ldstr ""str"" IL_0011: stloc.2 IL_0012: ldloc.2 IL_0013: ldc.i4.7 IL_0014: ldc.i4.0 IL_0015: ldloc.0 IL_0016: ldloc.1 IL_0017: ldloc.2 IL_0018: ldloca.s V_4 IL_001a: newobj ""CustomHandler..ctor(int, int, int, C, string, out bool)"" IL_001f: stloc.3 IL_0020: ldloc.s V_4 IL_0022: brfalse.s IL_0032 IL_0024: ldloca.s V_3 IL_0026: ldstr ""literal"" IL_002b: call ""bool CustomHandler.AppendLiteral(string)"" IL_0030: br.s IL_0033 IL_0032: ldc.i4.0 IL_0033: pop IL_0034: ldloc.3 IL_0035: callvirt ""void C.M(int, string, CustomHandler)"" IL_003a: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, -1, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Fact] public void InterpolatedStringHandlerArgumentAttribute_OnConstructor() { var code = @" using System; using System.Runtime.CompilerServices; _ = new C(5, $""literal""); public class C { public int Prop { get; } public C(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")]CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" i:5 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 34 (0x22) .maxstack 5 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.5 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldloca.s V_1 IL_0005: ldc.i4.7 IL_0006: ldc.i4.0 IL_0007: ldloc.0 IL_0008: call ""CustomHandler..ctor(int, int, int)"" IL_000d: ldloca.s V_1 IL_000f: ldstr ""literal"" IL_0014: call ""bool CustomHandler.AppendLiteral(string)"" IL_0019: pop IL_001a: ldloc.1 IL_001b: newobj ""C..ctor(int, CustomHandler)"" IL_0020: pop IL_0021: ret } "); } [Theory] [InlineData("")] [InlineData(", out bool success")] public void RefReturningMethodAsReceiver_Success(string extraConstructorArg) { var code = @" using System; using System.Runtime.CompilerServices; C c = new C(1); GetC(ref c).M($""literal""); Console.WriteLine(c.I); ref C GetC(ref C c) { Console.WriteLine(""GetC""); return ref c; } public class C { public int I; public C(int i) { I = i; } public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref C c" + extraConstructorArg + @") : this(literalLength, formattedCount) { c = new C(2); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, verify: ExecutionConditionUtil.IsWindowsDesktop ? Verification.Skipped : Verification.Passes, expectedOutput: @" GetC literal:literal 2 "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 57 (0x39) .maxstack 4 .locals init (C V_0, //c C& V_1, CustomHandler V_2) IL_0000: ldc.i4.1 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: call ""ref C <Program>$.<<Main>$>g__GetC|0_0(ref C)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldind.ref IL_0011: ldc.i4.7 IL_0012: ldc.i4.0 IL_0013: ldloc.1 IL_0014: newobj ""CustomHandler..ctor(int, int, ref C)"" IL_0019: stloc.2 IL_001a: ldloca.s V_2 IL_001c: ldstr ""literal"" IL_0021: call ""bool CustomHandler.AppendLiteral(string)"" IL_0026: pop IL_0027: ldloc.2 IL_0028: callvirt ""void C.M(CustomHandler)"" IL_002d: ldloc.0 IL_002e: ldfld ""int C.I"" IL_0033: call ""void System.Console.WriteLine(int)"" IL_0038: ret } " : @" { // Code size 65 (0x41) .maxstack 5 .locals init (C V_0, //c C& V_1, CustomHandler V_2, bool V_3) IL_0000: ldc.i4.1 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: call ""ref C <Program>$.<<Main>$>g__GetC|0_0(ref C)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldind.ref IL_0011: ldc.i4.7 IL_0012: ldc.i4.0 IL_0013: ldloc.1 IL_0014: ldloca.s V_3 IL_0016: newobj ""CustomHandler..ctor(int, int, ref C, out bool)"" IL_001b: stloc.2 IL_001c: ldloc.3 IL_001d: brfalse.s IL_002d IL_001f: ldloca.s V_2 IL_0021: ldstr ""literal"" IL_0026: call ""bool CustomHandler.AppendLiteral(string)"" IL_002b: br.s IL_002e IL_002d: ldc.i4.0 IL_002e: pop IL_002f: ldloc.2 IL_0030: callvirt ""void C.M(CustomHandler)"" IL_0035: ldloc.0 IL_0036: ldfld ""int C.I"" IL_003b: call ""void System.Console.WriteLine(int)"" IL_0040: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { -1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [InlineData("")] [InlineData(", out bool success")] public void RefReturningMethodAsReceiver_Success_StructReceiver(string extraConstructorArg) { var code = @" using System; using System.Runtime.CompilerServices; C c = new C(1); GetC(ref c).M($""literal""); Console.WriteLine(c.I); ref C GetC(ref C c) { Console.WriteLine(""GetC""); return ref c; } public struct C { public int I; public C(int i) { I = i; } public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref C c" + extraConstructorArg + @") : this(literalLength, formattedCount) { c = new C(2); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, verify: ExecutionConditionUtil.IsWindowsDesktop ? Verification.Skipped : Verification.Passes, expectedOutput: @" GetC literal:literal 2 "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 57 (0x39) .maxstack 4 .locals init (C V_0, //c C& V_1, CustomHandler V_2) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: call ""C..ctor(int)"" IL_0008: ldloca.s V_0 IL_000a: call ""ref C <Program>$.<<Main>$>g__GetC|0_0(ref C)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.7 IL_0012: ldc.i4.0 IL_0013: ldloc.1 IL_0014: newobj ""CustomHandler..ctor(int, int, ref C)"" IL_0019: stloc.2 IL_001a: ldloca.s V_2 IL_001c: ldstr ""literal"" IL_0021: call ""bool CustomHandler.AppendLiteral(string)"" IL_0026: pop IL_0027: ldloc.2 IL_0028: call ""void C.M(CustomHandler)"" IL_002d: ldloc.0 IL_002e: ldfld ""int C.I"" IL_0033: call ""void System.Console.WriteLine(int)"" IL_0038: ret } " : @" { // Code size 65 (0x41) .maxstack 5 .locals init (C V_0, //c C& V_1, CustomHandler V_2, bool V_3) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: call ""C..ctor(int)"" IL_0008: ldloca.s V_0 IL_000a: call ""ref C <Program>$.<<Main>$>g__GetC|0_0(ref C)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.7 IL_0012: ldc.i4.0 IL_0013: ldloc.1 IL_0014: ldloca.s V_3 IL_0016: newobj ""CustomHandler..ctor(int, int, ref C, out bool)"" IL_001b: stloc.2 IL_001c: ldloc.3 IL_001d: brfalse.s IL_002d IL_001f: ldloca.s V_2 IL_0021: ldstr ""literal"" IL_0026: call ""bool CustomHandler.AppendLiteral(string)"" IL_002b: br.s IL_002e IL_002d: ldc.i4.0 IL_002e: pop IL_002f: ldloc.2 IL_0030: call ""void C.M(CustomHandler)"" IL_0035: ldloc.0 IL_0036: ldfld ""int C.I"" IL_003b: call ""void System.Console.WriteLine(int)"" IL_0040: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { -1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [InlineData("ref readonly")] [InlineData("")] public void RefReturningMethodAsReceiver_MismatchedRefness_01(string refness) { var code = @" using System.Runtime.CompilerServices; C c = new C(1); GetC().M($""literal""); " + refness + @" C GetC() => throw null; public class C { public C(int i) { } public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) { } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref C c) : this(literalLength, formattedCount) { } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (5,10): error CS1620: Argument 3 must be passed with the 'ref' keyword // GetC().M($"literal"); Diagnostic(ErrorCode.ERR_BadArgRef, @"$""literal""").WithArguments("3", "ref").WithLocation(5, 10) ); } [Theory] [InlineData("in")] [InlineData("")] public void RefReturningMethodAsReceiver_MismatchedRefness_02(string refness) { var code = @" using System.Runtime.CompilerServices; C c = new C(1); GetC(ref c).M($""literal""); ref C GetC(ref C c) => ref c; public class C { public C(int i) { } public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) { } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount," + refness + @" C c) : this(literalLength, formattedCount) { } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (5,15): error CS1615: Argument 3 may not be passed with the 'ref' keyword // GetC(ref c).M($"literal"); Diagnostic(ErrorCode.ERR_BadArgExtraRef, @"$""literal""").WithArguments("3", "ref").WithLocation(5, 15) ); } [Fact] public void StructReceiver_Rvalue() { var code = @" using System; using System.Runtime.CompilerServices; S s1 = new S { I = 1 }; S s2 = new S { I = 2 }; s1.M(s2, $""""); public struct S { public int I; public void M(S s2, [InterpolatedStringHandlerArgument("""", ""s2"")]CustomHandler handler) { Console.WriteLine(""s1.I:"" + this.I.ToString()); Console.WriteLine(""s2.I:"" + s2.I.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, S s1, S s2) : this(literalLength, formattedCount) { s1.I = 3; s2.I = 4; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" s1.I:1 s2.I:2"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 56 (0x38) .maxstack 6 .locals init (S V_0, //s2 S V_1, S V_2) IL_0000: ldloca.s V_1 IL_0002: initobj ""S"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: stfld ""int S.I"" IL_0010: ldloc.1 IL_0011: ldloca.s V_1 IL_0013: initobj ""S"" IL_0019: ldloca.s V_1 IL_001b: ldc.i4.2 IL_001c: stfld ""int S.I"" IL_0021: ldloc.1 IL_0022: stloc.0 IL_0023: stloc.1 IL_0024: ldloca.s V_1 IL_0026: ldloc.0 IL_0027: stloc.2 IL_0028: ldloc.2 IL_0029: ldc.i4.0 IL_002a: ldc.i4.0 IL_002b: ldloc.1 IL_002c: ldloc.2 IL_002d: newobj ""CustomHandler..ctor(int, int, S, S)"" IL_0032: call ""void S.M(S, CustomHandler)"" IL_0037: ret } "); } [Fact] public void StructReceiver_Lvalue() { var code = @" using System; using System.Runtime.CompilerServices; S s1 = new S { I = 1 }; S s2 = new S { I = 2 }; s1.M(ref s2, $""""); public struct S { public int I; public void M(ref S s2, [InterpolatedStringHandlerArgument("""", ""s2"")]CustomHandler handler) { Console.WriteLine(""s1.I:"" + this.I.ToString()); Console.WriteLine(""s2.I:"" + s2.I.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref S s1, ref S s2) : this(literalLength, formattedCount) { s1.I = 3; s2.I = 4; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (8,14): error CS1620: Argument 3 must be passed with the 'ref' keyword // s1.M(ref s2, $""); Diagnostic(ErrorCode.ERR_BadArgRef, @"$""""").WithArguments("3", "ref").WithLocation(8, 14) ); } [Fact] public void StructParameter_ByVal() { var code = @" using System; using System.Runtime.CompilerServices; S s = new S { I = 1 }; S.M(s, $""""); public struct S { public int I; public static void M(S s, [InterpolatedStringHandlerArgument(""s"")]CustomHandler handler) { Console.WriteLine(""s.I:"" + s.I.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, S s) : this(literalLength, formattedCount) { s.I = 2; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @"s.I:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 33 (0x21) .maxstack 4 .locals init (S V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloca.s V_0 IL_000a: ldc.i4.1 IL_000b: stfld ""int S.I"" IL_0010: ldloc.0 IL_0011: stloc.0 IL_0012: ldloc.0 IL_0013: ldc.i4.0 IL_0014: ldc.i4.0 IL_0015: ldloc.0 IL_0016: newobj ""CustomHandler..ctor(int, int, S)"" IL_001b: call ""void S.M(S, CustomHandler)"" IL_0020: ret } "); } [Fact] public void StructParameter_ByRef() { var code = @" using System; using System.Runtime.CompilerServices; S s = new S { I = 1 }; S.M(ref s, $""""); public struct S { public int I; public static void M(ref S s, [InterpolatedStringHandlerArgument(""s"")]CustomHandler handler) { Console.WriteLine(""s.I:"" + s.I.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref S s) : this(literalLength, formattedCount) { s.I = 2; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @"s.I:2"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 36 (0x24) .maxstack 4 .locals init (S V_0, //s S V_1, S& V_2) IL_0000: ldloca.s V_1 IL_0002: initobj ""S"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: stfld ""int S.I"" IL_0010: ldloc.1 IL_0011: stloc.0 IL_0012: ldloca.s V_0 IL_0014: stloc.2 IL_0015: ldloc.2 IL_0016: ldc.i4.0 IL_0017: ldc.i4.0 IL_0018: ldloc.2 IL_0019: newobj ""CustomHandler..ctor(int, int, ref S)"" IL_001e: call ""void S.M(ref S, CustomHandler)"" IL_0023: ret } "); } [Theory] [CombinatorialData] public void SideEffects(bool useBoolReturns, bool validityParameter) { var code = @" using System; using System.Runtime.CompilerServices; GetReceiver().M( GetArg(""Unrelated parameter 1""), GetArg(""Second value""), GetArg(""Unrelated parameter 2""), GetArg(""First value""), $""literal"", GetArg(""Unrelated parameter 4"")); C GetReceiver() { Console.WriteLine(""GetReceiver""); return new C() { Prop = ""Prop"" }; } string GetArg(string s) { Console.WriteLine(s); return s; } public class C { public string Prop { get; set; } public void M(string param1, string param2, string param3, string param4, [InterpolatedStringHandlerArgument(""param4"", """", ""param2"")] CustomHandler c, string param6) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s1, C c, string s2" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""Handler constructor""); _builder.AppendLine(""s1:"" + s1); _builder.AppendLine(""c.Prop:"" + c.Prop); _builder.AppendLine(""s2:"" + s2); " + (validityParameter ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns); var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }, expectedOutput: @" GetReceiver Unrelated parameter 1 Second value Unrelated parameter 2 First value Handler constructor Unrelated parameter 4 s1:First value c.Prop:Prop s2:Second value literal:literal "); verifier.VerifyDiagnostics(); } [Fact] public void InterpolatedStringHandlerArgumentsAttribute_ConversionFromArgumentType() { var code = @" using System; using System.Globalization; using System.Runtime.CompilerServices; int i = 1; C.M(i, $""literal""); public class C { public static implicit operator C(int i) => throw null; public static implicit operator C(double d) { Console.WriteLine(d.ToString(""G"", CultureInfo.InvariantCulture)); return new C(); } public override string ToString() => ""C""; public static void M(double d, [InterpolatedStringHandlerArgument(""d"")] CustomHandler handler) => Console.WriteLine(handler.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, C c) : this(literalLength, formattedCount) { } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" 1 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 39 (0x27) .maxstack 5 .locals init (double V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: conv.r8 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldloca.s V_1 IL_0006: ldc.i4.7 IL_0007: ldc.i4.0 IL_0008: ldloc.0 IL_0009: call ""C C.op_Implicit(double)"" IL_000e: call ""CustomHandler..ctor(int, int, C)"" IL_0013: ldloca.s V_1 IL_0015: ldstr ""literal"" IL_001a: call ""bool CustomHandler.AppendLiteral(string)"" IL_001f: pop IL_0020: ldloc.1 IL_0021: call ""void C.M(double, CustomHandler)"" IL_0026: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentsAttribute_CompoundAssignment_Indexer_01(bool useBoolReturns, bool validityParameter) { var code = @" using System; using System.Runtime.CompilerServices; int i = 3; GetC()[GetInt(1), $""literal{i}""] += GetInt(2); static C GetC() { Console.WriteLine(""GetC""); return new C() { Prop = 2 }; } static int GetInt(int i) { Console.WriteLine(""GetInt"" + i.ToString()); return 1; } public class C { public int Prop { get; set; } public int this[int arg1, [InterpolatedStringHandlerArgument(""arg1"", """")] CustomHandler c] { get { Console.WriteLine(""Indexer getter""); return 0; } set { Console.WriteLine(""Indexer setter""); Console.WriteLine(c.ToString()); } } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int arg1, C c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""Handler constructor""); _builder.AppendLine(""arg1:"" + arg1); _builder.AppendLine(""C.Prop:"" + c.Prop.ToString()); " + (validityParameter ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" GetC GetInt1 Handler constructor Indexer getter GetInt2 Indexer setter arg1:1 C.Prop:2 literal:literal value:3 alignment:0 format: "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 85 (0x55) .maxstack 6 .locals init (int V_0, //i int V_1, C V_2, int V_3, CustomHandler V_4, CustomHandler V_5) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldc.i4.1 IL_0009: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: stloc.3 IL_0011: ldloca.s V_5 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_5 IL_001e: ldstr ""literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_5 IL_002a: ldloc.0 IL_002b: box ""int"" IL_0030: ldc.i4.0 IL_0031: ldnull IL_0032: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0037: ldloc.s V_5 IL_0039: stloc.s V_4 IL_003b: ldloc.2 IL_003c: ldloc.3 IL_003d: ldloc.s V_4 IL_003f: ldloc.2 IL_0040: ldloc.3 IL_0041: ldloc.s V_4 IL_0043: callvirt ""int C.this[int, CustomHandler].get"" IL_0048: ldc.i4.2 IL_0049: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_004e: add IL_004f: callvirt ""void C.this[int, CustomHandler].set"" IL_0054: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 96 (0x60) .maxstack 6 .locals init (int V_0, //i int V_1, C V_2, int V_3, CustomHandler V_4, CustomHandler V_5, bool V_6) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldc.i4.1 IL_0009: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: stloc.3 IL_0011: ldc.i4.7 IL_0012: ldc.i4.1 IL_0013: ldloc.1 IL_0014: ldloc.2 IL_0015: ldloca.s V_6 IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001c: stloc.s V_5 IL_001e: ldloc.s V_6 IL_0020: brfalse.s IL_0040 IL_0022: ldloca.s V_5 IL_0024: ldstr ""literal"" IL_0029: call ""void CustomHandler.AppendLiteral(string)"" IL_002e: ldloca.s V_5 IL_0030: ldloc.0 IL_0031: box ""int"" IL_0036: ldc.i4.0 IL_0037: ldnull IL_0038: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_003d: ldc.i4.1 IL_003e: br.s IL_0041 IL_0040: ldc.i4.0 IL_0041: pop IL_0042: ldloc.s V_5 IL_0044: stloc.s V_4 IL_0046: ldloc.2 IL_0047: ldloc.3 IL_0048: ldloc.s V_4 IL_004a: ldloc.2 IL_004b: ldloc.3 IL_004c: ldloc.s V_4 IL_004e: callvirt ""int C.this[int, CustomHandler].get"" IL_0053: ldc.i4.2 IL_0054: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_0059: add IL_005a: callvirt ""void C.this[int, CustomHandler].set"" IL_005f: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 91 (0x5b) .maxstack 6 .locals init (int V_0, //i int V_1, C V_2, int V_3, CustomHandler V_4, CustomHandler V_5) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldc.i4.1 IL_0009: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: stloc.3 IL_0011: ldloca.s V_5 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_5 IL_001e: ldstr ""literal"" IL_0023: call ""bool CustomHandler.AppendLiteral(string)"" IL_0028: brfalse.s IL_003b IL_002a: ldloca.s V_5 IL_002c: ldloc.0 IL_002d: box ""int"" IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0039: br.s IL_003c IL_003b: ldc.i4.0 IL_003c: pop IL_003d: ldloc.s V_5 IL_003f: stloc.s V_4 IL_0041: ldloc.2 IL_0042: ldloc.3 IL_0043: ldloc.s V_4 IL_0045: ldloc.2 IL_0046: ldloc.3 IL_0047: ldloc.s V_4 IL_0049: callvirt ""int C.this[int, CustomHandler].get"" IL_004e: ldc.i4.2 IL_004f: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_0054: add IL_0055: callvirt ""void C.this[int, CustomHandler].set"" IL_005a: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 97 (0x61) .maxstack 6 .locals init (int V_0, //i int V_1, C V_2, int V_3, CustomHandler V_4, CustomHandler V_5, bool V_6) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldc.i4.1 IL_0009: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: stloc.3 IL_0011: ldc.i4.7 IL_0012: ldc.i4.1 IL_0013: ldloc.1 IL_0014: ldloc.2 IL_0015: ldloca.s V_6 IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001c: stloc.s V_5 IL_001e: ldloc.s V_6 IL_0020: brfalse.s IL_0041 IL_0022: ldloca.s V_5 IL_0024: ldstr ""literal"" IL_0029: call ""bool CustomHandler.AppendLiteral(string)"" IL_002e: brfalse.s IL_0041 IL_0030: ldloca.s V_5 IL_0032: ldloc.0 IL_0033: box ""int"" IL_0038: ldc.i4.0 IL_0039: ldnull IL_003a: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_003f: br.s IL_0042 IL_0041: ldc.i4.0 IL_0042: pop IL_0043: ldloc.s V_5 IL_0045: stloc.s V_4 IL_0047: ldloc.2 IL_0048: ldloc.3 IL_0049: ldloc.s V_4 IL_004b: ldloc.2 IL_004c: ldloc.3 IL_004d: ldloc.s V_4 IL_004f: callvirt ""int C.this[int, CustomHandler].get"" IL_0054: ldc.i4.2 IL_0055: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_005a: add IL_005b: callvirt ""void C.this[int, CustomHandler].set"" IL_0060: ret } ", }; } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentsAttribute_CompoundAssignment_Indexer_02(bool useBoolReturns, bool validityParameter) { var code = @" using System; using System.Runtime.CompilerServices; int i = 3; GetC()[GetInt(1), $""literal{i}""] += GetInt(2); static C GetC() { Console.WriteLine(""GetC""); return new C() { Prop = 2 }; } static int GetInt(int i) { Console.WriteLine(""GetInt"" + i.ToString()); return 1; } public class C { private int field; public int Prop { get; set; } public ref int this[int arg1, [InterpolatedStringHandlerArgument(""arg1"", """")] CustomHandler c] { get { Console.WriteLine(""Indexer getter""); Console.WriteLine(c.ToString()); return ref field; } } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int arg1, C c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""Handler constructor""); _builder.AppendLine(""arg1:"" + arg1); _builder.AppendLine(""C.Prop:"" + c.Prop.ToString()); " + (validityParameter ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" GetC GetInt1 Handler constructor Indexer getter arg1:1 C.Prop:2 literal:literal value:3 alignment:0 format: GetInt2 "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 72 (0x48) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldloca.s V_3 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_3 IL_001e: ldstr ""literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_3 IL_002a: ldloc.0 IL_002b: box ""int"" IL_0030: ldc.i4.0 IL_0031: ldnull IL_0032: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0037: ldloc.3 IL_0038: callvirt ""ref int C.this[int, CustomHandler].get"" IL_003d: dup IL_003e: ldind.i4 IL_003f: ldc.i4.2 IL_0040: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_0045: add IL_0046: stind.i4 IL_0047: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 82 (0x52) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.7 IL_0012: ldc.i4.1 IL_0013: ldloc.1 IL_0014: ldloc.2 IL_0015: ldloca.s V_4 IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001c: stloc.3 IL_001d: ldloc.s V_4 IL_001f: brfalse.s IL_003f IL_0021: ldloca.s V_3 IL_0023: ldstr ""literal"" IL_0028: call ""void CustomHandler.AppendLiteral(string)"" IL_002d: ldloca.s V_3 IL_002f: ldloc.0 IL_0030: box ""int"" IL_0035: ldc.i4.0 IL_0036: ldnull IL_0037: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_003c: ldc.i4.1 IL_003d: br.s IL_0040 IL_003f: ldc.i4.0 IL_0040: pop IL_0041: ldloc.3 IL_0042: callvirt ""ref int C.this[int, CustomHandler].get"" IL_0047: dup IL_0048: ldind.i4 IL_0049: ldc.i4.2 IL_004a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_004f: add IL_0050: stind.i4 IL_0051: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 78 (0x4e) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldloca.s V_3 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_3 IL_001e: ldstr ""literal"" IL_0023: call ""bool CustomHandler.AppendLiteral(string)"" IL_0028: brfalse.s IL_003b IL_002a: ldloca.s V_3 IL_002c: ldloc.0 IL_002d: box ""int"" IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0039: br.s IL_003c IL_003b: ldc.i4.0 IL_003c: pop IL_003d: ldloc.3 IL_003e: callvirt ""ref int C.this[int, CustomHandler].get"" IL_0043: dup IL_0044: ldind.i4 IL_0045: ldc.i4.2 IL_0046: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_004b: add IL_004c: stind.i4 IL_004d: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 83 (0x53) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.7 IL_0012: ldc.i4.1 IL_0013: ldloc.1 IL_0014: ldloc.2 IL_0015: ldloca.s V_4 IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001c: stloc.3 IL_001d: ldloc.s V_4 IL_001f: brfalse.s IL_0040 IL_0021: ldloca.s V_3 IL_0023: ldstr ""literal"" IL_0028: call ""bool CustomHandler.AppendLiteral(string)"" IL_002d: brfalse.s IL_0040 IL_002f: ldloca.s V_3 IL_0031: ldloc.0 IL_0032: box ""int"" IL_0037: ldc.i4.0 IL_0038: ldnull IL_0039: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_003e: br.s IL_0041 IL_0040: ldc.i4.0 IL_0041: pop IL_0042: ldloc.3 IL_0043: callvirt ""ref int C.this[int, CustomHandler].get"" IL_0048: dup IL_0049: ldind.i4 IL_004a: ldc.i4.2 IL_004b: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_0050: add IL_0051: stind.i4 IL_0052: ret } ", }; } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentsAttribute_CompoundAssignment_RefReturningMethod(bool useBoolReturns, bool validityParameter) { var code = @" using System; using System.Runtime.CompilerServices; int i = 3; GetC().M(GetInt(1), $""literal{i}"") += GetInt(2); static C GetC() { Console.WriteLine(""GetC""); return new C() { Prop = 2 }; } static int GetInt(int i) { Console.WriteLine(""GetInt"" + i.ToString()); return 1; } public class C { private int field; public int Prop { get; set; } public ref int M(int arg1, [InterpolatedStringHandlerArgument(""arg1"", """")] CustomHandler c) { Console.WriteLine(""M""); Console.WriteLine(c.ToString()); return ref field; } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int arg1, C c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""Handler constructor""); _builder.AppendLine(""arg1:"" + arg1); _builder.AppendLine(""C.Prop:"" + c.Prop.ToString()); " + (validityParameter ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" GetC GetInt1 Handler constructor M arg1:1 C.Prop:2 literal:literal value:3 alignment:0 format: GetInt2 "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 72 (0x48) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldloca.s V_3 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_3 IL_001e: ldstr ""literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_3 IL_002a: ldloc.0 IL_002b: box ""int"" IL_0030: ldc.i4.0 IL_0031: ldnull IL_0032: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0037: ldloc.3 IL_0038: callvirt ""ref int C.M(int, CustomHandler)"" IL_003d: dup IL_003e: ldind.i4 IL_003f: ldc.i4.2 IL_0040: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_0045: add IL_0046: stind.i4 IL_0047: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 82 (0x52) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.7 IL_0012: ldc.i4.1 IL_0013: ldloc.1 IL_0014: ldloc.2 IL_0015: ldloca.s V_4 IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001c: stloc.3 IL_001d: ldloc.s V_4 IL_001f: brfalse.s IL_003f IL_0021: ldloca.s V_3 IL_0023: ldstr ""literal"" IL_0028: call ""void CustomHandler.AppendLiteral(string)"" IL_002d: ldloca.s V_3 IL_002f: ldloc.0 IL_0030: box ""int"" IL_0035: ldc.i4.0 IL_0036: ldnull IL_0037: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_003c: ldc.i4.1 IL_003d: br.s IL_0040 IL_003f: ldc.i4.0 IL_0040: pop IL_0041: ldloc.3 IL_0042: callvirt ""ref int C.M(int, CustomHandler)"" IL_0047: dup IL_0048: ldind.i4 IL_0049: ldc.i4.2 IL_004a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_004f: add IL_0050: stind.i4 IL_0051: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 78 (0x4e) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldloca.s V_3 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_3 IL_001e: ldstr ""literal"" IL_0023: call ""bool CustomHandler.AppendLiteral(string)"" IL_0028: brfalse.s IL_003b IL_002a: ldloca.s V_3 IL_002c: ldloc.0 IL_002d: box ""int"" IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0039: br.s IL_003c IL_003b: ldc.i4.0 IL_003c: pop IL_003d: ldloc.3 IL_003e: callvirt ""ref int C.M(int, CustomHandler)"" IL_0043: dup IL_0044: ldind.i4 IL_0045: ldc.i4.2 IL_0046: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_004b: add IL_004c: stind.i4 IL_004d: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 83 (0x53) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.7 IL_0012: ldc.i4.1 IL_0013: ldloc.1 IL_0014: ldloc.2 IL_0015: ldloca.s V_4 IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001c: stloc.3 IL_001d: ldloc.s V_4 IL_001f: brfalse.s IL_0040 IL_0021: ldloca.s V_3 IL_0023: ldstr ""literal"" IL_0028: call ""bool CustomHandler.AppendLiteral(string)"" IL_002d: brfalse.s IL_0040 IL_002f: ldloca.s V_3 IL_0031: ldloc.0 IL_0032: box ""int"" IL_0037: ldc.i4.0 IL_0038: ldnull IL_0039: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_003e: br.s IL_0041 IL_0040: ldc.i4.0 IL_0041: pop IL_0042: ldloc.3 IL_0043: callvirt ""ref int C.M(int, CustomHandler)"" IL_0048: dup IL_0049: ldind.i4 IL_004a: ldc.i4.2 IL_004b: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_0050: add IL_0051: stind.i4 IL_0052: ret } ", }; } [Fact] public void InterpolatedStringHandlerArgumentsAttribute_CollectionInitializerAdd() { var code = @" using System; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; _ = new C(1) { $""literal"" }; public class C : IEnumerable<int> { public int Field; public C(int i) { Field = i; } public void Add([InterpolatedStringHandlerArgument("""")] CustomHandler c) { Console.WriteLine(c.ToString()); } public IEnumerator<int> GetEnumerator() => throw null; IEnumerator IEnumerable.GetEnumerator() => throw null; } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, C c) : this(literalLength, formattedCount) { _builder.AppendLine(""c.Field:"" + c.Field.ToString()); } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" c.Field:1 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 37 (0x25) .maxstack 5 .locals init (C V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldloca.s V_1 IL_000a: ldc.i4.7 IL_000b: ldc.i4.0 IL_000c: ldloc.0 IL_000d: call ""CustomHandler..ctor(int, int, C)"" IL_0012: ldloca.s V_1 IL_0014: ldstr ""literal"" IL_0019: call ""void CustomHandler.AppendLiteral(string)"" IL_001e: ldloc.1 IL_001f: callvirt ""void C.Add(CustomHandler)"" IL_0024: ret } "); } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_AttributeOnAppendFormatCall(bool useBoolReturns, bool validityParameter) { var code = @" using System; using System.Runtime.CompilerServices; C.M(1, $""{$""Inner string""}{2}""); class C { public static void M(int i, [InterpolatedStringHandlerArgument(""i"")]CustomHandler handler) { Console.WriteLine(handler.ToString()); } } public partial class CustomHandler { private int I = 0; public CustomHandler(int literalLength, int formattedCount, int i" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""int constructor""); I = i; " + (validityParameter ? "success = true;" : "") + @" } public CustomHandler(int literalLength, int formattedCount, CustomHandler c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""CustomHandler constructor""); _builder.AppendLine(""c.I:"" + c.I.ToString()); " + (validityParameter ? "success = true;" : "") + @" } public " + (useBoolReturns ? "bool" : "void") + @" AppendFormatted([InterpolatedStringHandlerArgument("""")]CustomHandler c) { _builder.AppendLine(""CustomHandler AppendFormatted""); _builder.Append(c.ToString()); " + (useBoolReturns ? "return true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" int constructor CustomHandler constructor CustomHandler AppendFormatted c.I:1 literal:Inner string value:2 alignment:0 format: "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 59 (0x3b) .maxstack 6 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.2 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: dup IL_000c: stloc.1 IL_000d: ldloc.1 IL_000e: ldc.i4.s 12 IL_0010: ldc.i4.0 IL_0011: ldloc.1 IL_0012: newobj ""CustomHandler..ctor(int, int, CustomHandler)"" IL_0017: dup IL_0018: ldstr ""Inner string"" IL_001d: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0022: callvirt ""void CustomHandler.AppendFormatted(CustomHandler)"" IL_0027: dup IL_0028: ldc.i4.2 IL_0029: box ""int"" IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0035: call ""void C.M(int, CustomHandler)"" IL_003a: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 87 (0x57) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2, CustomHandler V_3, CustomHandler V_4, bool V_5) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.2 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000d: stloc.1 IL_000e: ldloc.2 IL_000f: brfalse.s IL_004e IL_0011: ldloc.1 IL_0012: stloc.3 IL_0013: ldloc.3 IL_0014: ldc.i4.s 12 IL_0016: ldc.i4.0 IL_0017: ldloc.3 IL_0018: ldloca.s V_5 IL_001a: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)"" IL_001f: stloc.s V_4 IL_0021: ldloc.s V_5 IL_0023: brfalse.s IL_0034 IL_0025: ldloc.s V_4 IL_0027: ldstr ""Inner string"" IL_002c: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0031: ldc.i4.1 IL_0032: br.s IL_0035 IL_0034: ldc.i4.0 IL_0035: pop IL_0036: ldloc.s V_4 IL_0038: callvirt ""void CustomHandler.AppendFormatted(CustomHandler)"" IL_003d: ldloc.1 IL_003e: ldc.i4.2 IL_003f: box ""int"" IL_0044: ldc.i4.0 IL_0045: ldnull IL_0046: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_004b: ldc.i4.1 IL_004c: br.s IL_004f IL_004e: ldc.i4.0 IL_004f: pop IL_0050: ldloc.1 IL_0051: call ""void C.M(int, CustomHandler)"" IL_0056: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 68 (0x44) .maxstack 5 .locals init (int V_0, CustomHandler V_1, CustomHandler V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.2 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: stloc.2 IL_000e: ldloc.2 IL_000f: ldc.i4.s 12 IL_0011: ldc.i4.0 IL_0012: ldloc.2 IL_0013: newobj ""CustomHandler..ctor(int, int, CustomHandler)"" IL_0018: dup IL_0019: ldstr ""Inner string"" IL_001e: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0023: pop IL_0024: callvirt ""bool CustomHandler.AppendFormatted(CustomHandler)"" IL_0029: brfalse.s IL_003b IL_002b: ldloc.1 IL_002c: ldc.i4.2 IL_002d: box ""int"" IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0039: br.s IL_003c IL_003b: ldc.i4.0 IL_003c: pop IL_003d: ldloc.1 IL_003e: call ""void C.M(int, CustomHandler)"" IL_0043: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 87 (0x57) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2, CustomHandler V_3, CustomHandler V_4, bool V_5) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.2 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000d: stloc.1 IL_000e: ldloc.2 IL_000f: brfalse.s IL_004e IL_0011: ldloc.1 IL_0012: stloc.3 IL_0013: ldloc.3 IL_0014: ldc.i4.s 12 IL_0016: ldc.i4.0 IL_0017: ldloc.3 IL_0018: ldloca.s V_5 IL_001a: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)"" IL_001f: stloc.s V_4 IL_0021: ldloc.s V_5 IL_0023: brfalse.s IL_0033 IL_0025: ldloc.s V_4 IL_0027: ldstr ""Inner string"" IL_002c: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0031: br.s IL_0034 IL_0033: ldc.i4.0 IL_0034: pop IL_0035: ldloc.s V_4 IL_0037: callvirt ""bool CustomHandler.AppendFormatted(CustomHandler)"" IL_003c: brfalse.s IL_004e IL_003e: ldloc.1 IL_003f: ldc.i4.2 IL_0040: box ""int"" IL_0045: ldc.i4.0 IL_0046: ldnull IL_0047: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_004c: br.s IL_004f IL_004e: ldc.i4.0 IL_004f: pop IL_0050: ldloc.1 IL_0051: call ""void C.M(int, CustomHandler)"" IL_0056: ret } ", }; } [Fact] public void DiscardsUsedAsParameters() { var code = @" using System; using System.Runtime.CompilerServices; C.M(out _, $""literal""); public class C { public static void M(out int i, [InterpolatedStringHandlerArgument(""i"")]CustomHandler c) { i = 0; Console.WriteLine(c.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, out int i) : this(literalLength, formattedCount) { i = 1; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @"literal:literal"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 31 (0x1f) .maxstack 4 .locals init (int V_0, CustomHandler V_1) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.0 IL_0004: ldloca.s V_0 IL_0006: newobj ""CustomHandler..ctor(int, int, out int)"" IL_000b: stloc.1 IL_000c: ldloca.s V_1 IL_000e: ldstr ""literal"" IL_0013: call ""void CustomHandler.AppendLiteral(string)"" IL_0018: ldloc.1 IL_0019: call ""void C.M(out int, CustomHandler)"" IL_001e: ret } "); } [Fact] public void DiscardsUsedAsParameters_DefinedInVB() { var vb = @" Imports System Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Public Class C Public Shared Sub M(<Out> ByRef i As Integer, <InterpolatedStringHandlerArgument(""i"")>c As CustomHandler) Console.WriteLine(i) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler Public Sub New(literalLength As Integer, formattedCount As Integer, <Out> ByRef i As Integer) i = 1 End Sub End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vb, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var code = @"C.M(out _, $"""");"; var comp = CreateCompilation(code, new[] { vbComp.EmitToImageReference() }); var verifier = CompileAndVerify(comp, expectedOutput: @"1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 17 (0x11) .maxstack 4 .locals init (int V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.0 IL_0003: ldc.i4.0 IL_0004: ldloca.s V_0 IL_0006: newobj ""CustomHandler..ctor(int, int, out int)"" IL_000b: call ""void C.M(out int, CustomHandler)"" IL_0010: ret } "); } [Fact] public void DisallowedInExpressionTrees() { var code = @" using System; using System.Linq.Expressions; Expression<Func<CustomHandler>> expr = () => $""""; "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, handler }); comp.VerifyDiagnostics( // (5,46): error CS8952: An expression tree may not contain an interpolated string handler conversion. // Expression<Func<CustomHandler>> expr = () => $""; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsInterpolatedStringHandlerConversion, @"$""""").WithLocation(5, 46) ); } [Theory] [CombinatorialData] public void CustomHandlerUsedAsArgumentToCustomHandler(bool useBoolReturns, bool validityParameter) { var code = @" using System; using System.Runtime.CompilerServices; C.M(1, $"""", $""""); public class C { public static void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c1, [InterpolatedStringHandlerArgument(""c1"")] CustomHandler c2) => Console.WriteLine(c2.ToString()); } public partial class CustomHandler { private int i; public CustomHandler(int literalLength, int formattedCount, int i" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); this.i = i; " + (validityParameter ? "success = true;" : "") + @" } public CustomHandler(int literalLength, int formattedCount, CustomHandler c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { _builder.AppendLine(""c.i:"" + c.i.ToString()); " + (validityParameter ? "success = true;" : "") + @" } }"; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: "c.i:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 27 (0x1b) .maxstack 5 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: ldc.i4.0 IL_000e: ldc.i4.0 IL_000f: ldloc.1 IL_0010: newobj ""CustomHandler..ctor(int, int, CustomHandler)"" IL_0015: call ""void C.M(int, CustomHandler, CustomHandler)"" IL_001a: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 31 (0x1f) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000d: stloc.1 IL_000e: ldloc.1 IL_000f: ldc.i4.0 IL_0010: ldc.i4.0 IL_0011: ldloc.1 IL_0012: ldloca.s V_2 IL_0014: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)"" IL_0019: call ""void C.M(int, CustomHandler, CustomHandler)"" IL_001e: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 27 (0x1b) .maxstack 5 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: ldc.i4.0 IL_000e: ldc.i4.0 IL_000f: ldloc.1 IL_0010: newobj ""CustomHandler..ctor(int, int, CustomHandler)"" IL_0015: call ""void C.M(int, CustomHandler, CustomHandler)"" IL_001a: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 31 (0x1f) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000d: stloc.1 IL_000e: ldloc.1 IL_000f: ldc.i4.0 IL_0010: ldc.i4.0 IL_0011: ldloc.1 IL_0012: ldloca.s V_2 IL_0014: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)"" IL_0019: call ""void C.M(int, CustomHandler, CustomHandler)"" IL_001e: ret } ", }; } [Theory] [CombinatorialData] public void DefiniteAssignment_01(bool useBoolReturns, bool trailingOutParameter) { var code = @" int i; string s; CustomHandler c = $""{i = 1}{M(out var o)}{s = o.ToString()}""; _ = i.ToString(); _ = o.ToString(); _ = s.ToString(); string M(out object o) { o = null; return null; } "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns, includeTrailingOutConstructorParameter: trailingOutParameter); var comp = CreateCompilation(new[] { code, customHandler }); if (trailingOutParameter) { comp.VerifyDiagnostics( // (6,5): error CS0165: Use of unassigned local variable 'i' // _ = i.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(6, 5), // (7,5): error CS0165: Use of unassigned local variable 'o' // _ = o.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "o").WithArguments("o").WithLocation(7, 5), // (8,5): error CS0165: Use of unassigned local variable 's' // _ = s.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "s").WithArguments("s").WithLocation(8, 5) ); } else if (useBoolReturns) { comp.VerifyDiagnostics( // (7,5): error CS0165: Use of unassigned local variable 'o' // _ = o.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "o").WithArguments("o").WithLocation(7, 5), // (8,5): error CS0165: Use of unassigned local variable 's' // _ = s.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "s").WithArguments("s").WithLocation(8, 5) ); } else { comp.VerifyDiagnostics(); } } [Theory] [CombinatorialData] public void DefiniteAssignment_02(bool useBoolReturns, bool trailingOutParameter) { var code = @" int i; CustomHandler c = $""{i = 1}""; _ = i.ToString(); "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns, includeTrailingOutConstructorParameter: trailingOutParameter); var comp = CreateCompilation(new[] { code, customHandler }); if (trailingOutParameter) { comp.VerifyDiagnostics( // (5,5): error CS0165: Use of unassigned local variable 'i' // _ = i.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(5, 5) ); } else { comp.VerifyDiagnostics(); } } [Fact] public void DynamicConstruction_01() { var code = @" using System.Runtime.CompilerServices; dynamic d = 1; M(d, $""""); void M(dynamic d, [InterpolatedStringHandlerArgument(""d"")]CustomHandler c) {} public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, dynamic d) : this() {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute }); comp.VerifyDiagnostics( // (4,6): error CS8953: An interpolated string handler construction cannot use dynamic. Manually construct an instance of 'CustomHandler'. // M(d, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, @"$""""").WithArguments("CustomHandler").WithLocation(4, 6) ); } [Fact] public void DynamicConstruction_02() { var code = @" using System.Runtime.CompilerServices; int i = 1; M(i, $""""); void M(dynamic d, [InterpolatedStringHandlerArgument(""d"")]CustomHandler c) {} public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, dynamic d) : this() {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute }); comp.VerifyDiagnostics( // (4,6): error CS8953: An interpolated string handler construction cannot use dynamic. Manually construct an instance of 'CustomHandler'. // M(d, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, @"$""""").WithArguments("CustomHandler").WithLocation(4, 6) ); } [Fact] public void DynamicConstruction_03() { var code = @" using System; using System.Runtime.CompilerServices; int i = 1; M(i, $""""); void M(int i, [InterpolatedStringHandlerArgument(""i"")]CustomHandler c) {} public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, dynamic d) : this(literalLength, formattedCount) { Console.WriteLine(""d:"" + d.ToString()); } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false, includeOneTimeHelpers: false); var comp = CreateCompilation(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "d:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 22 (0x16) .maxstack 4 .locals init (int V_0) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: box ""int"" IL_000b: newobj ""CustomHandler..ctor(int, int, dynamic)"" IL_0010: call ""void <Program>$.<<Main>$>g__M|0_0(int, CustomHandler)"" IL_0015: ret } "); } [Fact] public void DynamicConstruction_04() { var code = @" using System; using System.Runtime.CompilerServices; M($""""); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(dynamic literalLength, int formattedCount) { Console.WriteLine(""ctor""); } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "ctor"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 18 (0x12) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: box ""int"" IL_0006: ldc.i4.0 IL_0007: newobj ""CustomHandler..ctor(dynamic, int)"" IL_000c: call ""void <Program>$.<<Main>$>g__M|0_0(CustomHandler)"" IL_0011: ret } "); } [Fact] public void DynamicConstruction_05() { var code = @" using System; using System.Runtime.CompilerServices; M($""""); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { Console.WriteLine(""ctor""); } public CustomHandler(dynamic literalLength, int formattedCount) { throw null; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "ctor"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: ldc.i4.0 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: call ""void <Program>$.<<Main>$>g__M|0_0(CustomHandler)"" IL_000c: ret } "); } [Fact] public void DynamicConstruction_06() { var code = @" using System; using System.Runtime.CompilerServices; M($""Literal""); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } public void AppendLiteral(dynamic d) { Console.WriteLine(""AppendLiteral""); } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "AppendLiteral"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 28 (0x1c) .maxstack 3 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.0 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldstr ""Literal"" IL_0010: call ""void CustomHandler.AppendLiteral(dynamic)"" IL_0015: ldloc.0 IL_0016: call ""void <Program>$.<<Main>$>g__M|0_0(CustomHandler)"" IL_001b: ret } "); } [Fact] public void DynamicConstruction_07() { var code = @" using System; using System.Runtime.CompilerServices; M($""{1}""); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } public void AppendFormatted(dynamic d) { Console.WriteLine(""AppendFormatted""); } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "AppendFormatted"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 29 (0x1d) .maxstack 3 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.0 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: call ""void CustomHandler.AppendFormatted(dynamic)"" IL_0016: ldloc.0 IL_0017: call ""void <Program>$.<<Main>$>g__M|0_0(CustomHandler)"" IL_001c: ret } "); } [Fact] public void DynamicConstruction_08() { var code = @" using System; using System.Runtime.CompilerServices; dynamic d = 1; M($""literal{d}""); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } public void AppendLiteral(dynamic d) { Console.WriteLine(""AppendLiteral""); } public void AppendFormatted(dynamic d) { Console.WriteLine(""AppendFormatted""); } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: @" AppendLiteral AppendFormatted"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 128 (0x80) .maxstack 9 .locals init (object V_0, //d CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldloca.s V_1 IL_0009: ldc.i4.7 IL_000a: ldc.i4.1 IL_000b: call ""CustomHandler..ctor(int, int)"" IL_0010: ldloca.s V_1 IL_0012: ldstr ""literal"" IL_0017: call ""void CustomHandler.AppendLiteral(dynamic)"" IL_001c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000002}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> <Program>$.<>o__0.<>p__0"" IL_0021: brtrue.s IL_0062 IL_0023: ldc.i4 0x100 IL_0028: ldstr ""AppendFormatted"" IL_002d: ldnull IL_002e: ldtoken ""<Program>$"" IL_0033: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0038: ldc.i4.2 IL_0039: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_003e: dup IL_003f: ldc.i4.0 IL_0040: ldc.i4.s 9 IL_0042: ldnull IL_0043: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0048: stelem.ref IL_0049: dup IL_004a: ldc.i4.1 IL_004b: ldc.i4.0 IL_004c: ldnull IL_004d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0052: stelem.ref IL_0053: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0058: call ""System.Runtime.CompilerServices.CallSite<<>A{00000002}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> System.Runtime.CompilerServices.CallSite<<>A{00000002}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_005d: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000002}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> <Program>$.<>o__0.<>p__0"" IL_0062: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000002}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> <Program>$.<>o__0.<>p__0"" IL_0067: ldfld ""<>A{00000002}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic> System.Runtime.CompilerServices.CallSite<<>A{00000002}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>>.Target"" IL_006c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000002}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> <Program>$.<>o__0.<>p__0"" IL_0071: ldloca.s V_1 IL_0073: ldloc.0 IL_0074: callvirt ""void <>A{00000002}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, ref CustomHandler, dynamic)"" IL_0079: ldloc.1 IL_007a: call ""void <Program>$.<<Main>$>g__M|0_0(CustomHandler)"" IL_007f: ret } "); } [Fact] public void DynamicConstruction_09() { var code = @" using System; using System.Runtime.CompilerServices; dynamic d = 1; M($""literal{d}""); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } public bool AppendLiteral(dynamic d) { Console.WriteLine(""AppendLiteral""); return true; } public bool AppendFormatted(dynamic d) { Console.WriteLine(""AppendFormatted""); return true; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: @" AppendLiteral AppendFormatted"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 196 (0xc4) .maxstack 11 .locals init (object V_0, //d CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldloca.s V_1 IL_0009: ldc.i4.7 IL_000a: ldc.i4.1 IL_000b: call ""CustomHandler..ctor(int, int)"" IL_0010: ldloca.s V_1 IL_0012: ldstr ""literal"" IL_0017: call ""bool CustomHandler.AppendLiteral(dynamic)"" IL_001c: brfalse IL_00bb IL_0021: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <Program>$.<>o__0.<>p__1"" IL_0026: brtrue.s IL_004c IL_0028: ldc.i4.0 IL_0029: ldtoken ""bool"" IL_002e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0033: ldtoken ""<Program>$"" IL_0038: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0042: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0047: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <Program>$.<>o__0.<>p__1"" IL_004c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <Program>$.<>o__0.<>p__1"" IL_0051: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>>.Target"" IL_0056: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <Program>$.<>o__0.<>p__1"" IL_005b: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000002}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> <Program>$.<>o__0.<>p__0"" IL_0060: brtrue.s IL_009d IL_0062: ldc.i4.0 IL_0063: ldstr ""AppendFormatted"" IL_0068: ldnull IL_0069: ldtoken ""<Program>$"" IL_006e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0073: ldc.i4.2 IL_0074: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0079: dup IL_007a: ldc.i4.0 IL_007b: ldc.i4.s 9 IL_007d: ldnull IL_007e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0083: stelem.ref IL_0084: dup IL_0085: ldc.i4.1 IL_0086: ldc.i4.0 IL_0087: ldnull IL_0088: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_008d: stelem.ref IL_008e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0093: call ""System.Runtime.CompilerServices.CallSite<<>F{00000002}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<<>F{00000002}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0098: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000002}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> <Program>$.<>o__0.<>p__0"" IL_009d: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000002}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> <Program>$.<>o__0.<>p__0"" IL_00a2: ldfld ""<>F{00000002}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<<>F{00000002}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>>.Target"" IL_00a7: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000002}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> <Program>$.<>o__0.<>p__0"" IL_00ac: ldloca.s V_1 IL_00ae: ldloc.0 IL_00af: callvirt ""dynamic <>F{00000002}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, ref CustomHandler, dynamic)"" IL_00b4: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_00b9: br.s IL_00bc IL_00bb: ldc.i4.0 IL_00bc: pop IL_00bd: ldloc.1 IL_00be: call ""void <Program>$.<<Main>$>g__M|0_0(CustomHandler)"" IL_00c3: ret } "); } [Fact] public void RefEscape_01() { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount) : this() {} public void AppendFormatted(Span<char> s) => this.s = s; public static CustomHandler M() { Span<char> s = stackalloc char[10]; return $""{s}""; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (17,19): error CS8352: Cannot use local 's' in this context because it may expose referenced variables outside of their declaration scope // return $"{s}"; Diagnostic(ErrorCode.ERR_EscapeLocal, "s").WithArguments("s").WithLocation(17, 19) ); } [Fact] public void RefEscape_02() { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount) : this() {} public void AppendFormatted(Span<char> s) => this.s = s; public static ref CustomHandler M() { Span<char> s = stackalloc char[10]; return $""{s}""; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (17,9): error CS8150: By-value returns may only be used in methods that return by value // return $"{s}"; Diagnostic(ErrorCode.ERR_MustHaveRefReturn, "return").WithLocation(17, 9) ); } [Fact] public void RefEscape_03() { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount) : this() {} public void AppendFormatted(Span<char> s) => this.s = s; public static ref CustomHandler M() { Span<char> s = stackalloc char[10]; return ref $""{s}""; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (17,20): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // return ref $"{s}"; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, @"$""{s}""").WithLocation(17, 20) ); } [Fact] public void RefEscape_04() { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { S1 s1; public CustomHandler(int literalLength, int formattedCount, ref S1 s1) : this() { this.s1 = s1; } public void AppendFormatted(Span<char> s) => this.s1.s = s; public static void M(ref S1 s1) { Span<char> s = stackalloc char[10]; M2(ref s1, $""{s}""); } public static void M2(ref S1 s1, [InterpolatedStringHandlerArgument(""s1"")] ref CustomHandler handler) {} } public ref struct S1 { public Span<char> s; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (17,9): error CS8350: This combination of arguments to 'CustomHandler.M2(ref S1, ref CustomHandler)' is disallowed because it may expose variables referenced by parameter 'handler' outside of their declaration scope // M2(ref s1, $"{s}"); Diagnostic(ErrorCode.ERR_CallArgMixing, @"M2(ref s1, $""{s}"")").WithArguments("CustomHandler.M2(ref S1, ref CustomHandler)", "handler").WithLocation(17, 9), // (17,23): error CS8352: Cannot use local 's' in this context because it may expose referenced variables outside of their declaration scope // M2(ref s1, $"{s}"); Diagnostic(ErrorCode.ERR_EscapeLocal, "s").WithArguments("s").WithLocation(17, 23) ); } [Fact] public void RefEscape_05() { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount, ref Span<char> s) : this() { this.s = s; } public void AppendFormatted(S1 s1) => s1.s = this.s; public static void M(ref S1 s1) { Span<char> s = stackalloc char[10]; M2(ref s, $""{s1}""); } public static void M2(ref Span<char> s, [InterpolatedStringHandlerArgument(""s"")] CustomHandler handler) {} } public ref struct S1 { public Span<char> s; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics(); } [Fact] public void RefEscape_06() { var code = @" using System; using System.Runtime.CompilerServices; Span<char> s = stackalloc char[5]; Span<char> s2 = stackalloc char[10]; s.TryWrite($""{s2}""); public static class MemoryExtensions { public static bool TryWrite(this Span<char> span, [InterpolatedStringHandlerArgument(""span"")] CustomHandler builder) => true; } [InterpolatedStringHandler] public ref struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, Span<char> s) : this() { } public bool AppendFormatted(Span<char> s) => true; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics(); } [Fact] public void RefEscape_07() { var code = @" using System; using System.Runtime.CompilerServices; Span<char> s = stackalloc char[5]; Span<char> s2 = stackalloc char[10]; s.TryWrite($""{s2}""); public static class MemoryExtensions { public static bool TryWrite(this Span<char> span, [InterpolatedStringHandlerArgument(""span"")] ref CustomHandler builder) => true; } [InterpolatedStringHandler] public ref struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, Span<char> s) : this() { } public bool AppendFormatted(Span<char> s) => true; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics(); } [Fact, WorkItem(54703, "https://github.com/dotnet/roslyn/issues/54703")] public void BracesAreEscaped_01() { var code = @" int i = 1; System.Console.WriteLine($""{{ {i} }}"");"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" { value:1 }"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 56 (0x38) .maxstack 3 .locals init (int V_0, //i System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.1 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""{ "" IL_0012: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: ldloca.s V_1 IL_0019: ldloc.0 IL_001a: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_001f: ldloca.s V_1 IL_0021: ldstr "" }"" IL_0026: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_002b: ldloca.s V_1 IL_002d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0032: call ""void System.Console.WriteLine(string)"" IL_0037: ret } "); } [Fact, WorkItem(54703, "https://github.com/dotnet/roslyn/issues/54703")] public void BracesAreEscaped_02() { var code = @" int i = 1; CustomHandler c = $""{{ {i} }}""; System.Console.WriteLine(c.ToString());"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" literal:{ value:1 alignment:0 format: literal: }"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 71 (0x47) .maxstack 4 .locals init (int V_0, //i CustomHandler V_1, //c CustomHandler V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_2 IL_0004: ldc.i4.4 IL_0005: ldc.i4.1 IL_0006: call ""CustomHandler..ctor(int, int)"" IL_000b: ldloca.s V_2 IL_000d: ldstr ""{ "" IL_0012: call ""void CustomHandler.AppendLiteral(string)"" IL_0017: ldloca.s V_2 IL_0019: ldloc.0 IL_001a: box ""int"" IL_001f: ldc.i4.0 IL_0020: ldnull IL_0021: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0026: ldloca.s V_2 IL_0028: ldstr "" }"" IL_002d: call ""void CustomHandler.AppendLiteral(string)"" IL_0032: ldloc.2 IL_0033: stloc.1 IL_0034: ldloca.s V_1 IL_0036: constrained. ""CustomHandler"" IL_003c: callvirt ""string object.ToString()"" IL_0041: call ""void System.Console.WriteLine(string)"" IL_0046: ret } "); } } }
// Licensed to the .NET Foundation under one or more 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.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Text; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { public class InterpolationTests : CompilingTestBase { [Fact] public void TestSimpleInterp() { string source = @"using System; class Program { public static void Main(string[] args) { var number = 8675309; Console.WriteLine($""Jenny don\'t change your number { number }.""); Console.WriteLine($""Jenny don\'t change your number { number , -12 }.""); Console.WriteLine($""Jenny don\'t change your number { number , 12 }.""); Console.WriteLine($""Jenny don\'t change your number { number :###-####}.""); Console.WriteLine($""Jenny don\'t change your number { number , -12 :###-####}.""); Console.WriteLine($""Jenny don\'t change your number { number , 12 :###-####}.""); Console.WriteLine($""{number}""); } }"; string expectedOutput = @"Jenny don't change your number 8675309. Jenny don't change your number 8675309 . Jenny don't change your number 8675309. Jenny don't change your number 867-5309. Jenny don't change your number 867-5309 . Jenny don't change your number 867-5309. 8675309"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestOnlyInterp() { string source = @"using System; class Program { public static void Main(string[] args) { var number = 8675309; Console.WriteLine($""{number}""); } }"; string expectedOutput = @"8675309"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestDoubleInterp01() { string source = @"using System; class Program { public static void Main(string[] args) { var number = 8675309; Console.WriteLine($""{number}{number}""); } }"; string expectedOutput = @"86753098675309"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestDoubleInterp02() { string source = @"using System; class Program { public static void Main(string[] args) { var number = 8675309; Console.WriteLine($""Jenny don\'t change your number { number :###-####} { number :###-####}.""); } }"; string expectedOutput = @"Jenny don't change your number 867-5309 867-5309."; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TestEmptyInterp() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""Jenny don\'t change your number { /*trash*/ }.""); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,73): error CS1733: Expected expression // Console.WriteLine("Jenny don\'t change your number \{ /*trash*/ }."); Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(5, 73) ); } [Fact] public void TestHalfOpenInterp01() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""Jenny don\'t change your number { ""); } }"; // too many diagnostics perhaps, but it starts the right way. CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,63): error CS1010: Newline in constant // Console.WriteLine($"Jenny don\'t change your number { "); Diagnostic(ErrorCode.ERR_NewlineInConst, "").WithLocation(5, 63), // (5,66): error CS8967: Newlines are not allowed inside a non-verbatim interpolated string // Console.WriteLine($"Jenny don\'t change your number { "); Diagnostic(ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString, "").WithLocation(5, 66), // (6,6): error CS1026: ) expected // } Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(6, 6), // (6,6): error CS1002: ; expected // } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 6), // (7,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2)); } [Fact] public void TestHalfOpenInterp02() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""Jenny don\'t change your number { 8675309 // ""); } }"; // too many diagnostics perhaps, but it starts the right way. CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,71): error CS8077: A single-line comment may not be used in an interpolated string. // Console.WriteLine($"Jenny don\'t change your number { 8675309 // "); Diagnostic(ErrorCode.ERR_SingleLineCommentInExpressionHole, "//").WithLocation(5, 71), // (6,6): error CS1026: ) expected // } Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(6, 6), // (6,6): error CS1002: ; expected // } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 6), // (7,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2)); } [Fact] public void TestHalfOpenInterp03() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""Jenny don\'t change your number { 8675309 /* ""); } }"; // too many diagnostics perhaps, but it starts the right way. CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,71): error CS1035: End-of-file found, '*/' expected // Console.WriteLine($"Jenny don\'t change your number { 8675309 /* "); Diagnostic(ErrorCode.ERR_OpenEndedComment, "").WithLocation(5, 71), // (5,77): error CS8967: Newlines are not allowed inside a non-verbatim interpolated string // Console.WriteLine($"Jenny don\'t change your number { 8675309 /* "); Diagnostic(ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString, "").WithLocation(5, 77), // (7,2): error CS1026: ) expected // } Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(7, 2), // (7,2): error CS1002: ; expected // } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 2), // (7,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2), // (7,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 2)); } [Fact] public void LambdaInInterp() { string source = @"using System; class Program { static void Main(string[] args) { //Console.WriteLine(""jenny {0:(408) ###-####}"", new object[] { ((Func<int>)(() => { return number; })).Invoke() }); Console.WriteLine($""jenny { ((Func<int>)(() => { return number; })).Invoke() :(408) ###-####}""); } static int number = 8675309; } "; string expectedOutput = @"jenny (408) 867-5309"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void OneLiteral() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""Hello"" ); } }"; string expectedOutput = @"Hello"; var verifier = CompileAndVerify(source, expectedOutput: expectedOutput); verifier.VerifyIL("Program.Main", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldstr ""Hello"" IL_0005: call ""void System.Console.WriteLine(string)"" IL_000a: ret } "); } [Fact] public void OneInsert() { string source = @"using System; class Program { static void Main(string[] args) { var hello = $""Hello""; Console.WriteLine( $""{hello}"" ); } }"; string expectedOutput = @"Hello"; var verifier = CompileAndVerify(source, expectedOutput: expectedOutput); verifier.VerifyIL("Program.Main", @" { // Code size 20 (0x14) .maxstack 2 IL_0000: ldstr ""Hello"" IL_0005: dup IL_0006: brtrue.s IL_000e IL_0008: pop IL_0009: ldstr """" IL_000e: call ""void System.Console.WriteLine(string)"" IL_0013: ret } "); } [Fact] public void TwoInserts() { string source = @"using System; class Program { static void Main(string[] args) { var hello = $""Hello""; var world = $""world"" ; Console.WriteLine( $""{hello}, { world }."" ); } }"; string expectedOutput = @"Hello, world."; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void TwoInserts02() { string source = @"using System; class Program { static void Main(string[] args) { var hello = $""Hello""; var world = $""world"" ; Console.WriteLine( $@""{ hello }, { world }."" ); } }"; string expectedOutput = @"Hello, world."; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact, WorkItem(306, "https://github.com/dotnet/roslyn/issues/306"), WorkItem(308, "https://github.com/dotnet/roslyn/issues/308")] public void DynamicInterpolation() { string source = @"using System; using System.Linq.Expressions; class Program { static void Main(string[] args) { dynamic nil = null; dynamic a = new string[] {""Hello"", ""world""}; Console.WriteLine($""<{nil}>""); Console.WriteLine($""<{a}>""); } Expression<Func<string>> M(dynamic d) { return () => $""Dynamic: {d}""; } }"; string expectedOutput = @"<> <System.String[]>"; var verifier = CompileAndVerify(source, new[] { CSharpRef }, expectedOutput: expectedOutput).VerifyDiagnostics(); } [Fact] public void UnclosedInterpolation01() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""{"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,31): error CS1010: Newline in constant // Console.WriteLine( $"{" ); Diagnostic(ErrorCode.ERR_NewlineInConst, "").WithLocation(6, 31), // (6,35): error CS8958: Newlines are not allowed inside a non-verbatim interpolated string // Console.WriteLine( $"{" ); Diagnostic(ErrorCode.ERR_NewlinesAreNotAllowedInsideANonVerbatimInterpolatedString, "").WithLocation(6, 35), // (7,6): error CS1026: ) expected // } Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(7, 6), // (7,6): error CS1002: ; expected // } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 6), // (8,2): error CS1513: } expected // } Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(8, 2)); } [Fact] public void UnclosedInterpolation02() { string source = @"class Program { static void Main(string[] args) { var x = $"";"; // The precise error messages are not important, but this must be an error. CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,19): error CS1010: Newline in constant // var x = $"; Diagnostic(ErrorCode.ERR_NewlineInConst, ";").WithLocation(5, 19), // (5,20): error CS1002: ; expected // var x = $"; Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(5, 20), // (5,20): error CS1513: } expected // var x = $"; Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 20), // (5,20): error CS1513: } expected // var x = $"; Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 20) ); } [Fact] public void EmptyFormatSpecifier() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""{3:}"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,32): error CS8089: Empty format specifier. // Console.WriteLine( $"{3:}" ); Diagnostic(ErrorCode.ERR_EmptyFormatSpecifier, ":").WithLocation(6, 32) ); } [Fact] public void TrailingSpaceInFormatSpecifier() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""{3:d }"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,32): error CS8088: A format specifier may not contain trailing whitespace. // Console.WriteLine( $"{3:d }" ); Diagnostic(ErrorCode.ERR_TrailingWhitespaceInFormatSpecifier, ":d ").WithLocation(6, 32) ); } [Fact] public void TrailingSpaceInFormatSpecifier02() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $@""{3:d }"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,33): error CS8088: A format specifier may not contain trailing whitespace. // Console.WriteLine( $@"{3:d Diagnostic(ErrorCode.ERR_TrailingWhitespaceInFormatSpecifier, @":d ").WithLocation(6, 33) ); } [Fact] public void MissingInterpolationExpression01() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $""{ }"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,32): error CS1733: Expected expression // Console.WriteLine( $"{ }" ); Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(6, 32) ); } [Fact] public void MissingInterpolationExpression02() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( $@""{ }"" ); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (6,33): error CS1733: Expected expression // Console.WriteLine( $@"{ }" ); Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(6, 33) ); } [Fact] public void MissingInterpolationExpression03() { string source = @"using System; class Program { static void Main(string[] args) { Console.WriteLine( "; var normal = "$\""; var verbat = "$@\""; // ensure reparsing of interpolated string token is precise in error scenarios (assertions do not fail) Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal + " ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal + "{").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + normal + "{ ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat + " ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat + "{").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); Assert.True(SyntaxFactory.ParseSyntaxTree(source + verbat + "{ ").GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [Fact] public void MisplacedNewline01() { string source = @"using System; class Program { static void Main(string[] args) { var s = $""{ @"" "" } ""; } }"; // The precise error messages are not important, but this must be an error. Assert.True(SyntaxFactory.ParseSyntaxTree(source).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [Fact] public void MisplacedNewline02() { string source = @"using System; class Program { static void Main(string[] args) { var s = $""{ @"" ""} ""; } }"; // The precise error messages are not important, but this must be an error. Assert.True(SyntaxFactory.ParseSyntaxTree(source).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [Fact] public void PreprocessorInsideInterpolation() { string source = @"class Program { static void Main() { var s = $@""{ #region : #endregion 0 }""; } }"; // The precise error messages are not important, but this must be an error. Assert.True(SyntaxFactory.ParseSyntaxTree(source).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [Fact] public void EscapedCurly() { string source = @"class Program { static void Main() { var s1 = $"" \u007B ""; var s2 = $"" \u007D""; } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,21): error CS8087: A '{' character may only be escaped by doubling '{{' in an interpolated string. // var s1 = $" \u007B "; Diagnostic(ErrorCode.ERR_EscapedCurly, @"\u007B").WithArguments("{").WithLocation(5, 21), // (6,21): error CS8087: A '}' character may only be escaped by doubling '}}' in an interpolated string. // var s2 = $" \u007D"; Diagnostic(ErrorCode.ERR_EscapedCurly, @"\u007D").WithArguments("}").WithLocation(6, 21) ); } [Fact, WorkItem(1119878, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1119878")] public void NoFillIns01() { string source = @"class Program { static void Main() { System.Console.Write($""{{ x }}""); System.Console.WriteLine($@""This is a test""); } }"; string expectedOutput = @"{ x }This is a test"; CompileAndVerify(source, expectedOutput: expectedOutput); } [Fact] public void BadAlignment() { string source = @"class Program { static void Main() { var s = $""{1,1E10}""; var t = $""{1,(int)1E10}""; } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (5,22): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // var s = $"{1,1E10}"; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1E10").WithArguments("double", "int").WithLocation(5, 22), // (5,22): error CS0150: A constant value is expected // var s = $"{1,1E10}"; Diagnostic(ErrorCode.ERR_ConstantExpected, "1E10").WithLocation(5, 22), // (6,22): error CS0221: Constant value '10000000000' cannot be converted to a 'int' (use 'unchecked' syntax to override) // var t = $"{1,(int)1E10}"; Diagnostic(ErrorCode.ERR_ConstOutOfRangeChecked, "(int)1E10").WithArguments("10000000000", "int").WithLocation(6, 22), // (6,22): error CS0150: A constant value is expected // var t = $"{1,(int)1E10}"; Diagnostic(ErrorCode.ERR_ConstantExpected, "(int)1E10").WithLocation(6, 22) ); } [Fact] public void NestedInterpolatedVerbatim() { string source = @"using System; class Program { static void Main(string[] args) { var s = $@""{$@""{1}""}""; Console.WriteLine(s); } }"; string expectedOutput = @"1"; CompileAndVerify(source, expectedOutput: expectedOutput); } // Since the platform type System.FormattableString is not yet in our platforms (at the // time of writing), we explicitly include the required platform types into the sources under test. private const string formattableString = @" /*============================================================ ** ** Class: FormattableString ** ** ** Purpose: implementation of the FormattableString ** class. ** ===========================================================*/ namespace System { /// <summary> /// A composite format string along with the arguments to be formatted. An instance of this /// type may result from the use of the C# or VB language primitive ""interpolated string"". /// </summary> public abstract class FormattableString : IFormattable { /// <summary> /// The composite format string. /// </summary> public abstract string Format { get; } /// <summary> /// Returns an object array that contains zero or more objects to format. Clients should not /// mutate the contents of the array. /// </summary> public abstract object[] GetArguments(); /// <summary> /// The number of arguments to be formatted. /// </summary> public abstract int ArgumentCount { get; } /// <summary> /// Returns one argument to be formatted from argument position <paramref name=""index""/>. /// </summary> public abstract object GetArgument(int index); /// <summary> /// Format to a string using the given culture. /// </summary> public abstract string ToString(IFormatProvider formatProvider); string IFormattable.ToString(string ignored, IFormatProvider formatProvider) { return ToString(formatProvider); } /// <summary> /// Format the given object in the invariant culture. This static method may be /// imported in C# by /// <code> /// using static System.FormattableString; /// </code>. /// Within the scope /// of that import directive an interpolated string may be formatted in the /// invariant culture by writing, for example, /// <code> /// Invariant($""{{ lat = {latitude}; lon = {longitude} }}"") /// </code> /// </summary> public static string Invariant(FormattableString formattable) { if (formattable == null) { throw new ArgumentNullException(""formattable""); } return formattable.ToString(Globalization.CultureInfo.InvariantCulture); } public override string ToString() { return ToString(Globalization.CultureInfo.CurrentCulture); } } } /*============================================================ ** ** Class: FormattableStringFactory ** ** ** Purpose: implementation of the FormattableStringFactory ** class. ** ===========================================================*/ namespace System.Runtime.CompilerServices { /// <summary> /// A factory type used by compilers to create instances of the type <see cref=""FormattableString""/>. /// </summary> public static class FormattableStringFactory { /// <summary> /// Create a <see cref=""FormattableString""/> from a composite format string and object /// array containing zero or more objects to format. /// </summary> public static FormattableString Create(string format, params object[] arguments) { if (format == null) { throw new ArgumentNullException(""format""); } if (arguments == null) { throw new ArgumentNullException(""arguments""); } return new ConcreteFormattableString(format, arguments); } private sealed class ConcreteFormattableString : FormattableString { private readonly string _format; private readonly object[] _arguments; internal ConcreteFormattableString(string format, object[] arguments) { _format = format; _arguments = arguments; } public override string Format { get { return _format; } } public override object[] GetArguments() { return _arguments; } public override int ArgumentCount { get { return _arguments.Length; } } public override object GetArgument(int index) { return _arguments[index]; } public override string ToString(IFormatProvider formatProvider) { return string.Format(formatProvider, Format, _arguments); } } } } "; [Fact] public void TargetType01() { string source = @"using System; class Program { public static void Main(string[] args) { IFormattable f = $""test""; Console.Write(f is System.FormattableString); } }"; CompileAndVerify(source + formattableString, expectedOutput: "True"); } [Fact] public void TargetType02() { string source = @"using System; interface I1 { void M(String s); } interface I2 { void M(FormattableString s); } interface I3 { void M(IFormattable s); } interface I4 : I1, I2 {} interface I5 : I1, I3 {} interface I6 : I2, I3 {} interface I7 : I1, I2, I3 {} class C : I1, I2, I3, I4, I5, I6, I7 { public void M(String s) { Console.Write(1); } public void M(FormattableString s) { Console.Write(2); } public void M(IFormattable s) { Console.Write(3); } } class Program { public static void Main(string[] args) { C c = new C(); ((I1)c).M($""""); ((I2)c).M($""""); ((I3)c).M($""""); ((I4)c).M($""""); ((I5)c).M($""""); ((I6)c).M($""""); ((I7)c).M($""""); ((C)c).M($""""); } }"; CompileAndVerify(source + formattableString, expectedOutput: "12311211"); } [Fact] public void MissingHelper() { string source = @"using System; class Program { public static void Main(string[] args) { IFormattable f = $""test""; } }"; CreateCompilationWithMscorlib40(source).VerifyEmitDiagnostics( // (5,26): error CS0518: Predefined type 'System.Runtime.CompilerServices.FormattableStringFactory' is not defined or imported // IFormattable f = $"test"; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"$""test""").WithArguments("System.Runtime.CompilerServices.FormattableStringFactory").WithLocation(5, 26) ); } [Fact] public void AsyncInterp() { string source = @"using System; using System.Threading.Tasks; class Program { public static void Main(string[] args) { Task<string> hello = Task.FromResult(""Hello""); Task<string> world = Task.FromResult(""world""); M(hello, world).Wait(); } public static async Task M(Task<string> hello, Task<string> world) { Console.WriteLine($""{ await hello }, { await world }!""); } }"; CompileAndVerify( source, references: new[] { MscorlibRef_v4_0_30316_17626, SystemRef_v4_0_30319_17929, SystemCoreRef_v4_0_30319_17929 }, expectedOutput: "Hello, world!", targetFramework: TargetFramework.Empty); } [Fact] public void AlignmentExpression() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""X = { 123 , -(3+4) }.""); } }"; CompileAndVerify(source + formattableString, expectedOutput: "X = 123 ."); } [Fact] public void AlignmentMagnitude() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""X = { 123 , (32768) }.""); Console.WriteLine($""X = { 123 , -(32768) }.""); Console.WriteLine($""X = { 123 , (32767) }.""); Console.WriteLine($""X = { 123 , -(32767) }.""); Console.WriteLine($""X = { 123 , int.MaxValue }.""); Console.WriteLine($""X = { 123 , int.MinValue }.""); } }"; CreateCompilation(source).VerifyDiagnostics( // (5,42): warning CS8094: Alignment value 32768 has a magnitude greater than 32767 and may result in a large formatted string. // Console.WriteLine($"X = { 123 , (32768) }."); Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "32768").WithArguments("32768", "32767").WithLocation(5, 42), // (6,41): warning CS8094: Alignment value -32768 has a magnitude greater than 32767 and may result in a large formatted string. // Console.WriteLine($"X = { 123 , -(32768) }."); Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "-(32768)").WithArguments("-32768", "32767").WithLocation(6, 41), // (9,41): warning CS8094: Alignment value 2147483647 has a magnitude greater than 32767 and may result in a large formatted string. // Console.WriteLine($"X = { 123 , int.MaxValue }."); Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "int.MaxValue").WithArguments("2147483647", "32767").WithLocation(9, 41), // (10,41): warning CS8094: Alignment value -2147483648 has a magnitude greater than 32767 and may result in a large formatted string. // Console.WriteLine($"X = { 123 , int.MinValue }."); Diagnostic(ErrorCode.WRN_AlignmentMagnitude, "int.MinValue").WithArguments("-2147483648", "32767").WithLocation(10, 41) ); } [WorkItem(1097388, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097388")] [Fact] public void InterpolationExpressionMustBeValue01() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""X = { String }.""); Console.WriteLine($""X = { null }.""); } }"; CreateCompilation(source).VerifyDiagnostics( // (5,35): error CS0119: 'string' is a type, which is not valid in the given context // Console.WriteLine($"X = { String }."); Diagnostic(ErrorCode.ERR_BadSKunknown, "String").WithArguments("string", "type").WithLocation(5, 35) ); } [Fact] public void InterpolationExpressionMustBeValue02() { string source = @"using System; class Program { public static void Main(string[] args) { Console.WriteLine($""X = { x=>3 }.""); Console.WriteLine($""X = { Program.Main }.""); Console.WriteLine($""X = { Program.Main(null) }.""); } }"; CreateCompilation(source).VerifyDiagnostics( // (5,35): error CS1660: Cannot convert lambda expression to type 'object' because it is not a delegate type // Console.WriteLine($"X = { x=>3 }."); Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "x=>3").WithArguments("lambda expression", "object").WithLocation(5, 35), // (6,43): error CS0428: Cannot convert method group 'Main' to non-delegate type 'object'. Did you intend to invoke the method? // Console.WriteLine($"X = { Program.Main }."); Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "Main").WithArguments("Main", "object").WithLocation(6, 43), // (7,35): error CS0029: Cannot implicitly convert type 'void' to 'object' // Console.WriteLine($"X = { Program.Main(null) }."); Diagnostic(ErrorCode.ERR_NoImplicitConv, "Program.Main(null)").WithArguments("void", "object").WithLocation(7, 35) ); } [WorkItem(1097428, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097428")] [Fact] public void BadCorelib01() { var text = @"namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } } public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } } public struct Char { } public class String { } internal class Program { public static void Main() { var s = $""X = { 1 } ""; } } }"; CreateEmptyCompilation(text, options: TestOptions.DebugExe) .VerifyEmitDiagnostics(new CodeAnalysis.Emit.EmitOptions(runtimeMetadataVersion: "x.y"), // (15,21): error CS0117: 'string' does not contain a definition for 'Format' // var s = $"X = { 1 } "; Diagnostic(ErrorCode.ERR_NoSuchMember, @"$""X = { 1 } """).WithArguments("string", "Format").WithLocation(15, 21) ); } [WorkItem(1097428, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097428")] [Fact] public void BadCorelib02() { var text = @"namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } } public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } } public struct Char { } public class String { public static Boolean Format(string format, int arg) { return true; } } internal class Program { public static void Main() { var s = $""X = { 1 } ""; } } }"; CreateEmptyCompilation(text, options: TestOptions.DebugExe) .VerifyEmitDiagnostics(new CodeAnalysis.Emit.EmitOptions(runtimeMetadataVersion: "x.y"), // (17,21): error CS0029: Cannot implicitly convert type 'bool' to 'string' // var s = $"X = { 1 } "; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""X = { 1 } """).WithArguments("bool", "string").WithLocation(17, 21) ); } [Fact] public void SillyCoreLib01() { var text = @"namespace System { interface IFormattable { } namespace Runtime.CompilerServices { public static class FormattableStringFactory { public static Bozo Create(string format, int arg) { return new Bozo(); } } } public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { private Boolean m_value; Boolean Use(Boolean b) { m_value = b; return m_value; } } public struct Int32 { private Int32 m_value; Int32 Use(Int32 b) { m_value = b; return m_value; } } public struct Char { } public class String { public static Bozo Format(string format, int arg) { return new Bozo(); } } public class FormattableString { } public class Bozo { public static implicit operator string(Bozo bozo) { return ""zz""; } public static implicit operator FormattableString(Bozo bozo) { return new FormattableString(); } } internal class Program { public static void Main() { var s1 = $""X = { 1 } ""; FormattableString s2 = $""X = { 1 } ""; } } }"; var comp = CreateEmptyCompilation(text, options: Test.Utilities.TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); var compilation = CompileAndVerify(comp, verify: Verification.Fails); compilation.VerifyIL("System.Program.Main", @"{ // Code size 35 (0x23) .maxstack 2 IL_0000: ldstr ""X = {0} "" IL_0005: ldc.i4.1 IL_0006: call ""System.Bozo string.Format(string, int)"" IL_000b: call ""string System.Bozo.op_Implicit(System.Bozo)"" IL_0010: pop IL_0011: ldstr ""X = {0} "" IL_0016: ldc.i4.1 IL_0017: call ""System.Bozo System.Runtime.CompilerServices.FormattableStringFactory.Create(string, int)"" IL_001c: call ""System.FormattableString System.Bozo.op_Implicit(System.Bozo)"" IL_0021: pop IL_0022: ret }"); } [WorkItem(1097386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097386")] [Fact] public void Syntax01() { var text = @"using System; class Program { static void Main(string[] args) { var x = $""{ Math.Abs(value: 1):\}""; var y = x; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,40): error CS8087: A '}' character may only be escaped by doubling '}}' in an interpolated string. // var x = $"{ Math.Abs(value: 1):\}"; Diagnostic(ErrorCode.ERR_EscapedCurly, @"\").WithArguments("}").WithLocation(6, 40), // (6,40): error CS1009: Unrecognized escape sequence // var x = $"{ Math.Abs(value: 1):\}"; Diagnostic(ErrorCode.ERR_IllegalEscape, @"\}").WithLocation(6, 40) ); } [WorkItem(1097941, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097941")] [Fact] public void Syntax02() { var text = @"using S = System; class C { void M() { var x = $""{ (S: } }"; // the precise diagnostics do not matter, as long as it is an error and not a crash. Assert.True(SyntaxFactory.ParseSyntaxTree(text).GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)); } [WorkItem(1097386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097386")] [Fact] public void Syntax03() { var text = @"using System; class Program { static void Main(string[] args) { var x = $""{ Math.Abs(value: 1):}}""; var y = x; } } "; CreateCompilation(text).VerifyDiagnostics( // (6,18): error CS8076: Missing close delimiter '}' for interpolated expression started with '{'. // var x = $"{ Math.Abs(value: 1):}}"; Diagnostic(ErrorCode.ERR_UnclosedExpressionHole, @"""{").WithLocation(6, 18) ); } [WorkItem(1099105, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1099105")] [Fact] public void NoUnexpandedForm() { string source = @"using System; class Program { public static void Main(string[] args) { string[] arr1 = new string[] { ""xyzzy"" }; object[] arr2 = arr1; Console.WriteLine($""-{null}-""); Console.WriteLine($""-{arr1}-""); Console.WriteLine($""-{arr2}-""); } }"; CompileAndVerify(source + formattableString, expectedOutput: @"-- -System.String[]- -System.String[]-"); } [WorkItem(1097386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1097386")] [Fact] public void Dynamic01() { var text = @"class C { const dynamic a = a; string s = $""{0,a}""; }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (3,19): error CS0110: The evaluation of the constant value for 'C.a' involves a circular definition // const dynamic a = a; Diagnostic(ErrorCode.ERR_CircConstValue, "a").WithArguments("C.a").WithLocation(3, 19), // (3,23): error CS0134: 'C.a' is of type 'dynamic'. A const field of a reference type other than string can only be initialized with null. // const dynamic a = a; Diagnostic(ErrorCode.ERR_NotNullConstRefField, "a").WithArguments("C.a", "dynamic").WithLocation(3, 23), // (4,21): error CS0150: A constant value is expected // string s = $"{0,a}"; Diagnostic(ErrorCode.ERR_ConstantExpected, "a").WithLocation(4, 21) ); } [WorkItem(1099238, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1099238")] [Fact] public void Syntax04() { var text = @"using System; using System.Linq.Expressions; class Program { static void Main() { Expression<Func<string>> e = () => $""\u1{0:\u2}""; Console.WriteLine(e); } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (8,46): error CS1009: Unrecognized escape sequence // Expression<Func<string>> e = () => $"\u1{0:\u2}"; Diagnostic(ErrorCode.ERR_IllegalEscape, @"\u1").WithLocation(8, 46), // (8,52): error CS1009: Unrecognized escape sequence // Expression<Func<string>> e = () => $"\u1{0:\u2}"; Diagnostic(ErrorCode.ERR_IllegalEscape, @"\u2").WithLocation(8, 52) ); } [Fact, WorkItem(1098612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1098612")] public void MissingConversionFromFormattableStringToIFormattable() { var text = @"namespace System.Runtime.CompilerServices { public static class FormattableStringFactory { public static FormattableString Create(string format, params object[] arguments) { return null; } } } namespace System { public abstract class FormattableString { } } static class C { static void Main() { System.IFormattable i = $""{""""}""; } }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyEmitDiagnostics( // (23,33): error CS0029: Cannot implicitly convert type 'FormattableString' to 'IFormattable' // System.IFormattable i = $"{""}"; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"$""{""""}""").WithArguments("System.FormattableString", "System.IFormattable").WithLocation(23, 33) ); } [Fact, WorkItem(54702, "https://github.com/dotnet/roslyn/issues/54702")] public void InterpolatedStringHandler_ConcatPreferencesForAllStringElements() { var code = @" using System; Console.WriteLine(TwoComponents()); Console.WriteLine(ThreeComponents()); Console.WriteLine(FourComponents()); Console.WriteLine(FiveComponents()); string TwoComponents() { string s1 = ""1""; string s2 = ""2""; return $""{s1}{s2}""; } string ThreeComponents() { string s1 = ""1""; string s2 = ""2""; string s3 = ""3""; return $""{s1}{s2}{s3}""; } string FourComponents() { string s1 = ""1""; string s2 = ""2""; string s3 = ""3""; string s4 = ""4""; return $""{s1}{s2}{s3}{s4}""; } string FiveComponents() { string s1 = ""1""; string s2 = ""2""; string s3 = ""3""; string s4 = ""4""; string s5 = ""5""; return $""{s1}{s2}{s3}{s4}{s5}""; } "; var handler = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { code, handler }, expectedOutput: @" 12 123 1234 value:1 value:2 value:3 value:4 value:5 "); verifier.VerifyIL("<Program>$.<<Main>$>g__TwoComponents|0_0()", @" { // Code size 18 (0x12) .maxstack 2 .locals init (string V_0) //s2 IL_0000: ldstr ""1"" IL_0005: ldstr ""2"" IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: call ""string string.Concat(string, string)"" IL_0011: ret } "); verifier.VerifyIL("<Program>$.<<Main>$>g__ThreeComponents|0_1()", @" { // Code size 25 (0x19) .maxstack 3 .locals init (string V_0, //s2 string V_1) //s3 IL_0000: ldstr ""1"" IL_0005: ldstr ""2"" IL_000a: stloc.0 IL_000b: ldstr ""3"" IL_0010: stloc.1 IL_0011: ldloc.0 IL_0012: ldloc.1 IL_0013: call ""string string.Concat(string, string, string)"" IL_0018: ret } "); verifier.VerifyIL("<Program>$.<<Main>$>g__FourComponents|0_2()", @" { // Code size 32 (0x20) .maxstack 4 .locals init (string V_0, //s2 string V_1, //s3 string V_2) //s4 IL_0000: ldstr ""1"" IL_0005: ldstr ""2"" IL_000a: stloc.0 IL_000b: ldstr ""3"" IL_0010: stloc.1 IL_0011: ldstr ""4"" IL_0016: stloc.2 IL_0017: ldloc.0 IL_0018: ldloc.1 IL_0019: ldloc.2 IL_001a: call ""string string.Concat(string, string, string, string)"" IL_001f: ret } "); verifier.VerifyIL("<Program>$.<<Main>$>g__FiveComponents|0_3()", @" { // Code size 89 (0x59) .maxstack 3 .locals init (string V_0, //s1 string V_1, //s2 string V_2, //s3 string V_3, //s4 string V_4, //s5 System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_5) IL_0000: ldstr ""1"" IL_0005: stloc.0 IL_0006: ldstr ""2"" IL_000b: stloc.1 IL_000c: ldstr ""3"" IL_0011: stloc.2 IL_0012: ldstr ""4"" IL_0017: stloc.3 IL_0018: ldstr ""5"" IL_001d: stloc.s V_4 IL_001f: ldloca.s V_5 IL_0021: ldc.i4.0 IL_0022: ldc.i4.5 IL_0023: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0028: ldloca.s V_5 IL_002a: ldloc.0 IL_002b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0030: ldloca.s V_5 IL_0032: ldloc.1 IL_0033: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0038: ldloca.s V_5 IL_003a: ldloc.2 IL_003b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0040: ldloca.s V_5 IL_0042: ldloc.3 IL_0043: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0048: ldloca.s V_5 IL_004a: ldloc.s V_4 IL_004c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0051: ldloca.s V_5 IL_0053: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0058: ret } "); } [Theory] [CombinatorialData] public void InterpolatedStringHandler_OverloadsAndBoolReturns(bool useDefaultParameters, bool useBoolReturns, bool constructorBoolArg) { var source = @"int a = 1; System.Console.WriteLine($""base{a}{a,1}{a:X}{a,2:Y}"");"; string interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters, useBoolReturns, constructorBoolArg: constructorBoolArg); string expectedOutput = useDefaultParameters ? @"base value:1,alignment:0:format: value:1,alignment:1:format: value:1,alignment:0:format:X value:1,alignment:2:format:Y" : @"base value:1 value:1,alignment:1 value:1:format:X value:1,alignment:2:format:Y"; string expectedIl = getIl(); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: expectedOutput); verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl); var comp1 = CreateCompilation(interpolatedStringBuilder); foreach (var reference in new[] { comp1.EmitToImageReference(), comp1.ToMetadataReference() }) { var comp2 = CreateCompilation(source, new[] { reference }); verifier = CompileAndVerify(comp2, expectedOutput: expectedOutput); verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl); } string getIl() => (useDefaultParameters, useBoolReturns, constructorBoolArg) switch { (useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: false) => @" { // Code size 80 (0x50) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""base"" IL_0012: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: ldloca.s V_1 IL_0019: ldloc.0 IL_001a: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_001f: ldloca.s V_1 IL_0021: ldloc.0 IL_0022: ldc.i4.1 IL_0023: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)"" IL_0028: ldloca.s V_1 IL_002a: ldloc.0 IL_002b: ldstr ""X"" IL_0030: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)"" IL_0035: ldloca.s V_1 IL_0037: ldloc.0 IL_0038: ldc.i4.2 IL_0039: ldstr ""Y"" IL_003e: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0043: ldloca.s V_1 IL_0045: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_004a: call ""void System.Console.WriteLine(string)"" IL_004f: ret } ", (useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: false) => @" { // Code size 84 (0x54) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""base"" IL_0012: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: ldloca.s V_1 IL_0019: ldloc.0 IL_001a: ldc.i4.0 IL_001b: ldnull IL_001c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0021: ldloca.s V_1 IL_0023: ldloc.0 IL_0024: ldc.i4.1 IL_0025: ldnull IL_0026: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_002b: ldloca.s V_1 IL_002d: ldloc.0 IL_002e: ldc.i4.0 IL_002f: ldstr ""X"" IL_0034: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0039: ldloca.s V_1 IL_003b: ldloc.0 IL_003c: ldc.i4.2 IL_003d: ldstr ""Y"" IL_0042: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0047: ldloca.s V_1 IL_0049: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_004e: call ""void System.Console.WriteLine(string)"" IL_0053: ret } ", (useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: false) => @" { // Code size 92 (0x5c) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""base"" IL_0012: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: brfalse.s IL_004d IL_0019: ldloca.s V_1 IL_001b: ldloc.0 IL_001c: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0021: brfalse.s IL_004d IL_0023: ldloca.s V_1 IL_0025: ldloc.0 IL_0026: ldc.i4.1 IL_0027: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)"" IL_002c: brfalse.s IL_004d IL_002e: ldloca.s V_1 IL_0030: ldloc.0 IL_0031: ldstr ""X"" IL_0036: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)"" IL_003b: brfalse.s IL_004d IL_003d: ldloca.s V_1 IL_003f: ldloc.0 IL_0040: ldc.i4.2 IL_0041: ldstr ""Y"" IL_0046: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_004b: br.s IL_004e IL_004d: ldc.i4.0 IL_004e: pop IL_004f: ldloca.s V_1 IL_0051: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0056: call ""void System.Console.WriteLine(string)"" IL_005b: ret } ", (useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: false) => @" { // Code size 96 (0x60) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""base"" IL_0012: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: brfalse.s IL_0051 IL_0019: ldloca.s V_1 IL_001b: ldloc.0 IL_001c: ldc.i4.0 IL_001d: ldnull IL_001e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0023: brfalse.s IL_0051 IL_0025: ldloca.s V_1 IL_0027: ldloc.0 IL_0028: ldc.i4.1 IL_0029: ldnull IL_002a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_002f: brfalse.s IL_0051 IL_0031: ldloca.s V_1 IL_0033: ldloc.0 IL_0034: ldc.i4.0 IL_0035: ldstr ""X"" IL_003a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_003f: brfalse.s IL_0051 IL_0041: ldloca.s V_1 IL_0043: ldloc.0 IL_0044: ldc.i4.2 IL_0045: ldstr ""Y"" IL_004a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_004f: br.s IL_0052 IL_0051: ldc.i4.0 IL_0052: pop IL_0053: ldloca.s V_1 IL_0055: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005a: call ""void System.Console.WriteLine(string)"" IL_005f: ret } ", (useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: true) => @" { // Code size 89 (0x59) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.4 IL_0004: ldloca.s V_2 IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_000b: stloc.1 IL_000c: ldloc.2 IL_000d: brfalse.s IL_004a IL_000f: ldloca.s V_1 IL_0011: ldstr ""base"" IL_0016: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_001b: ldloca.s V_1 IL_001d: ldloc.0 IL_001e: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0023: ldloca.s V_1 IL_0025: ldloc.0 IL_0026: ldc.i4.1 IL_0027: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)"" IL_002c: ldloca.s V_1 IL_002e: ldloc.0 IL_002f: ldstr ""X"" IL_0034: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)"" IL_0039: ldloca.s V_1 IL_003b: ldloc.0 IL_003c: ldc.i4.2 IL_003d: ldstr ""Y"" IL_0042: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0047: ldc.i4.1 IL_0048: br.s IL_004b IL_004a: ldc.i4.0 IL_004b: pop IL_004c: ldloca.s V_1 IL_004e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0053: call ""void System.Console.WriteLine(string)"" IL_0058: ret } ", (useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: true) => @" { // Code size 93 (0x5d) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.4 IL_0004: ldloca.s V_2 IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_000b: stloc.1 IL_000c: ldloc.2 IL_000d: brfalse.s IL_004e IL_000f: ldloca.s V_1 IL_0011: ldstr ""base"" IL_0016: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_001b: ldloca.s V_1 IL_001d: ldloc.0 IL_001e: ldc.i4.0 IL_001f: ldnull IL_0020: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0025: ldloca.s V_1 IL_0027: ldloc.0 IL_0028: ldc.i4.1 IL_0029: ldnull IL_002a: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_002f: ldloca.s V_1 IL_0031: ldloc.0 IL_0032: ldc.i4.0 IL_0033: ldstr ""X"" IL_0038: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_003d: ldloca.s V_1 IL_003f: ldloc.0 IL_0040: ldc.i4.2 IL_0041: ldstr ""Y"" IL_0046: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_004b: ldc.i4.1 IL_004c: br.s IL_004f IL_004e: ldc.i4.0 IL_004f: pop IL_0050: ldloca.s V_1 IL_0052: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0057: call ""void System.Console.WriteLine(string)"" IL_005c: ret } ", (useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: true) => @" { // Code size 96 (0x60) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.4 IL_0004: ldloca.s V_2 IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_000b: stloc.1 IL_000c: ldloc.2 IL_000d: brfalse.s IL_0051 IL_000f: ldloca.s V_1 IL_0011: ldstr ""base"" IL_0016: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_001b: brfalse.s IL_0051 IL_001d: ldloca.s V_1 IL_001f: ldloc.0 IL_0020: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0025: brfalse.s IL_0051 IL_0027: ldloca.s V_1 IL_0029: ldloc.0 IL_002a: ldc.i4.1 IL_002b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int)"" IL_0030: brfalse.s IL_0051 IL_0032: ldloca.s V_1 IL_0034: ldloc.0 IL_0035: ldstr ""X"" IL_003a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, string)"" IL_003f: brfalse.s IL_0051 IL_0041: ldloca.s V_1 IL_0043: ldloc.0 IL_0044: ldc.i4.2 IL_0045: ldstr ""Y"" IL_004a: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_004f: br.s IL_0052 IL_0051: ldc.i4.0 IL_0052: pop IL_0053: ldloca.s V_1 IL_0055: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005a: call ""void System.Console.WriteLine(string)"" IL_005f: ret } ", (useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: true) => @" { // Code size 100 (0x64) .maxstack 4 .locals init (int V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.4 IL_0004: ldloca.s V_2 IL_0006: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_000b: stloc.1 IL_000c: ldloc.2 IL_000d: brfalse.s IL_0055 IL_000f: ldloca.s V_1 IL_0011: ldstr ""base"" IL_0016: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_001b: brfalse.s IL_0055 IL_001d: ldloca.s V_1 IL_001f: ldloc.0 IL_0020: ldc.i4.0 IL_0021: ldnull IL_0022: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0027: brfalse.s IL_0055 IL_0029: ldloca.s V_1 IL_002b: ldloc.0 IL_002c: ldc.i4.1 IL_002d: ldnull IL_002e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0033: brfalse.s IL_0055 IL_0035: ldloca.s V_1 IL_0037: ldloc.0 IL_0038: ldc.i4.0 IL_0039: ldstr ""X"" IL_003e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0043: brfalse.s IL_0055 IL_0045: ldloca.s V_1 IL_0047: ldloc.0 IL_0048: ldc.i4.2 IL_0049: ldstr ""Y"" IL_004e: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int, int, string)"" IL_0053: br.s IL_0056 IL_0055: ldc.i4.0 IL_0056: pop IL_0057: ldloca.s V_1 IL_0059: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005e: call ""void System.Console.WriteLine(string)"" IL_0063: ret } ", }; } [Fact] public void UseOfSpanInInterpolationHole_CSharp9() { var source = @" using System; ReadOnlySpan<char> span = stackalloc char[1]; Console.WriteLine($""{span}"");"; var comp = CreateCompilation(new[] { source, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false) }, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,22): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater. // Console.WriteLine($"{span}"); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "span").WithArguments("interpolated string handlers", "10.0").WithLocation(4, 22) ); } [ConditionalTheory(typeof(MonoOrCoreClrOnly))] [CombinatorialData] public void UseOfSpanInInterpolationHole(bool useDefaultParameters, bool useBoolReturns, bool constructorBoolArg) { var source = @" using System; ReadOnlySpan<char> a = ""1""; System.Console.WriteLine($""base{a}{a,1}{a:X}{a,2:Y}"");"; string interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters, useBoolReturns, constructorBoolArg: constructorBoolArg); string expectedOutput = useDefaultParameters ? @"base value:1,alignment:0:format: value:1,alignment:1:format: value:1,alignment:0:format:X value:1,alignment:2:format:Y" : @"base value:1 value:1,alignment:1 value:1:format:X value:1,alignment:2:format:Y"; string expectedIl = getIl(); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: expectedOutput, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular10); verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl); var comp1 = CreateCompilation(interpolatedStringBuilder, targetFramework: TargetFramework.NetCoreApp); foreach (var reference in new[] { comp1.EmitToImageReference(), comp1.ToMetadataReference() }) { var comp2 = CreateCompilation(source, new[] { reference }, targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular10); verifier = CompileAndVerify(comp2, expectedOutput: expectedOutput); verifier.VerifyIL("<top-level-statements-entry-point>", expectedIl); } string getIl() => (useDefaultParameters, useBoolReturns, constructorBoolArg) switch { (useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: false) => @" { // Code size 89 (0x59) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldloca.s V_1 IL_000d: ldc.i4.4 IL_000e: ldc.i4.4 IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0014: ldloca.s V_1 IL_0016: ldstr ""base"" IL_001b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0020: ldloca.s V_1 IL_0022: ldloc.0 IL_0023: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_0028: ldloca.s V_1 IL_002a: ldloc.0 IL_002b: ldc.i4.1 IL_002c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)"" IL_0031: ldloca.s V_1 IL_0033: ldloc.0 IL_0034: ldstr ""X"" IL_0039: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)"" IL_003e: ldloca.s V_1 IL_0040: ldloc.0 IL_0041: ldc.i4.2 IL_0042: ldstr ""Y"" IL_0047: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_004c: ldloca.s V_1 IL_004e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0053: call ""void System.Console.WriteLine(string)"" IL_0058: ret } ", (useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: false) => @" { // Code size 93 (0x5d) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldloca.s V_1 IL_000d: ldc.i4.4 IL_000e: ldc.i4.4 IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0014: ldloca.s V_1 IL_0016: ldstr ""base"" IL_001b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0020: ldloca.s V_1 IL_0022: ldloc.0 IL_0023: ldc.i4.0 IL_0024: ldnull IL_0025: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_002a: ldloca.s V_1 IL_002c: ldloc.0 IL_002d: ldc.i4.1 IL_002e: ldnull IL_002f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0034: ldloca.s V_1 IL_0036: ldloc.0 IL_0037: ldc.i4.0 IL_0038: ldstr ""X"" IL_003d: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0042: ldloca.s V_1 IL_0044: ldloc.0 IL_0045: ldc.i4.2 IL_0046: ldstr ""Y"" IL_004b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0050: ldloca.s V_1 IL_0052: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0057: call ""void System.Console.WriteLine(string)"" IL_005c: ret } ", (useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: false) => @" { // Code size 101 (0x65) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldloca.s V_1 IL_000d: ldc.i4.4 IL_000e: ldc.i4.4 IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0014: ldloca.s V_1 IL_0016: ldstr ""base"" IL_001b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0020: brfalse.s IL_0056 IL_0022: ldloca.s V_1 IL_0024: ldloc.0 IL_0025: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_002a: brfalse.s IL_0056 IL_002c: ldloca.s V_1 IL_002e: ldloc.0 IL_002f: ldc.i4.1 IL_0030: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)"" IL_0035: brfalse.s IL_0056 IL_0037: ldloca.s V_1 IL_0039: ldloc.0 IL_003a: ldstr ""X"" IL_003f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)"" IL_0044: brfalse.s IL_0056 IL_0046: ldloca.s V_1 IL_0048: ldloc.0 IL_0049: ldc.i4.2 IL_004a: ldstr ""Y"" IL_004f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0054: br.s IL_0057 IL_0056: ldc.i4.0 IL_0057: pop IL_0058: ldloca.s V_1 IL_005a: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005f: call ""void System.Console.WriteLine(string)"" IL_0064: ret } ", (useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: false) => @" { // Code size 105 (0x69) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldloca.s V_1 IL_000d: ldc.i4.4 IL_000e: ldc.i4.4 IL_000f: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0014: ldloca.s V_1 IL_0016: ldstr ""base"" IL_001b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0020: brfalse.s IL_005a IL_0022: ldloca.s V_1 IL_0024: ldloc.0 IL_0025: ldc.i4.0 IL_0026: ldnull IL_0027: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_002c: brfalse.s IL_005a IL_002e: ldloca.s V_1 IL_0030: ldloc.0 IL_0031: ldc.i4.1 IL_0032: ldnull IL_0033: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0038: brfalse.s IL_005a IL_003a: ldloca.s V_1 IL_003c: ldloc.0 IL_003d: ldc.i4.0 IL_003e: ldstr ""X"" IL_0043: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0048: brfalse.s IL_005a IL_004a: ldloca.s V_1 IL_004c: ldloc.0 IL_004d: ldc.i4.2 IL_004e: ldstr ""Y"" IL_0053: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0058: br.s IL_005b IL_005a: ldc.i4.0 IL_005b: pop IL_005c: ldloca.s V_1 IL_005e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0063: call ""void System.Console.WriteLine(string)"" IL_0068: ret } ", (useDefaultParameters: false, useBoolReturns: false, constructorBoolArg: true) => @" { // Code size 98 (0x62) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldc.i4.4 IL_000c: ldc.i4.4 IL_000d: ldloca.s V_2 IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_0014: stloc.1 IL_0015: ldloc.2 IL_0016: brfalse.s IL_0053 IL_0018: ldloca.s V_1 IL_001a: ldstr ""base"" IL_001f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0024: ldloca.s V_1 IL_0026: ldloc.0 IL_0027: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_002c: ldloca.s V_1 IL_002e: ldloc.0 IL_002f: ldc.i4.1 IL_0030: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)"" IL_0035: ldloca.s V_1 IL_0037: ldloc.0 IL_0038: ldstr ""X"" IL_003d: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)"" IL_0042: ldloca.s V_1 IL_0044: ldloc.0 IL_0045: ldc.i4.2 IL_0046: ldstr ""Y"" IL_004b: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0050: ldc.i4.1 IL_0051: br.s IL_0054 IL_0053: ldc.i4.0 IL_0054: pop IL_0055: ldloca.s V_1 IL_0057: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005c: call ""void System.Console.WriteLine(string)"" IL_0061: ret } ", (useDefaultParameters: false, useBoolReturns: true, constructorBoolArg: true) => @" { // Code size 105 (0x69) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldc.i4.4 IL_000c: ldc.i4.4 IL_000d: ldloca.s V_2 IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_0014: stloc.1 IL_0015: ldloc.2 IL_0016: brfalse.s IL_005a IL_0018: ldloca.s V_1 IL_001a: ldstr ""base"" IL_001f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0024: brfalse.s IL_005a IL_0026: ldloca.s V_1 IL_0028: ldloc.0 IL_0029: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_002e: brfalse.s IL_005a IL_0030: ldloca.s V_1 IL_0032: ldloc.0 IL_0033: ldc.i4.1 IL_0034: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int)"" IL_0039: brfalse.s IL_005a IL_003b: ldloca.s V_1 IL_003d: ldloc.0 IL_003e: ldstr ""X"" IL_0043: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, string)"" IL_0048: brfalse.s IL_005a IL_004a: ldloca.s V_1 IL_004c: ldloc.0 IL_004d: ldc.i4.2 IL_004e: ldstr ""Y"" IL_0053: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0058: br.s IL_005b IL_005a: ldc.i4.0 IL_005b: pop IL_005c: ldloca.s V_1 IL_005e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0063: call ""void System.Console.WriteLine(string)"" IL_0068: ret } ", (useDefaultParameters: true, useBoolReturns: false, constructorBoolArg: true) => @" { // Code size 102 (0x66) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldc.i4.4 IL_000c: ldc.i4.4 IL_000d: ldloca.s V_2 IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_0014: stloc.1 IL_0015: ldloc.2 IL_0016: brfalse.s IL_0057 IL_0018: ldloca.s V_1 IL_001a: ldstr ""base"" IL_001f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0024: ldloca.s V_1 IL_0026: ldloc.0 IL_0027: ldc.i4.0 IL_0028: ldnull IL_0029: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_002e: ldloca.s V_1 IL_0030: ldloc.0 IL_0031: ldc.i4.1 IL_0032: ldnull IL_0033: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0038: ldloca.s V_1 IL_003a: ldloc.0 IL_003b: ldc.i4.0 IL_003c: ldstr ""X"" IL_0041: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0046: ldloca.s V_1 IL_0048: ldloc.0 IL_0049: ldc.i4.2 IL_004a: ldstr ""Y"" IL_004f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0054: ldc.i4.1 IL_0055: br.s IL_0058 IL_0057: ldc.i4.0 IL_0058: pop IL_0059: ldloca.s V_1 IL_005b: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0060: call ""void System.Console.WriteLine(string)"" IL_0065: ret } ", (useDefaultParameters: true, useBoolReturns: true, constructorBoolArg: true) => @" { // Code size 109 (0x6d) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //a System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1, bool V_2) IL_0000: ldstr ""1"" IL_0005: call ""System.ReadOnlySpan<char> string.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldc.i4.4 IL_000c: ldc.i4.4 IL_000d: ldloca.s V_2 IL_000f: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int, out bool)"" IL_0014: stloc.1 IL_0015: ldloc.2 IL_0016: brfalse.s IL_005e IL_0018: ldloca.s V_1 IL_001a: ldstr ""base"" IL_001f: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0024: brfalse.s IL_005e IL_0026: ldloca.s V_1 IL_0028: ldloc.0 IL_0029: ldc.i4.0 IL_002a: ldnull IL_002b: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_0030: brfalse.s IL_005e IL_0032: ldloca.s V_1 IL_0034: ldloc.0 IL_0035: ldc.i4.1 IL_0036: ldnull IL_0037: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_003c: brfalse.s IL_005e IL_003e: ldloca.s V_1 IL_0040: ldloc.0 IL_0041: ldc.i4.0 IL_0042: ldstr ""X"" IL_0047: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_004c: brfalse.s IL_005e IL_004e: ldloca.s V_1 IL_0050: ldloc.0 IL_0051: ldc.i4.2 IL_0052: ldstr ""Y"" IL_0057: call ""bool System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>, int, string)"" IL_005c: br.s IL_005f IL_005e: ldc.i4.0 IL_005f: pop IL_0060: ldloca.s V_1 IL_0062: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0067: call ""void System.Console.WriteLine(string)"" IL_006c: ret } ", }; } [Fact] public void BoolReturns_ShortCircuit() { var source = @" using System; int a = 1; Console.Write($""base{Throw()}{a = 2}""); Console.WriteLine(a); string Throw() => throw new Exception();"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: true, returnExpression: "false"); CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" base 1"); } [Theory] [CombinatorialData] public void BoolOutParameter_ShortCircuits(bool useBoolReturns) { var source = @" using System; int a = 1; Console.WriteLine(a); Console.WriteLine($""{Throw()}{a = 2}""); Console.WriteLine(a); string Throw() => throw new Exception(); "; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: useBoolReturns, constructorBoolArg: true, constructorSuccessResult: false); CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" 1 1"); } [Fact] public void AwaitInHoles_UsesFormat() { var source = @" using System; using System.Threading.Tasks; Console.WriteLine($""base{await Hole()}""); Task<int> Hole() => Task.FromResult(1);"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"base1"); verifier.VerifyIL("<Program>$.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext", @" { // Code size 164 (0xa4) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Exception V_3) IL_0000: ldarg.0 IL_0001: ldfld ""int <Program>$.<<Main>$>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_003e IL_000a: call ""System.Threading.Tasks.Task<int> <Program>$.<<Main>$>g__Hole|0_0()"" IL_000f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0014: stloc.2 IL_0015: ldloca.s V_2 IL_0017: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_001c: brtrue.s IL_005a IL_001e: ldarg.0 IL_001f: ldc.i4.0 IL_0020: dup IL_0021: stloc.0 IL_0022: stfld ""int <Program>$.<<Main>$>d__0.<>1__state"" IL_0027: ldarg.0 IL_0028: ldloc.2 IL_0029: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1"" IL_002e: ldarg.0 IL_002f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder"" IL_0034: ldloca.s V_2 IL_0036: ldarg.0 IL_0037: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, <Program>$.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref <Program>$.<<Main>$>d__0)"" IL_003c: leave.s IL_00a3 IL_003e: ldarg.0 IL_003f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1"" IL_0044: stloc.2 IL_0045: ldarg.0 IL_0046: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1"" IL_004b: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0051: ldarg.0 IL_0052: ldc.i4.m1 IL_0053: dup IL_0054: stloc.0 IL_0055: stfld ""int <Program>$.<<Main>$>d__0.<>1__state"" IL_005a: ldloca.s V_2 IL_005c: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0061: stloc.1 IL_0062: ldstr ""base{0}"" IL_0067: ldloc.1 IL_0068: box ""int"" IL_006d: call ""string string.Format(string, object)"" IL_0072: call ""void System.Console.WriteLine(string)"" IL_0077: leave.s IL_0090 } catch System.Exception { IL_0079: stloc.3 IL_007a: ldarg.0 IL_007b: ldc.i4.s -2 IL_007d: stfld ""int <Program>$.<<Main>$>d__0.<>1__state"" IL_0082: ldarg.0 IL_0083: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder"" IL_0088: ldloc.3 IL_0089: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_008e: leave.s IL_00a3 } IL_0090: ldarg.0 IL_0091: ldc.i4.s -2 IL_0093: stfld ""int <Program>$.<<Main>$>d__0.<>1__state"" IL_0098: ldarg.0 IL_0099: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder"" IL_009e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00a3: ret } "); } [Fact] public void NoAwaitInHoles_UsesBuilder() { var source = @" using System; using System.Threading.Tasks; var hole = await Hole(); Console.WriteLine($""base{hole}""); Task<int> Hole() => Task.FromResult(1);"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" base value:1"); verifier.VerifyIL("<Program>$.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 185 (0xb9) .maxstack 3 .locals init (int V_0, int V_1, //hole System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int <Program>$.<<Main>$>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_003e IL_000a: call ""System.Threading.Tasks.Task<int> <Program>$.<<Main>$>g__Hole|0_0()"" IL_000f: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0014: stloc.2 IL_0015: ldloca.s V_2 IL_0017: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_001c: brtrue.s IL_005a IL_001e: ldarg.0 IL_001f: ldc.i4.0 IL_0020: dup IL_0021: stloc.0 IL_0022: stfld ""int <Program>$.<<Main>$>d__0.<>1__state"" IL_0027: ldarg.0 IL_0028: ldloc.2 IL_0029: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1"" IL_002e: ldarg.0 IL_002f: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder"" IL_0034: ldloca.s V_2 IL_0036: ldarg.0 IL_0037: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, <Program>$.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref <Program>$.<<Main>$>d__0)"" IL_003c: leave.s IL_00b8 IL_003e: ldarg.0 IL_003f: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1"" IL_0044: stloc.2 IL_0045: ldarg.0 IL_0046: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1"" IL_004b: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0051: ldarg.0 IL_0052: ldc.i4.m1 IL_0053: dup IL_0054: stloc.0 IL_0055: stfld ""int <Program>$.<<Main>$>d__0.<>1__state"" IL_005a: ldloca.s V_2 IL_005c: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0061: stloc.1 IL_0062: ldc.i4.4 IL_0063: ldc.i4.1 IL_0064: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0069: stloc.3 IL_006a: ldloca.s V_3 IL_006c: ldstr ""base"" IL_0071: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0076: ldloca.s V_3 IL_0078: ldloc.1 IL_0079: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_007e: ldloca.s V_3 IL_0080: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0085: call ""void System.Console.WriteLine(string)"" IL_008a: leave.s IL_00a5 } catch System.Exception { IL_008c: stloc.s V_4 IL_008e: ldarg.0 IL_008f: ldc.i4.s -2 IL_0091: stfld ""int <Program>$.<<Main>$>d__0.<>1__state"" IL_0096: ldarg.0 IL_0097: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder"" IL_009c: ldloc.s V_4 IL_009e: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_00a3: leave.s IL_00b8 } IL_00a5: ldarg.0 IL_00a6: ldc.i4.s -2 IL_00a8: stfld ""int <Program>$.<<Main>$>d__0.<>1__state"" IL_00ad: ldarg.0 IL_00ae: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder"" IL_00b3: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_00b8: ret } "); } [Fact] public void NoAwaitInHoles_AwaitInExpression_UsesBuilder() { var source = @" using System; using System.Threading.Tasks; var hole = 2; Test(await M(1), $""base{hole}"", await M(3)); void Test(int i1, string s, int i2) => Console.WriteLine(s); Task<int> M(int i) { Console.WriteLine(i); return Task.FromResult(1); }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" 1 3 base value:2"); verifier.VerifyIL("<Program>$.<<Main>$>d__0.System.Runtime.CompilerServices.IAsyncStateMachine.MoveNext()", @" { // Code size 328 (0x148) .maxstack 3 .locals init (int V_0, int V_1, System.Runtime.CompilerServices.TaskAwaiter<int> V_2, System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_3, System.Exception V_4) IL_0000: ldarg.0 IL_0001: ldfld ""int <Program>$.<<Main>$>d__0.<>1__state"" IL_0006: stloc.0 .try { IL_0007: ldloc.0 IL_0008: brfalse.s IL_0050 IL_000a: ldloc.0 IL_000b: ldc.i4.1 IL_000c: beq IL_00dc IL_0011: ldarg.0 IL_0012: ldc.i4.2 IL_0013: stfld ""int <Program>$.<<Main>$>d__0.<hole>5__2"" IL_0018: ldc.i4.1 IL_0019: call ""System.Threading.Tasks.Task<int> <Program>$.<<Main>$>g__M|0_1(int)"" IL_001e: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_0023: stloc.2 IL_0024: ldloca.s V_2 IL_0026: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_002b: brtrue.s IL_006c IL_002d: ldarg.0 IL_002e: ldc.i4.0 IL_002f: dup IL_0030: stloc.0 IL_0031: stfld ""int <Program>$.<<Main>$>d__0.<>1__state"" IL_0036: ldarg.0 IL_0037: ldloc.2 IL_0038: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1"" IL_003d: ldarg.0 IL_003e: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder"" IL_0043: ldloca.s V_2 IL_0045: ldarg.0 IL_0046: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, <Program>$.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref <Program>$.<<Main>$>d__0)"" IL_004b: leave IL_0147 IL_0050: ldarg.0 IL_0051: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1"" IL_0056: stloc.2 IL_0057: ldarg.0 IL_0058: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1"" IL_005d: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_0063: ldarg.0 IL_0064: ldc.i4.m1 IL_0065: dup IL_0066: stloc.0 IL_0067: stfld ""int <Program>$.<<Main>$>d__0.<>1__state"" IL_006c: ldarg.0 IL_006d: ldloca.s V_2 IL_006f: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_0074: stfld ""int <Program>$.<<Main>$>d__0.<>7__wrap2"" IL_0079: ldarg.0 IL_007a: ldc.i4.4 IL_007b: ldc.i4.1 IL_007c: newobj ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0081: stloc.3 IL_0082: ldloca.s V_3 IL_0084: ldstr ""base"" IL_0089: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_008e: ldloca.s V_3 IL_0090: ldarg.0 IL_0091: ldfld ""int <Program>$.<<Main>$>d__0.<hole>5__2"" IL_0096: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_009b: ldloca.s V_3 IL_009d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_00a2: stfld ""string <Program>$.<<Main>$>d__0.<>7__wrap3"" IL_00a7: ldc.i4.3 IL_00a8: call ""System.Threading.Tasks.Task<int> <Program>$.<<Main>$>g__M|0_1(int)"" IL_00ad: callvirt ""System.Runtime.CompilerServices.TaskAwaiter<int> System.Threading.Tasks.Task<int>.GetAwaiter()"" IL_00b2: stloc.2 IL_00b3: ldloca.s V_2 IL_00b5: call ""bool System.Runtime.CompilerServices.TaskAwaiter<int>.IsCompleted.get"" IL_00ba: brtrue.s IL_00f8 IL_00bc: ldarg.0 IL_00bd: ldc.i4.1 IL_00be: dup IL_00bf: stloc.0 IL_00c0: stfld ""int <Program>$.<<Main>$>d__0.<>1__state"" IL_00c5: ldarg.0 IL_00c6: ldloc.2 IL_00c7: stfld ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1"" IL_00cc: ldarg.0 IL_00cd: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder"" IL_00d2: ldloca.s V_2 IL_00d4: ldarg.0 IL_00d5: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.AwaitUnsafeOnCompleted<System.Runtime.CompilerServices.TaskAwaiter<int>, <Program>$.<<Main>$>d__0>(ref System.Runtime.CompilerServices.TaskAwaiter<int>, ref <Program>$.<<Main>$>d__0)"" IL_00da: leave.s IL_0147 IL_00dc: ldarg.0 IL_00dd: ldfld ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1"" IL_00e2: stloc.2 IL_00e3: ldarg.0 IL_00e4: ldflda ""System.Runtime.CompilerServices.TaskAwaiter<int> <Program>$.<<Main>$>d__0.<>u__1"" IL_00e9: initobj ""System.Runtime.CompilerServices.TaskAwaiter<int>"" IL_00ef: ldarg.0 IL_00f0: ldc.i4.m1 IL_00f1: dup IL_00f2: stloc.0 IL_00f3: stfld ""int <Program>$.<<Main>$>d__0.<>1__state"" IL_00f8: ldloca.s V_2 IL_00fa: call ""int System.Runtime.CompilerServices.TaskAwaiter<int>.GetResult()"" IL_00ff: stloc.1 IL_0100: ldarg.0 IL_0101: ldfld ""int <Program>$.<<Main>$>d__0.<>7__wrap2"" IL_0106: ldarg.0 IL_0107: ldfld ""string <Program>$.<<Main>$>d__0.<>7__wrap3"" IL_010c: ldloc.1 IL_010d: call ""void <Program>$.<<Main>$>g__Test|0_0(int, string, int)"" IL_0112: ldarg.0 IL_0113: ldnull IL_0114: stfld ""string <Program>$.<<Main>$>d__0.<>7__wrap3"" IL_0119: leave.s IL_0134 } catch System.Exception { IL_011b: stloc.s V_4 IL_011d: ldarg.0 IL_011e: ldc.i4.s -2 IL_0120: stfld ""int <Program>$.<<Main>$>d__0.<>1__state"" IL_0125: ldarg.0 IL_0126: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder"" IL_012b: ldloc.s V_4 IL_012d: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetException(System.Exception)"" IL_0132: leave.s IL_0147 } IL_0134: ldarg.0 IL_0135: ldc.i4.s -2 IL_0137: stfld ""int <Program>$.<<Main>$>d__0.<>1__state"" IL_013c: ldarg.0 IL_013d: ldflda ""System.Runtime.CompilerServices.AsyncTaskMethodBuilder <Program>$.<<Main>$>d__0.<>t__builder"" IL_0142: call ""void System.Runtime.CompilerServices.AsyncTaskMethodBuilder.SetResult()"" IL_0147: ret } "); } [Fact] public void MissingCreate_01() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public override string ToString() => throw null; public void Dispose() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 2 arguments // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 3 arguments // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "3").WithLocation(1, 5) ); } [Fact] public void MissingCreate_02() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(int literalLength) => throw null; public override string ToString() => throw null; public void Dispose() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 2 arguments // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'DefaultInterpolatedStringHandler' does not contain a constructor that takes 3 arguments // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "3").WithLocation(1, 5) ); } [Fact] public void MissingCreate_03() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(ref int literalLength, int formattedCount) => throw null; public override string ToString() => throw null; public void Dispose() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,5): error CS1620: Argument 1 must be passed with the 'ref' keyword // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BadArgRef, @"$""{(object)1}""").WithArguments("1", "ref").WithLocation(1, 5) ); } [Theory] [InlineData(null)] [InlineData("public string ToStringAndClear(int literalLength) => throw null;")] [InlineData("public void ToStringAndClear() => throw null;")] [InlineData("public static string ToStringAndClear() => throw null;")] public void MissingWellKnownMethod_ToStringAndClear(string toStringAndClearMethod) { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null; " + toStringAndClearMethod + @" public override string ToString() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics(); comp.VerifyEmitDiagnostics( // (1,5): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear' // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler", "ToStringAndClear").WithLocation(1, 5) ); } [Fact] public void ObsoleteCreateMethod() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { [System.Obsolete(""Constructor is obsolete"", error: true)] public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null; public void Dispose() => throw null; public override string ToString() => throw null; public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,5): error CS0619: 'DefaultInterpolatedStringHandler.DefaultInterpolatedStringHandler(int, int)' is obsolete: 'Constructor is obsolete' // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.DefaultInterpolatedStringHandler(int, int)", "Constructor is obsolete").WithLocation(1, 5) ); } [Fact] public void ObsoleteAppendLiteralMethod() { var code = @"_ = $""base{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null; public void Dispose() => throw null; public override string ToString() => throw null; [System.Obsolete(""AppendLiteral is obsolete"", error: true)] public void AppendLiteral(string value) => throw null; public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,7): error CS0619: 'DefaultInterpolatedStringHandler.AppendLiteral(string)' is obsolete: 'AppendLiteral is obsolete' // _ = $"base{(object)1}"; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "base").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)", "AppendLiteral is obsolete").WithLocation(1, 7) ); } [Fact] public void ObsoleteAppendFormattedMethod() { var code = @"_ = $""base{(object)1}"";"; var interpolatedStringBuilder = @" namespace System.Runtime.CompilerServices { public ref struct DefaultInterpolatedStringHandler { public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) => throw null; public void Dispose() => throw null; public override string ToString() => throw null; public void AppendLiteral(string value) => throw null; [System.Obsolete(""AppendFormatted is obsolete"", error: true)] public void AppendFormatted<T>(T hole, int alignment = 0, string format = null) => throw null; } } "; var comp = CreateCompilation(new[] { code, interpolatedStringBuilder }); comp.VerifyDiagnostics( // (1,11): error CS0619: 'DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)' is obsolete: 'AppendFormatted is obsolete' // _ = $"base{(object)1}"; Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "{(object)1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)", "AppendFormatted is obsolete").WithLocation(1, 11) ); } private const string UnmanagedCallersOnlyIl = @" .class public auto ansi sealed beforefieldinit System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute extends [mscorlib]System.Attribute { .custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = ( 01 00 40 00 00 00 01 00 54 02 09 49 6e 68 65 72 69 74 65 64 00 ) .field public class [mscorlib]System.Type[] CallConvs .field public string EntryPoint .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { ldarg.0 call instance void [mscorlib]System.Attribute::.ctor() ret } }"; [Fact] public void UnmanagedCallersOnlyAppendFormattedMethod() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" .class public sequential ansi sealed beforefieldinit System.Runtime.CompilerServices.DefaultInterpolatedStringHandler extends [mscorlib]System.ValueType { .custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void [mscorlib]System.ObsoleteAttribute::.ctor(string, bool) = ( 01 00 52 54 79 70 65 73 20 77 69 74 68 20 65 6d 62 65 64 64 65 64 20 72 65 66 65 72 65 6e 63 65 73 20 61 72 65 20 6e 6f 74 20 73 75 70 70 6f 72 74 65 64 20 69 6e 20 74 68 69 73 20 76 65 72 73 69 6f 6e 20 6f 66 20 79 6f 75 72 20 63 6f 6d 70 69 6c 65 72 2e 01 00 00 ) .pack 0 .size 1 .method public hidebysig specialname rtspecialname instance void .ctor ( int32 literalLength, int32 formattedCount ) cil managed { ldnull throw } .method public hidebysig instance void Dispose () cil managed { ldnull throw } .method public hidebysig virtual instance string ToString () cil managed { ldnull throw } .method public hidebysig instance void AppendLiteral ( string 'value' ) cil managed { ldnull throw } .method public hidebysig instance void AppendFormatted<T> ( !!T hole, [opt] int32 'alignment', [opt] string format ) cil managed { .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) .param [2] = int32(0) .param [3] = nullref ldnull throw } } "; var comp = CreateCompilationWithIL(code, ilSource: interpolatedStringBuilder + UnmanagedCallersOnlyIl); comp.VerifyDiagnostics( // (1,7): error CS0570: 'DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)' is not supported by the language // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BindToBogus, "{(object)1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<T>(T, int, string)").WithLocation(1, 7) ); } [Fact] public void UnmanagedCallersOnlyToStringMethod() { var code = @"_ = $""{(object)1}"";"; var interpolatedStringBuilder = @" .class public sequential ansi sealed beforefieldinit System.Runtime.CompilerServices.DefaultInterpolatedStringHandler extends [mscorlib]System.ValueType { .custom instance void [mscorlib]System.Runtime.CompilerServices.IsByRefLikeAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void [mscorlib]System.ObsoleteAttribute::.ctor(string, bool) = ( 01 00 52 54 79 70 65 73 20 77 69 74 68 20 65 6d 62 65 64 64 65 64 20 72 65 66 65 72 65 6e 63 65 73 20 61 72 65 20 6e 6f 74 20 73 75 70 70 6f 72 74 65 64 20 69 6e 20 74 68 69 73 20 76 65 72 73 69 6f 6e 20 6f 66 20 79 6f 75 72 20 63 6f 6d 70 69 6c 65 72 2e 01 00 00 ) .pack 0 .size 1 .method public hidebysig specialname rtspecialname instance void .ctor ( int32 literalLength, int32 formattedCount ) cil managed { ldnull throw } .method public hidebysig instance string ToStringAndClear () cil managed { .custom instance void System.Runtime.InteropServices.UnmanagedCallersOnlyAttribute::.ctor() = ( 01 00 00 00 ) ldnull throw } .method public hidebysig instance void AppendLiteral ( string 'value' ) cil managed { ldnull throw } .method public hidebysig instance void AppendFormatted<T> ( !!T hole, [opt] int32 'alignment', [opt] string format ) cil managed { .param [2] = int32(0) .param [3] = nullref ldnull throw } } "; var comp = CreateCompilationWithIL(code, ilSource: interpolatedStringBuilder + UnmanagedCallersOnlyIl); comp.VerifyDiagnostics(); comp.VerifyEmitDiagnostics( // (1,5): error CS0570: 'DefaultInterpolatedStringHandler.ToStringAndClear()' is not supported by the language // _ = $"{(object)1}"; Diagnostic(ErrorCode.ERR_BindToBogus, @"$""{(object)1}""").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()").WithLocation(1, 5) ); } [Fact] public void UnsupportedArgumentType() { var source = @" unsafe { int* i = null; var s = new S(); _ = $""{i}{s}""; } ref struct S { }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: true, useBoolReturns: false); var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, options: TestOptions.UnsafeReleaseExe, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (6,11): error CS0306: The type 'int*' may not be used as a type argument // _ = $"{i}{s}"; Diagnostic(ErrorCode.ERR_BadTypeArgument, "{i}").WithArguments("int*").WithLocation(6, 11), // (6,14): error CS0306: The type 'S' may not be used as a type argument // _ = $"{i}{s}"; Diagnostic(ErrorCode.ERR_BadTypeArgument, "{s}").WithArguments("S").WithLocation(6, 14) ); } [Fact] public void TargetTypedInterpolationHoles() { var source = @" bool b = true; System.Console.WriteLine($""{b switch { true => 1, false => null }}{(!b ? null : 2)}{default}{null}"");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" value:1 value:2 value: value:"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 81 (0x51) .maxstack 3 .locals init (bool V_0, //b object V_1, System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_2 IL_0004: ldc.i4.0 IL_0005: ldc.i4.4 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloc.0 IL_000c: brfalse.s IL_0017 IL_000e: ldc.i4.1 IL_000f: box ""int"" IL_0014: stloc.1 IL_0015: br.s IL_0019 IL_0017: ldnull IL_0018: stloc.1 IL_0019: ldloca.s V_2 IL_001b: ldloc.1 IL_001c: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)"" IL_0021: ldloca.s V_2 IL_0023: ldloc.0 IL_0024: brfalse.s IL_002e IL_0026: ldc.i4.2 IL_0027: box ""int"" IL_002c: br.s IL_002f IL_002e: ldnull IL_002f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)"" IL_0034: ldloca.s V_2 IL_0036: ldnull IL_0037: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_003c: ldloca.s V_2 IL_003e: ldnull IL_003f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(string)"" IL_0044: ldloca.s V_2 IL_0046: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_004b: call ""void System.Console.WriteLine(string)"" IL_0050: ret } "); } [Fact] public void TargetTypedInterpolationHoles_Errors() { var source = @"System.Console.WriteLine($""{(null, default)}{new()}"");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,29): error CS1503: Argument 1: cannot convert from '(<null>, default)' to 'object' // System.Console.WriteLine($"{(null, default)}{new()}"); Diagnostic(ErrorCode.ERR_BadArgType, "(null, default)").WithArguments("1", "(<null>, default)", "object").WithLocation(1, 29), // (1,29): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater. // System.Console.WriteLine($"{(null, default)}{new()}"); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "(null, default)").WithArguments("interpolated string handlers", "10.0").WithLocation(1, 29), // (1,46): error CS1729: 'string' does not contain a constructor that takes 0 arguments // System.Console.WriteLine($"{(null, default)}{new()}"); Diagnostic(ErrorCode.ERR_BadCtorArgCount, "new()").WithArguments("string", "0").WithLocation(1, 46) ); } [Fact] public void RefTernary() { var source = @" bool b = true; int i = 1; System.Console.WriteLine($""{(!b ? ref i : ref i)}"");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"value:1"); } [Fact] public void NestedInterpolatedStrings() { var source = @" int i = 1; System.Console.WriteLine($""{$""{i}""}"");"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @"value:1"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 32 (0x20) .maxstack 3 .locals init (int V_0, //i System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.0 IL_0005: ldc.i4.1 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldloc.0 IL_000e: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_0013: ldloca.s V_1 IL_0015: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_001a: call ""void System.Console.WriteLine(string)"" IL_001f: ret } "); } [Fact] public void ExceptionFilter_01() { var source = @" using System; int i = 1; try { Console.WriteLine(""Starting try""); throw new MyException { Prop = i }; } // Test DefaultInterpolatedStringHandler renders specially, so we're actually comparing to ""value:Prop"" plus some whitespace catch (MyException e) when (e.ToString() == $""{i}"".Trim()) { Console.WriteLine(""Caught""); } class MyException : Exception { public int Prop { get; set; } public override string ToString() => ""value:"" + Prop.ToString(); }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, expectedOutput: @" Starting try Caught"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 95 (0x5f) .maxstack 4 .locals init (int V_0, //i System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 .try { IL_0002: ldstr ""Starting try"" IL_0007: call ""void System.Console.WriteLine(string)"" IL_000c: newobj ""MyException..ctor()"" IL_0011: dup IL_0012: ldloc.0 IL_0013: callvirt ""void MyException.Prop.set"" IL_0018: throw } filter { IL_0019: isinst ""MyException"" IL_001e: dup IL_001f: brtrue.s IL_0025 IL_0021: pop IL_0022: ldc.i4.0 IL_0023: br.s IL_004f IL_0025: callvirt ""string object.ToString()"" IL_002a: ldloca.s V_1 IL_002c: ldc.i4.0 IL_002d: ldc.i4.1 IL_002e: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0033: ldloca.s V_1 IL_0035: ldloc.0 IL_0036: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_003b: ldloca.s V_1 IL_003d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0042: callvirt ""string string.Trim()"" IL_0047: call ""bool string.op_Equality(string, string)"" IL_004c: ldc.i4.0 IL_004d: cgt.un IL_004f: endfilter } // end filter { // handler IL_0051: pop IL_0052: ldstr ""Caught"" IL_0057: call ""void System.Console.WriteLine(string)"" IL_005c: leave.s IL_005e } IL_005e: ret } "); } [ConditionalFact(typeof(MonoOrCoreClrOnly), typeof(NoIOperationValidation))] public void ExceptionFilter_02() { var source = @" using System; ReadOnlySpan<char> s = new char[] { 'i' }; try { Console.WriteLine(""Starting try""); throw new MyException { Prop = s.ToString() }; } // Test DefaultInterpolatedStringHandler renders specially, so we're actually comparing to ""value:Prop"" plus some whitespace catch (MyException e) when (e.ToString() == $""{s}"".Trim()) { Console.WriteLine(""Caught""); } class MyException : Exception { public string Prop { get; set; } public override string ToString() => ""value:"" + Prop.ToString(); }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false); var verifier = CompileAndVerify(new[] { source, interpolatedStringBuilder }, targetFramework: TargetFramework.NetCoreApp, expectedOutput: @" Starting try Caught"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 122 (0x7a) .maxstack 4 .locals init (System.ReadOnlySpan<char> V_0, //s System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: newarr ""char"" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldc.i4.s 105 IL_000a: stelem.i2 IL_000b: call ""System.ReadOnlySpan<char> System.ReadOnlySpan<char>.op_Implicit(char[])"" IL_0010: stloc.0 .try { IL_0011: ldstr ""Starting try"" IL_0016: call ""void System.Console.WriteLine(string)"" IL_001b: newobj ""MyException..ctor()"" IL_0020: dup IL_0021: ldloca.s V_0 IL_0023: constrained. ""System.ReadOnlySpan<char>"" IL_0029: callvirt ""string object.ToString()"" IL_002e: callvirt ""void MyException.Prop.set"" IL_0033: throw } filter { IL_0034: isinst ""MyException"" IL_0039: dup IL_003a: brtrue.s IL_0040 IL_003c: pop IL_003d: ldc.i4.0 IL_003e: br.s IL_006a IL_0040: callvirt ""string object.ToString()"" IL_0045: ldloca.s V_1 IL_0047: ldc.i4.0 IL_0048: ldc.i4.1 IL_0049: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_004e: ldloca.s V_1 IL_0050: ldloc.0 IL_0051: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_0056: ldloca.s V_1 IL_0058: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_005d: callvirt ""string string.Trim()"" IL_0062: call ""bool string.op_Equality(string, string)"" IL_0067: ldc.i4.0 IL_0068: cgt.un IL_006a: endfilter } // end filter { // handler IL_006c: pop IL_006d: ldstr ""Caught"" IL_0072: call ""void System.Console.WriteLine(string)"" IL_0077: leave.s IL_0079 } IL_0079: ret } "); } [ConditionalFact(typeof(MonoOrCoreClrOnly), typeof(NoIOperationValidation))] public void ImplicitUserDefinedConversionInHole() { var source = @" using System; S s = default; C c = new C(); Console.WriteLine($""{s}{c}""); ref struct S { public static implicit operator ReadOnlySpan<char>(S s) => ""S converted""; } class C { public static implicit operator ReadOnlySpan<char>(C s) => ""C converted""; }"; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false); var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:S converted value:C"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 57 (0x39) .maxstack 3 .locals init (S V_0, //s C V_1, //c System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_2) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: newobj ""C..ctor()"" IL_000d: stloc.1 IL_000e: ldloca.s V_2 IL_0010: ldc.i4.0 IL_0011: ldc.i4.2 IL_0012: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0017: ldloca.s V_2 IL_0019: ldloc.0 IL_001a: call ""System.ReadOnlySpan<char> S.op_Implicit(S)"" IL_001f: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(System.ReadOnlySpan<char>)"" IL_0024: ldloca.s V_2 IL_0026: ldloc.1 IL_0027: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<C>(C)"" IL_002c: ldloca.s V_2 IL_002e: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0033: call ""void System.Console.WriteLine(string)"" IL_0038: ret } "); } [Fact] public void ExplicitUserDefinedConversionInHole() { var source = @" using System; S s = default; Console.WriteLine($""{s}""); ref struct S { public static explicit operator ReadOnlySpan<char>(S s) => ""S converted""; } "; var interpolatedStringBuilder = GetInterpolatedStringHandlerDefinition(includeSpanOverloads: true, useDefaultParameters: false, useBoolReturns: false); var comp = CreateCompilation(new[] { source, interpolatedStringBuilder }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (5,21): error CS0306: The type 'S' may not be used as a type argument // Console.WriteLine($"{s}"); Diagnostic(ErrorCode.ERR_BadTypeArgument, "{s}").WithArguments("S").WithLocation(5, 21) ); } [Fact] public void ImplicitUserDefinedConversionInLiteral() { var source = @" using System; Console.WriteLine($""Text{1}""); public struct CustomStruct { public static implicit operator CustomStruct(string s) => new CustomStruct { S = s }; public string S { get; set; } public override string ToString() => ""literal:"" + S; } namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public void AppendLiteral(CustomStruct s) => _builder.AppendLine(s.ToString()); public void AppendFormatted(object o) => _builder.AppendLine(""value:"" + o.ToString()); } }"; var verifier = CompileAndVerify(source, expectedOutput: @" literal:Text value:1"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 52 (0x34) .maxstack 3 .locals init (System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.4 IL_0003: ldc.i4.1 IL_0004: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldstr ""Text"" IL_0010: call ""CustomStruct CustomStruct.op_Implicit(string)"" IL_0015: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(CustomStruct)"" IL_001a: ldloca.s V_0 IL_001c: ldc.i4.1 IL_001d: box ""int"" IL_0022: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)"" IL_0027: ldloca.s V_0 IL_0029: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_002e: call ""void System.Console.WriteLine(string)"" IL_0033: ret } "); } [Fact] public void ExplicitUserDefinedConversionInLiteral() { var source = @" using System; Console.WriteLine($""Text{1}""); public struct CustomStruct { public static explicit operator CustomStruct(string s) => new CustomStruct { S = s }; public string S { get; set; } public override string ToString() => ""literal:"" + S; } namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public void AppendLiteral(CustomStruct s) => _builder.AppendLine(s.ToString()); public void AppendFormatted(object o) => _builder.AppendLine(""value:"" + o.ToString()); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,21): error CS1503: Argument 1: cannot convert from 'string' to 'CustomStruct' // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_BadArgType, "Text").WithArguments("1", "string", "CustomStruct").WithLocation(4, 21) ); } [Fact] public void InvalidBuilderReturnType() { var source = @" using System; Console.WriteLine($""Text{1}""); namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public int AppendLiteral(string s) => 0; public int AppendFormatted(object o) => 0; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,21): error CS8941: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendLiteral(string)' is malformed. It does not return 'void' or 'bool'. // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "Text").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)").WithLocation(4, 21), // (4,25): error CS8941: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendFormatted(object)' is malformed. It does not return 'void' or 'bool'. // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnMalformed, "{1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)").WithLocation(4, 25) ); } [Fact] public void MixedBuilderReturnTypes_01() { var source = @" using System; Console.WriteLine($""Text{1}""); Console.WriteLine($""{1}Text""); namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public bool AppendLiteral(string s) => true; public void AppendFormatted(object o) { } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,25): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendFormatted(object)' has inconsistent return type. Expected to return 'bool'. // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "{1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)", "bool").WithLocation(4, 25), // (5,24): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendLiteral(string)' has inconsistent return type. Expected to return 'void'. // Console.WriteLine($"{1}Text"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "Text").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)", "void").WithLocation(5, 24) ); } [Fact] public void MixedBuilderReturnTypes_02() { var source = @" using System; Console.WriteLine($""Text{1}""); Console.WriteLine($""{1}Text""); namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public void AppendLiteral(string s) { } public bool AppendFormatted(object o) => true; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,25): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendFormatted(object)' has inconsistent return type. Expected to return 'void'. // Console.WriteLine($"Text{1}"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "{1}").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(object)", "void").WithLocation(4, 25), // (5,24): error CS8942: Interpolated string handler method 'DefaultInterpolatedStringHandler.AppendLiteral(string)' has inconsistent return type. Expected to return 'bool'. // Console.WriteLine($"{1}Text"); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerMethodReturnInconsistent, "Text").WithArguments("System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)", "bool").WithLocation(5, 24) ); } [Fact] public void MixedBuilderReturnTypes_03() { var source = @" using System; Console.WriteLine($""{1}""); namespace System.Runtime.CompilerServices { using System.Text; public ref struct DefaultInterpolatedStringHandler { private readonly StringBuilder _builder; public DefaultInterpolatedStringHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public string ToStringAndClear() => _builder.ToString(); public bool AppendLiteral(string s) => true; public void AppendFormatted(object o) { _builder.AppendLine(""value:"" + o.ToString()); } } }"; CompileAndVerify(source, expectedOutput: "value:1"); } [Fact] public void MixedBuilderReturnTypes_04() { var source = @" using System; using System.Text; using System.Runtime.CompilerServices; Console.WriteLine((CustomHandler)$""l""); [InterpolatedStringHandler] public class CustomHandler { private readonly StringBuilder _builder; public CustomHandler(int literalLength, int formattedCount) { _builder = new StringBuilder(); } public override string ToString() => _builder.ToString(); public bool AppendFormatted(object o) => true; public void AppendLiteral(string s) { _builder.AppendLine(""literal:"" + s.ToString()); } } "; CompileAndVerify(new[] { source, InterpolatedStringHandlerAttribute }, expectedOutput: "literal:l"); } private static void VerifyInterpolatedStringExpression(CSharpCompilation comp, string handlerType = "CustomHandler") { var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var interpolatedString = tree.GetRoot().DescendantNodes().OfType<InterpolatedStringExpressionSyntax>().Single(); var semanticInfo = model.GetSemanticInfoSummary(interpolatedString); Assert.Equal(SpecialType.System_String, semanticInfo.Type.SpecialType); Assert.Equal(handlerType, semanticInfo.ConvertedType.ToTestDisplayString()); Assert.Equal(ConversionKind.InterpolatedStringHandler, semanticInfo.ImplicitConversion.Kind); Assert.True(semanticInfo.ImplicitConversion.Exists); Assert.True(semanticInfo.ImplicitConversion.IsValid); Assert.True(semanticInfo.ImplicitConversion.IsInterpolatedStringHandler); Assert.Null(semanticInfo.ImplicitConversion.Method); // https://github.com/dotnet/roslyn/issues/54505 Assert IConversionOperation.IsImplicit when IOperation is implemented for interpolated strings. } private CompilationVerifier CompileAndVerifyOnCorrectPlatforms(CSharpCompilation compilation, string expectedOutput) => CompileAndVerify( compilation, expectedOutput: ExecutionConditionUtil.IsMonoOrCoreClr ? expectedOutput : null, verify: ExecutionConditionUtil.IsMonoOrCoreClr ? Verification.Passes : Verification.Skipped); [Theory] [CombinatorialData] public void CustomHandlerLocal([CombinatorialValues("class", "struct")] string type, bool useBoolReturns) { var code = @" CustomHandler builder = $""Literal{1,2:f}""; System.Console.WriteLine(builder.ToString());"; var builder = GetInterpolatedStringCustomHandlerType("CustomHandler", type, useBoolReturns); var comp = CreateCompilation(new[] { code, builder }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" literal:Literal value:1 alignment:2 format:f"); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (type, useBoolReturns) switch { (type: "struct", useBoolReturns: true) => @" { // Code size 67 (0x43) .maxstack 4 .locals init (CustomHandler V_0, //builder CustomHandler V_1) IL_0000: ldloca.s V_1 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_1 IL_000b: ldstr ""Literal"" IL_0010: call ""bool CustomHandler.AppendLiteral(string)"" IL_0015: brfalse.s IL_002c IL_0017: ldloca.s V_1 IL_0019: ldc.i4.1 IL_001a: box ""int"" IL_001f: ldc.i4.2 IL_0020: ldstr ""f"" IL_0025: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_002a: br.s IL_002d IL_002c: ldc.i4.0 IL_002d: pop IL_002e: ldloc.1 IL_002f: stloc.0 IL_0030: ldloca.s V_0 IL_0032: constrained. ""CustomHandler"" IL_0038: callvirt ""string object.ToString()"" IL_003d: call ""void System.Console.WriteLine(string)"" IL_0042: ret } ", (type: "struct", useBoolReturns: false) => @" { // Code size 61 (0x3d) .maxstack 4 .locals init (CustomHandler V_0, //builder CustomHandler V_1) IL_0000: ldloca.s V_1 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_1 IL_000b: ldstr ""Literal"" IL_0010: call ""void CustomHandler.AppendLiteral(string)"" IL_0015: ldloca.s V_1 IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: ldc.i4.2 IL_001e: ldstr ""f"" IL_0023: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0028: ldloc.1 IL_0029: stloc.0 IL_002a: ldloca.s V_0 IL_002c: constrained. ""CustomHandler"" IL_0032: callvirt ""string object.ToString()"" IL_0037: call ""void System.Console.WriteLine(string)"" IL_003c: ret } ", (type: "class", useBoolReturns: true) => @" { // Code size 55 (0x37) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""Literal"" IL_000e: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0013: brfalse.s IL_0029 IL_0015: ldloc.0 IL_0016: ldc.i4.1 IL_0017: box ""int"" IL_001c: ldc.i4.2 IL_001d: ldstr ""f"" IL_0022: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: callvirt ""string object.ToString()"" IL_0031: call ""void System.Console.WriteLine(string)"" IL_0036: ret } ", (type: "class", useBoolReturns: false) => @" { // Code size 47 (0x2f) .maxstack 5 IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: dup IL_0008: ldstr ""Literal"" IL_000d: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0012: dup IL_0013: ldc.i4.1 IL_0014: box ""int"" IL_0019: ldc.i4.2 IL_001a: ldstr ""f"" IL_001f: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0024: callvirt ""string object.ToString()"" IL_0029: call ""void System.Console.WriteLine(string)"" IL_002e: ret } ", _ => throw ExceptionUtilities.Unreachable }; } [Fact] public void CustomHandlerMethodArgument() { var code = @" M($""{1,2:f}Literal""); void M(CustomHandler b) { System.Console.WriteLine(b.ToString()); }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"<top-level-statements-entry-point>", @" { // Code size 50 (0x32) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: call ""void <Program>$.<<Main>$>g__M|0_0(CustomHandler)"" IL_0031: ret } "); } [Fact] public void ExplicitHandlerCast_InCode() { var code = @"System.Console.WriteLine((CustomHandler)$""{1,2:f}Literal"");"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: false) }); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); SyntaxNode syntax = tree.GetRoot().DescendantNodes().OfType<CastExpressionSyntax>().Single(); var semanticInfo = model.GetSemanticInfoSummary(syntax); Assert.Equal("CustomHandler", semanticInfo.Type.ToTestDisplayString()); Assert.Equal(SpecialType.System_Object, semanticInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.ImplicitReference, semanticInfo.ImplicitConversion.Kind); syntax = ((CastExpressionSyntax)syntax).Expression; Assert.IsType<InterpolatedStringExpressionSyntax>(syntax); semanticInfo = model.GetSemanticInfoSummary(syntax); Assert.Equal(SpecialType.System_String, semanticInfo.Type.SpecialType); Assert.Equal(SpecialType.System_String, semanticInfo.ConvertedType.SpecialType); Assert.Equal(ConversionKind.Identity, semanticInfo.ImplicitConversion.Kind); // https://github.com/dotnet/roslyn/issues/54505 Assert cast is explicit after IOperation is implemented var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 42 (0x2a) .maxstack 5 IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: dup IL_0008: ldc.i4.1 IL_0009: box ""int"" IL_000e: ldc.i4.2 IL_000f: ldstr ""f"" IL_0014: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0019: dup IL_001a: ldstr ""Literal"" IL_001f: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0024: call ""void System.Console.WriteLine(object)"" IL_0029: ret } "); } [Fact] public void HandlerConversionPreferredOverStringForNonConstant() { var code = @" C.M($""{1,2:f}Literal""); class C { public static void M(CustomHandler b) { System.Console.WriteLine(b.ToString()); } public static void M(string s) { throw null; } } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"<top-level-statements-entry-point>", @" { // Code size 50 (0x32) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: call ""void C.M(CustomHandler)"" IL_0031: ret } "); } [Fact] public void StringPreferredOverHandlerConversionForConstant() { var code = @" C.M($""{""Literal""}""); class C { public static void M(CustomHandler b) { throw null; } public static void M(string s) { System.Console.WriteLine(s); } } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); var verifier = CompileAndVerify(comp, expectedOutput: @"Literal"); verifier.VerifyIL(@"<top-level-statements-entry-point>", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldstr ""Literal"" IL_0005: call ""void C.M(string)"" IL_000a: ret } "); } [Fact] public void HandlerConversionPreferredOverStringForNonConstant_AttributeConstructor() { var code = @" using System; [Attr($""{1}"")] class Attr : Attribute { public Attr(string s) {} public Attr(CustomHandler c) {} } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); comp.VerifyDiagnostics( // (4,2): error CS0181: Attribute constructor parameter 'c' has type 'CustomHandler', which is not a valid attribute parameter type // [Attr($"{1}")] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "Attr").WithArguments("c", "CustomHandler").WithLocation(4, 2) ); VerifyInterpolatedStringExpression(comp); var attr = comp.SourceAssembly.SourceModule.GlobalNamespace.GetTypeMember("Attr"); Assert.Equal("Attr..ctor(CustomHandler c)", attr.GetAttributes().Single().AttributeConstructor.ToTestDisplayString()); } [Fact] public void StringPreferredOverHandlerConversionForConstant_AttributeConstructor() { var code = @" using System; [Attr($""{""Literal""}"")] class Attr : Attribute { public Attr(string s) {} public Attr(CustomHandler c) {} } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); CompileAndVerify(comp, symbolValidator: validate, sourceSymbolValidator: validate); void validate(ModuleSymbol m) { var attr = m.GlobalNamespace.GetTypeMember("Attr"); Assert.Equal("Attr..ctor(System.String s)", attr.GetAttributes().Single().AttributeConstructor.ToTestDisplayString()); } } [Fact] public void MultipleBuilderTypes() { var code = @" C.M($""""); class C { public static void M(CustomHandler1 c) => throw null; public static void M(CustomHandler2 c) => throw null; }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler1", "struct", useBoolReturns: false), GetInterpolatedStringCustomHandlerType("CustomHandler2", "struct", useBoolReturns: false, includeOneTimeHelpers: false) }); comp.VerifyDiagnostics( // (2,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(CustomHandler1)' and 'C.M(CustomHandler2)' // C.M($""); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(CustomHandler1)", "C.M(CustomHandler2)").WithLocation(2, 3) ); } [Fact] public void GenericOverloadResolution_01() { var code = @" using System; C.M($""{1,2:f}Literal""); class C { public static void M<T>(T t) => throw null; public static void M(CustomHandler c) => Console.WriteLine(c); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 50 (0x32) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: call ""void C.M(CustomHandler)"" IL_0031: ret } "); } [Fact] public void GenericOverloadResolution_02() { var code = @" using System; C.M($""{1,2:f}Literal""); class C { public static void M<T>(T t) where T : CustomHandler => throw null; public static void M(CustomHandler c) => Console.WriteLine(c); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 50 (0x32) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: call ""void C.M(CustomHandler)"" IL_0031: ret } "); } [Fact] public void GenericOverloadResolution_03() { var code = @" C.M($""{1,2:f}Literal""); class C { public static void M<T>(T t) where T : CustomHandler => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); comp.VerifyDiagnostics( // (2,3): error CS0311: The type 'string' cannot be used as type parameter 'T' in the generic type or method 'C.M<T>(T)'. There is no implicit reference conversion from 'string' to 'CustomHandler'. // C.M($"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "M").WithArguments("C.M<T>(T)", "CustomHandler", "T", "string").WithLocation(2, 3) ); } [Fact] public void GenericInference_01() { var code = @" C.M($""{1,2:f}Literal"", default(CustomHandler)); C.M(default(CustomHandler), $""{1,2:f}Literal""); class C { public static void M<T>(T t1, T t2) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (2,3): error CS0411: The type arguments for method 'C.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // C.M($"{1,2:f}Literal", default(CustomHandler)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, T)").WithLocation(2, 3), // (3,3): error CS0411: The type arguments for method 'C.M<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // C.M(default(CustomHandler), $"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, T)").WithLocation(3, 3) ); } [Fact] public void GenericInference_02() { var code = @" using System; C.M(default(CustomHandler), () => $""{1,2:f}Literal""); class C { public static void M<T>(T t1, Func<T> t2) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); comp.VerifyDiagnostics( // (3,3): error CS0411: The type arguments for method 'C.M<T>(T, Func<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // C.M(default(CustomHandler), () => $"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M").WithArguments("C.M<T>(T, System.Func<T>)").WithLocation(3, 3) ); } [Fact] public void GenericInference_03() { var code = @" using System; C.M($""{1,2:f}Literal"", default(CustomHandler)); class C { public static void M<T>(T t1, T t2) => Console.WriteLine(t1); } partial class CustomHandler { public static implicit operator CustomHandler(string s) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 51 (0x33) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: ldnull IL_002d: call ""void C.M<CustomHandler>(CustomHandler, CustomHandler)"" IL_0032: ret } "); } [Fact] public void GenericInference_04() { var code = @" using System; C.M(default(CustomHandler), () => $""{1,2:f}Literal""); class C { public static void M<T>(T t1, Func<T> t2) => Console.WriteLine(t2()); } partial class CustomHandler { public static implicit operator CustomHandler(string s) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<Program>$.<>c.<<Main>$>b__0_0()", @" { // Code size 45 (0x2d) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: ret } "); } [Fact] public void LambdaReturnInference_01() { var code = @" using System; Func<CustomHandler> f = () => $""{1,2:f}Literal""; Console.WriteLine(f()); "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerify(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"<Program>$.<>c.<<Main>$>b__0_0()", @" { // Code size 45 (0x2d) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldc.i4.1 IL_000a: box ""int"" IL_000f: ldc.i4.2 IL_0010: ldstr ""f"" IL_0015: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_001a: brfalse.s IL_0029 IL_001c: ldloc.0 IL_001d: ldstr ""Literal"" IL_0022: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.0 IL_002c: ret } "); } [Fact] public void LambdaReturnInference_02() { var code = @" using System; CultureInfoNormalizer.Normalize(); C.M(() => $""{1,2:f}Literal""); class C { public static void M(Func<string> f) => Console.WriteLine(f()); public static void M(Func<CustomHandler> f) => throw null; } "; // Interpolated string handler conversions are not considered when determining the natural type of an expression: the natural return type of this lambda is string, // so we don't even consider that there is a conversion from interpolated string expression to CustomHandler here (Sections 12.6.3.13 and 12.6.3.15 of the spec). var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: true) }); var verifier = CompileAndVerify(comp, expectedOutput: @"1.00Literal"); // No DefaultInterpolatedStringHandler was included in the compilation, so it falls back to string.Format verifier.VerifyIL(@"<Program>$.<>c.<<Main>$>b__0_0()", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: ldstr ""{0,2:f}Literal"" IL_0005: ldc.i4.1 IL_0006: box ""int"" IL_000b: call ""string string.Format(string, object)"" IL_0010: ret } "); } [Fact] public void LambdaReturnInference_03() { // Same as 2, but using a type that isn't allowed in an interpolated string. There is an implicit conversion error on the ref struct // when converting to a string, because S cannot be a component of an interpolated string. This conversion error causes the lambda to // fail to bind as Func<string>, even though the natural return type is string, and the only successful bind is Func<CustomHandler>. var code = @" using System; C.M(() => $""{new S { Field = ""Field"" }}""); static class C { public static void M(Func<string> f) => throw null; public static void M(Func<CustomHandler> f) => Console.WriteLine(f()); } public partial class CustomHandler { public void AppendFormatted(S value) => _builder.AppendLine(""value:"" + value.Field); } public ref struct S { public string Field { get; set; } } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"value:Field"); verifier.VerifyIL(@"<Program>$.<>c.<<Main>$>b__0_0()", @" { // Code size 35 (0x23) .maxstack 4 .locals init (S V_0) IL_0000: ldc.i4.0 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: dup IL_0008: ldloca.s V_0 IL_000a: initobj ""S"" IL_0010: ldloca.s V_0 IL_0012: ldstr ""Field"" IL_0017: call ""void S.Field.set"" IL_001c: ldloc.0 IL_001d: callvirt ""void CustomHandler.AppendFormatted(S)"" IL_0022: ret } "); } [Fact] public void LambdaReturnInference_04() { // Same as 3, but with S added to DefaultInterpolatedStringHandler (which then allows the lambda to be bound as Func<string>, matching the natural return type) var code = @" using System; C.M(() => $""{new S { Field = ""Field"" }}""); static class C { public static void M(Func<string> f) => Console.WriteLine(f()); public static void M(Func<CustomHandler> f) => throw null; } public partial class CustomHandler { public void AppendFormatted(S value) => throw null; } public ref struct S { public string Field { get; set; } } namespace System.Runtime.CompilerServices { public ref partial struct DefaultInterpolatedStringHandler { public void AppendFormatted(S value) => _builder.AppendLine(""value:"" + value.Field); } } "; string[] source = new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: false), GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: true, useBoolReturns: false) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (3,11): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater. // C.M(() => $"{new S { Field = "Field" }}"); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, @"$""{new S { Field = ""Field"" }}""").WithArguments("interpolated string handlers", "10.0").WithLocation(3, 11), // (3,14): error CS8773: Feature 'interpolated string handlers' is not available in C# 9.0. Please use language version 10.0 or greater. // C.M(() => $"{new S { Field = "Field" }}"); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, @"new S { Field = ""Field"" }").WithArguments("interpolated string handlers", "10.0").WithLocation(3, 14) ); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"value:Field"); verifier.VerifyIL(@"<Program>$.<>c.<<Main>$>b__0_0()", @" { // Code size 45 (0x2d) .maxstack 3 .locals init (System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_0, S V_1) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.0 IL_0003: ldc.i4.1 IL_0004: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldloca.s V_1 IL_000d: initobj ""S"" IL_0013: ldloca.s V_1 IL_0015: ldstr ""Field"" IL_001a: call ""void S.Field.set"" IL_001f: ldloc.1 IL_0020: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted(S)"" IL_0025: ldloca.s V_0 IL_0027: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_002c: ret } "); } [Fact] public void LambdaReturnInference_05() { var code = @" using System; C.M(b => { if (b) return default(CustomHandler); else return $""{1,2:f}Literal""; }); static class C { public static void M(Func<bool, string> f) => throw null; public static void M(Func<bool, CustomHandler> f) => Console.WriteLine(f(false)); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"<Program>$.<>c.<<Main>$>b__0_0(bool)", @" { // Code size 55 (0x37) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldarg.1 IL_0001: brfalse.s IL_000d IL_0003: ldloca.s V_0 IL_0005: initobj ""CustomHandler"" IL_000b: ldloc.0 IL_000c: ret IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: ret } "); } [Fact] public void LambdaReturnInference_06() { // Same as 5, but with an implicit conversion from the builder type to string. This implicit conversion // means that a best common type can be inferred for all branches of the lambda expression (Section 12.6.3.15 of the spec) // and because there is a best common type, the inferred return type of the lambda is string. Since the inferred return type // has an identity conversion to the return type of Func<bool, string>, that is preferred. var code = @" using System; CultureInfoNormalizer.Normalize(); C.M(b => { if (b) return default(CustomHandler); else return $""{1,2:f}Literal""; }); static class C { public static void M(Func<bool, string> f) => Console.WriteLine(f(false)); public static void M(Func<bool, CustomHandler> f) => throw null; } public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"1.00Literal"); verifier.VerifyIL(@"<Program>$.<>c.<<Main>$>b__0_0(bool)", @" { // Code size 35 (0x23) .maxstack 2 .locals init (CustomHandler V_0) IL_0000: ldarg.1 IL_0001: brfalse.s IL_0012 IL_0003: ldloca.s V_0 IL_0005: initobj ""CustomHandler"" IL_000b: ldloc.0 IL_000c: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0011: ret IL_0012: ldstr ""{0,2:f}Literal"" IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: call ""string string.Format(string, object)"" IL_0022: ret } "); } [Fact] public void LambdaReturnInference_07() { // Same as 5, but with an implicit conversion from string to the builder type. var code = @" using System; C.M(b => { if (b) return default(CustomHandler); else return $""{1,2:f}Literal""; }); static class C { public static void M(Func<bool, string> f) => Console.WriteLine(f(false)); public static void M(Func<bool, CustomHandler> f) => Console.WriteLine(f(false)); } public partial struct CustomHandler { public static implicit operator CustomHandler(string s) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL(@"<Program>$.<>c.<<Main>$>b__0_0(bool)", @" { // Code size 55 (0x37) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldarg.1 IL_0001: brfalse.s IL_000d IL_0003: ldloca.s V_0 IL_0005: initobj ""CustomHandler"" IL_000b: ldloc.0 IL_000c: ret IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: ret } "); } [Fact] public void LambdaReturnInference_08() { // Same as 5, but with an implicit conversion from the builder type to string and from string to the builder type. var code = @" using System; C.M(b => { if (b) return default(CustomHandler); else return $""{1,2:f}Literal""; }); static class C { public static void M(Func<bool, string> f) => Console.WriteLine(f(false)); public static void M(Func<bool, CustomHandler> f) => throw null; } public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; public static implicit operator CustomHandler(string c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (3,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(Func<bool, string>)' and 'C.M(Func<bool, CustomHandler>)' // C.M(b => Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(System.Func<bool, string>)", "C.M(System.Func<bool, CustomHandler>)").WithLocation(3, 3) ); } [Fact] public void LambdaInference_AmbiguousInOlderLangVersions() { var code = @" using System; C.M(param => { param = $""{1}""; }); static class C { public static void M(Action<string> f) => throw null; public static void M(Action<CustomHandler> f) => throw null; } "; var source = new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); // This successful emit is being caused by https://github.com/dotnet/roslyn/issues/53761, along with the duplicate diagnostics in LambdaReturnInference_04 // We should not be changing binding behavior based on LangVersion. comp.VerifyEmitDiagnostics(); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (3,3): error CS0121: The call is ambiguous between the following methods or properties: 'C.M(Action<string>)' and 'C.M(Action<CustomHandler>)' // C.M(param => Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M(System.Action<string>)", "C.M(System.Action<CustomHandler>)").WithLocation(3, 3) ); } [Fact] public void TernaryTypes_01() { var code = @" using System; var x = (bool)(object)false ? default(CustomHandler) : $""{1,2:f}Literal""; Console.WriteLine(x); "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 76 (0x4c) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brtrue.s IL_0038 IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: br.s IL_0041 IL_0038: ldloca.s V_0 IL_003a: initobj ""CustomHandler"" IL_0040: ldloc.0 IL_0041: box ""CustomHandler"" IL_0046: call ""void System.Console.WriteLine(object)"" IL_004b: ret } "); } [Fact] public void TernaryTypes_02() { // Same as 01, but with a conversion from CustomHandler to string. The rules here are similar to LambdaReturnInference_06 var code = @" using System; CultureInfoNormalizer.Normalize(); var x = (bool)(object)false ? default(CustomHandler) : $""{1,2:f}Literal""; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"1.00Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 56 (0x38) .maxstack 2 .locals init (CustomHandler V_0) IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldc.i4.0 IL_0006: box ""bool"" IL_000b: unbox.any ""bool"" IL_0010: brtrue.s IL_0024 IL_0012: ldstr ""{0,2:f}Literal"" IL_0017: ldc.i4.1 IL_0018: box ""int"" IL_001d: call ""string string.Format(string, object)"" IL_0022: br.s IL_0032 IL_0024: ldloca.s V_0 IL_0026: initobj ""CustomHandler"" IL_002c: ldloc.0 IL_002d: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0032: call ""void System.Console.WriteLine(string)"" IL_0037: ret } "); } [Fact] public void TernaryTypes_03() { // Same as 02, but with a target-type var code = @" using System; CustomHandler x = (bool)(object)false ? default(CustomHandler) : $""{1,2:f}Literal""; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,19): error CS0029: Cannot implicitly convert type 'string' to 'CustomHandler' // CustomHandler x = (bool)(object)false ? default(CustomHandler) : $"{1,2:f}Literal"; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"(bool)(object)false ? default(CustomHandler) : $""{1,2:f}Literal""").WithArguments("string", "CustomHandler").WithLocation(4, 19) ); } [Fact] public void TernaryTypes_04() { // Same 01, but with a conversion from string to CustomHandler. The rules here are similar to LambdaReturnInference_07 var code = @" using System; var x = (bool)(object)false ? default(CustomHandler) : $""{1,2:f}Literal""; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 76 (0x4c) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brtrue.s IL_0038 IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: br.s IL_0041 IL_0038: ldloca.s V_0 IL_003a: initobj ""CustomHandler"" IL_0040: ldloc.0 IL_0041: box ""CustomHandler"" IL_0046: call ""void System.Console.WriteLine(object)"" IL_004b: ret } "); } [Fact] public void TernaryTypes_05() { // Same 01, but with a conversion from string to CustomHandler and CustomHandler to string. var code = @" using System; var x = (bool)(object)false ? default(CustomHandler) : $""{1,2:f}Literal""; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,9): error CS0172: Type of conditional expression cannot be determined because 'CustomHandler' and 'string' implicitly convert to one another // var x = (bool)(object)false ? default(CustomHandler) : $"{1,2:f}Literal"; Diagnostic(ErrorCode.ERR_AmbigQM, @"(bool)(object)false ? default(CustomHandler) : $""{1,2:f}Literal""").WithArguments("CustomHandler", "string").WithLocation(4, 9) ); } [Fact] public void TernaryTypes_06() { // Same 05, but with a target type var code = @" using System; CustomHandler x = (bool)(object)false ? default(CustomHandler) : $""{1,2:f}Literal""; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; public static implicit operator string(CustomHandler c) => c.ToString(); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 76 (0x4c) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brtrue.s IL_0038 IL_000d: ldloca.s V_0 IL_000f: ldc.i4.7 IL_0010: ldc.i4.1 IL_0011: call ""CustomHandler..ctor(int, int)"" IL_0016: ldloca.s V_0 IL_0018: ldc.i4.1 IL_0019: box ""int"" IL_001e: ldc.i4.2 IL_001f: ldstr ""f"" IL_0024: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0029: ldloca.s V_0 IL_002b: ldstr ""Literal"" IL_0030: call ""void CustomHandler.AppendLiteral(string)"" IL_0035: ldloc.0 IL_0036: br.s IL_0041 IL_0038: ldloca.s V_0 IL_003a: initobj ""CustomHandler"" IL_0040: ldloc.0 IL_0041: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0046: call ""void System.Console.WriteLine(string)"" IL_004b: ret } "); } [Fact] public void SwitchTypes_01() { // Switch expressions infer a best type based on _types_, not based on expressions (section 12.6.3.15 of the spec). Because this is based on types // and not on expression conversions, no best type can be found for this switch expression. var code = @" using System; var x = (bool)(object)false switch { true => default(CustomHandler), false => $""{1,2:f}Literal"" }; Console.WriteLine(x); "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,29): error CS8506: No best type was found for the switch expression. // var x = (bool)(object)false switch { true => default(CustomHandler), false => $"{1,2:f}Literal" }; Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(4, 29) ); } [Fact] public void SwitchTypes_02() { // Same as 01, but with a conversion from CustomHandler. This allows the switch expression to infer a best-common type, which is string. var code = @" using System; CultureInfoNormalizer.Normalize(); var x = (bool)(object)false switch { true => default(CustomHandler), false => $""{1,2:f}Literal"" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @"1.00Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 59 (0x3b) .maxstack 2 .locals init (string V_0, CustomHandler V_1) IL_0000: call ""void CultureInfoNormalizer.Normalize()"" IL_0005: ldc.i4.0 IL_0006: box ""bool"" IL_000b: unbox.any ""bool"" IL_0010: brfalse.s IL_0023 IL_0012: ldloca.s V_1 IL_0014: initobj ""CustomHandler"" IL_001a: ldloc.1 IL_001b: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0020: stloc.0 IL_0021: br.s IL_0034 IL_0023: ldstr ""{0,2:f}Literal"" IL_0028: ldc.i4.1 IL_0029: box ""int"" IL_002e: call ""string string.Format(string, object)"" IL_0033: stloc.0 IL_0034: ldloc.0 IL_0035: call ""void System.Console.WriteLine(string)"" IL_003a: ret } "); } [Fact] public void SwitchTypes_03() { // Same 02, but with a target-type. The natural type will fail to compile, so the switch will use a target type (unlike TernaryTypes_03, which fails to compile). var code = @" using System; CustomHandler x = (bool)(object)false switch { true => default(CustomHandler), false => $""{1,2:f}Literal"" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator string(CustomHandler c) => c.ToString(); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 79 (0x4f) .maxstack 4 .locals init (CustomHandler V_0, CustomHandler V_1) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brfalse.s IL_0019 IL_000d: ldloca.s V_1 IL_000f: initobj ""CustomHandler"" IL_0015: ldloc.1 IL_0016: stloc.0 IL_0017: br.s IL_0043 IL_0019: ldloca.s V_1 IL_001b: ldc.i4.7 IL_001c: ldc.i4.1 IL_001d: call ""CustomHandler..ctor(int, int)"" IL_0022: ldloca.s V_1 IL_0024: ldc.i4.1 IL_0025: box ""int"" IL_002a: ldc.i4.2 IL_002b: ldstr ""f"" IL_0030: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0035: ldloca.s V_1 IL_0037: ldstr ""Literal"" IL_003c: call ""void CustomHandler.AppendLiteral(string)"" IL_0041: ldloc.1 IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0049: call ""void System.Console.WriteLine(string)"" IL_004e: ret } "); } [Fact] public void SwitchTypes_04() { // Same as 01, but with a conversion to CustomHandler. This allows the switch expression to infer a best-common type, which is CustomHandler. var code = @" using System; var x = (bool)(object)false switch { true => default(CustomHandler), false => $""{1,2:f}Literal"" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 79 (0x4f) .maxstack 4 .locals init (CustomHandler V_0, CustomHandler V_1) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brfalse.s IL_0019 IL_000d: ldloca.s V_1 IL_000f: initobj ""CustomHandler"" IL_0015: ldloc.1 IL_0016: stloc.0 IL_0017: br.s IL_0043 IL_0019: ldloca.s V_1 IL_001b: ldc.i4.7 IL_001c: ldc.i4.1 IL_001d: call ""CustomHandler..ctor(int, int)"" IL_0022: ldloca.s V_1 IL_0024: ldc.i4.1 IL_0025: box ""int"" IL_002a: ldc.i4.2 IL_002b: ldstr ""f"" IL_0030: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0035: ldloca.s V_1 IL_0037: ldstr ""Literal"" IL_003c: call ""void CustomHandler.AppendLiteral(string)"" IL_0041: ldloc.1 IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: box ""CustomHandler"" IL_0049: call ""void System.Console.WriteLine(object)"" IL_004e: ret } "); } [Fact] public void SwitchTypes_05() { // Same as 01, but with conversions in both directions. No best common type can be found. var code = @" using System; var x = (bool)(object)false switch { true => default(CustomHandler), false => $""{1,2:f}Literal"" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; public static implicit operator string(CustomHandler c) => throw null; } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (4,29): error CS8506: No best type was found for the switch expression. // var x = (bool)(object)false switch { true => default(CustomHandler), false => $"{1,2:f}Literal" }; Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(4, 29) ); } [Fact] public void SwitchTypes_06() { // Same as 05, but with a target type. var code = @" using System; CustomHandler x = (bool)(object)false switch { true => default(CustomHandler), false => $""{1,2:f}Literal"" }; Console.WriteLine(x); public partial struct CustomHandler { public static implicit operator CustomHandler(string c) => throw null; public static implicit operator string(CustomHandler c) => c.ToString(); } "; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 79 (0x4f) .maxstack 4 .locals init (CustomHandler V_0, CustomHandler V_1) IL_0000: ldc.i4.0 IL_0001: box ""bool"" IL_0006: unbox.any ""bool"" IL_000b: brfalse.s IL_0019 IL_000d: ldloca.s V_1 IL_000f: initobj ""CustomHandler"" IL_0015: ldloc.1 IL_0016: stloc.0 IL_0017: br.s IL_0043 IL_0019: ldloca.s V_1 IL_001b: ldc.i4.7 IL_001c: ldc.i4.1 IL_001d: call ""CustomHandler..ctor(int, int)"" IL_0022: ldloca.s V_1 IL_0024: ldc.i4.1 IL_0025: box ""int"" IL_002a: ldc.i4.2 IL_002b: ldstr ""f"" IL_0030: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0035: ldloca.s V_1 IL_0037: ldstr ""Literal"" IL_003c: call ""void CustomHandler.AppendLiteral(string)"" IL_0041: ldloc.1 IL_0042: stloc.0 IL_0043: ldloc.0 IL_0044: call ""string CustomHandler.op_Implicit(CustomHandler)"" IL_0049: call ""void System.Console.WriteLine(string)"" IL_004e: ret } "); } [Fact] public void PassAsRefWithoutKeyword_01() { var code = @" M($""{1,2:f}Literal""); void M(ref CustomHandler c) => System.Console.WriteLine(c);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 48 (0x30) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_0 IL_002a: call ""void <Program>$.<<Main>$>g__M|0_0(ref CustomHandler)"" IL_002f: ret } "); } [Fact] public void PassAsRefWithoutKeyword_02() { var code = @" M($""{1,2:f}Literal""); M(ref $""{1,2:f}Literal""); void M(ref CustomHandler c) => System.Console.WriteLine(c);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (2,3): error CS1620: Argument 1 must be passed with the 'ref' keyword // M($"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_BadArgRef, @"$""{1,2:f}Literal""").WithArguments("1", "ref").WithLocation(2, 3), // (3,7): error CS1510: A ref or out value must be an assignable variable // M(ref $"{1,2:f}Literal"); Diagnostic(ErrorCode.ERR_RefLvalueExpected, @"$""{1,2:f}Literal""").WithLocation(3, 7) ); } [Fact] public void PassAsRefWithoutKeyword_03() { var code = @" M($""{1,2:f}Literal""); void M(in CustomHandler c) => System.Console.WriteLine(c);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "class", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 45 (0x2d) .maxstack 5 .locals init (CustomHandler V_0) IL_0000: ldc.i4.7 IL_0001: ldc.i4.1 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: dup IL_0008: ldc.i4.1 IL_0009: box ""int"" IL_000e: ldc.i4.2 IL_000f: ldstr ""f"" IL_0014: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0019: dup IL_001a: ldstr ""Literal"" IL_001f: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0024: stloc.0 IL_0025: ldloca.s V_0 IL_0027: call ""void <Program>$.<<Main>$>g__M|0_0(in CustomHandler)"" IL_002c: ret } "); } [Fact] public void PassAsRefWithoutKeyword_04() { var code = @" M($""{1,2:f}Literal""); void M(in CustomHandler c) => System.Console.WriteLine(c);"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 48 (0x30) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_0 IL_002a: call ""void <Program>$.<<Main>$>g__M|0_0(in CustomHandler)"" IL_002f: ret } "); } [Theory] [CombinatorialData] public void RefOverloadResolution_Struct([CombinatorialValues("in", "ref")] string refKind) { var code = @" C.M($""{1,2:f}Literal""); class C { public static void M(CustomHandler c) => System.Console.WriteLine(c); public static void M(" + refKind + @" CustomHandler c) => System.Console.WriteLine(c); }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 47 (0x2f) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloc.0 IL_0029: call ""void C.M(CustomHandler)"" IL_002e: ret } "); } [Theory] [CombinatorialData] public void RefOverloadResolution_Class([CombinatorialValues("in", "ref")] string refKind) { var code = @" C.M($""{1,2:f}Literal""); class C { public static void M(CustomHandler c) => System.Console.WriteLine(c); public static void M(" + refKind + @" CustomHandler c) => System.Console.WriteLine(c); }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }, targetFramework: TargetFramework.NetCoreApp); VerifyInterpolatedStringExpression(comp); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 47 (0x2f) .maxstack 4 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloc.0 IL_0029: call ""void C.M(CustomHandler)"" IL_002e: ret } "); } [Fact] public void RefOverloadResolution_MultipleBuilderTypes() { var code = @" C.M($""{1,2:f}Literal""); class C { public static void M(CustomHandler1 c) => System.Console.WriteLine(c); public static void M(ref CustomHandler2 c) => throw null; }"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler1", "struct", useBoolReturns: false), GetInterpolatedStringCustomHandlerType("CustomHandler2", "struct", useBoolReturns: false, includeOneTimeHelpers: false) }); VerifyInterpolatedStringExpression(comp, "CustomHandler1"); var verifier = CompileAndVerifyOnCorrectPlatforms(comp, expectedOutput: @" value:1 alignment:2 format:f literal:Literal"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 47 (0x2f) .maxstack 4 .locals init (CustomHandler1 V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler1..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: ldc.i4.2 IL_0012: ldstr ""f"" IL_0017: call ""void CustomHandler1.AppendFormatted(object, int, string)"" IL_001c: ldloca.s V_0 IL_001e: ldstr ""Literal"" IL_0023: call ""void CustomHandler1.AppendLiteral(string)"" IL_0028: ldloc.0 IL_0029: call ""void C.M(CustomHandler1)"" IL_002e: ret } "); } private const string InterpolatedStringHandlerAttributesVB = @" Namespace System.Runtime.CompilerServices <AttributeUsage(AttributeTargets.Class Or AttributeTargets.Struct, AllowMultiple:=False, Inherited:=False)> Public NotInheritable Class InterpolatedStringHandlerAttribute Inherits Attribute End Class <AttributeUsage(AttributeTargets.Parameter, AllowMultiple:=False, Inherited:=False)> Public NotInheritable Class InterpolatedStringHandlerArgumentAttribute Inherits Attribute Public Sub New(argument As String) Arguments = { argument } End Sub Public Sub New(ParamArray arguments() as String) Me.Arguments = arguments End Sub Public ReadOnly Property Arguments As String() End Class End Namespace "; [Fact] public void InterpolatedStringHandlerArgumentAttributeError_NonHandlerType() { var code = @" using System.Runtime.CompilerServices; C.M($""""); class C { public static void M([InterpolatedStringHandlerArgumentAttribute] string s) {} } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute }); comp.VerifyDiagnostics( // (8,27): error CS8946: 'string' is not an interpolated string handler type. // public static void M([InterpolatedStringHandlerArgumentAttribute] string s) {} Diagnostic(ErrorCode.ERR_TypeIsNotAnInterpolatedStringHandlerType, "InterpolatedStringHandlerArgumentAttribute").WithArguments("string").WithLocation(8, 27) ); var sParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", sParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(sParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(sParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_NonHandlerType_Metadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i as Integer, <InterpolatedStringHandlerArgument(""i"")> c As String) End Sub End Class "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); // Note: there is no compilation error here because the natural type of a string is still string, and // we just bind to that method without checking the handler attribute. var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics(); var sParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", sParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(sParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(sParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_InvalidArgument() { var code = @" using System.Runtime.CompilerServices; C.M($""""); class C { public static void M([InterpolatedStringHandlerArgumentAttribute(1)] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (8,70): error CS1503: Argument 1: cannot convert from 'int' to 'string' // public static void M([InterpolatedStringHandlerArgumentAttribute(1)] CustomHandler c) {} Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "string").WithLocation(8, 70) ); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.False(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_01() { var code = @" using System.Runtime.CompilerServices; C.M($""""); class C { public static void M([InterpolatedStringHandlerArgumentAttribute(""NonExistant"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 5), // (8,27): error CS8945: 'NonExistant' is not a valid parameter name from 'C.M(CustomHandler)'. // public static void M([InterpolatedStringHandlerArgumentAttribute("NonExistant")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""NonExistant"")").WithArguments("NonExistant", "C.M(CustomHandler)").WithLocation(8, 27) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_01_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(<InterpolatedStringHandlerArgument(""NonExistant"")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 5) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_02() { var code = @" using System.Runtime.CompilerServices; C.M(1, $""""); class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"", ""NonExistant"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8), // (8,34): error CS8945: 'NonExistant' is not a valid parameter name from 'C.M(int, CustomHandler)'. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("i", "NonExistant")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""i"", ""NonExistant"")").WithArguments("NonExistant", "C.M(int, CustomHandler)").WithLocation(8, 34) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_02_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument(""i"", ""NonExistant"")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_03() { var code = @" using System.Runtime.CompilerServices; C.M(1, $""""); class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""NonExistant1"", ""NonExistant2"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8), // (8,34): error CS8945: 'NonExistant1' is not a valid parameter name from 'C.M(int, CustomHandler)'. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("NonExistant1", "NonExistant2")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""NonExistant1"", ""NonExistant2"")").WithArguments("NonExistant1", "C.M(int, CustomHandler)").WithLocation(8, 34), // (8,34): error CS8945: 'NonExistant2' is not a valid parameter name from 'C.M(int, CustomHandler)'. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("NonExistant1", "NonExistant2")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_InvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute(""NonExistant1"", ""NonExistant2"")").WithArguments("NonExistant2", "C.M(int, CustomHandler)").WithLocation(8, 34) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_UnknownName_03_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument(""NonExistant1"", ""NonExistant2"")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_ReferenceSelf() { var code = @" using System.Runtime.CompilerServices; C.M(1, $""""); class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""c"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8), // (8,34): error CS8948: InterpolatedStringHandlerArgumentAttribute arguments cannot refer to the parameter the attribute is used on. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute("c")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_CannotUseSelfAsInterpolatedStringHandlerArgument, @"InterpolatedStringHandlerArgumentAttribute(""c"")").WithLocation(8, 34) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_ReferencesSelf_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(<InterpolatedStringHandlerArgument(""c"")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 5) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_NullConstant() { var code = @" using System.Runtime.CompilerServices; C.M(1, $""""); class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(new string[] { null })] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 8), // (8,34): error CS8943: 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. // public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(new string[] { null })] CustomHandler c) {} Diagnostic(ErrorCode.ERR_NullInvalidInterpolatedStringHandlerArgumentName, "InterpolatedStringHandlerArgumentAttribute(new string[] { null })").WithLocation(8, 34) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_NullConstant_FromMetadata_01() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument({ Nothing })> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_NullConstant_FromMetadata_02() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument({ Nothing, ""i"" })> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_NullConstant_FromMetadata_03() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(i As Integer, <InterpolatedStringHandlerArgument(CStr(Nothing))> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M(1, $"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,8): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M(1, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_ThisOnStaticMethod() { var code = @" using System.Runtime.CompilerServices; C.M($""""); class C { public static void M([InterpolatedStringHandlerArgumentAttribute("""")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 5), // (8,27): error CS8944: 'C.M(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument. // public static void M([InterpolatedStringHandlerArgumentAttribute("")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute("""")").WithArguments("C.M(CustomHandler)").WithLocation(8, 27) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"{""""}")] [InlineData(@"""""")] public void InterpolatedStringHandlerArgumentAttributeError_ThisOnStaticMethod_FromMetadata(string arg) { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(<InterpolatedStringHandlerArgument(" + arg + @")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C.M($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,5): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 5), // (1,5): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 5) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_ThisOnConstructor() { var code = @" using System.Runtime.CompilerServices; _ = new C($""""); class C { public C([InterpolatedStringHandlerArgumentAttribute("""")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (4,11): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // _ = new C($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 11), // (8,15): error CS8944: 'C.C(CustomHandler)' is not an instance method, the receiver cannot be an interpolated string handler argument. // public C([InterpolatedStringHandlerArgumentAttribute("")] CustomHandler c) {} Diagnostic(ErrorCode.ERR_NotInstanceInvalidInterpolatedStringHandlerArgumentName, @"InterpolatedStringHandlerArgumentAttribute("""")").WithArguments("C.C(CustomHandler)").WithLocation(8, 15) ); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod(".ctor").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData(@"{""""}")] [InlineData(@"""""")] public void InterpolatedStringHandlerArgumentAttributeError_ThisOnConstructor_FromMetadata(string arg) { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Sub New(<InterpolatedStringHandlerArgument(" + arg + @")> c As CustomHandler) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"_ = new C($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,11): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // _ = new C($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 11), // (1,11): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // _ = new C($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 11), // (1,11): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // _ = new C($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 11) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod(".ctor").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerAttributeArgumentError_SubstitutedTypeSymbol() { var code = @" using System.Runtime.CompilerServices; C<CustomHandler>.M($""""); public class C<T> { public static void M([InterpolatedStringHandlerArgumentAttribute] T t) { } } "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, customHandler }); comp.VerifyDiagnostics( // (4,20): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C<CustomHandler>.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(4, 20), // (8,27): error CS8946: 'T' is not an interpolated string handler type. // public static void M([InterpolatedStringHandlerArgumentAttribute] T t) { } Diagnostic(ErrorCode.ERR_TypeIsNotAnInterpolatedStringHandlerType, "InterpolatedStringHandlerArgumentAttribute").WithArguments("T").WithLocation(8, 27) ); var c = comp.SourceModule.GlobalNamespace.GetTypeMember("C"); var handler = comp.SourceModule.GlobalNamespace.GetTypeMember("CustomHandler"); var substitutedC = c.WithTypeArguments(ImmutableArray.Create(TypeWithAnnotations.Create(handler))); var cParam = substitutedC.GetMethod("M").Parameters.Single(); Assert.IsType<SubstitutedParameterSymbol>(cParam); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_SubstitutedTypeSymbol_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C(Of T) Public Shared Sub M(<InterpolatedStringHandlerArgument()> c As T) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation(@"C<CustomHandler>.M($"""");", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics( // (1,20): error CS8949: The InterpolatedStringHandlerArgumentAttribute applied to parameter 'CustomHandler' is malformed and cannot be interpreted. Construct an instance of 'CustomHandler' manually. // C<CustomHandler>.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentAttributeMalformed, @"$""""").WithArguments("CustomHandler", "CustomHandler").WithLocation(1, 20), // (1,20): error CS1729: 'CustomHandler' does not contain a constructor that takes 2 arguments // C<CustomHandler>.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "2").WithLocation(1, 20), // (1,20): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C<CustomHandler>.M($""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 20) ); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C`1").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); Assert.True(cParam.HasInterpolatedStringHandlerArgumentError); } [Theory] [InlineData("")] [InlineData(", out bool success")] public void InterpolatedStringHandlerArgumentAttributeWarn_ParameterAfterHandler(string extraConstructorArg) { var code = @" using System; using System.Runtime.CompilerServices; public class C { public static void M([InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c, int i) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var goodCode = @" int i = 10; C.M(i: i, c: $""text""); "; var comp = CreateCompilation(new[] { code, goodCode, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate, expectedOutput: @" i:10 literal:text "); verifier.VerifyDiagnostics( // (6,27): warning CS8947: Parameter i occurs after CustomHandler 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. // public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, int i) => Console.WriteLine(c.ToString()); Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(6, 27) ); verifyIL(verifier); var badCode = @"C.M($"""", 1);"; comp = CreateCompilation(new[] { code, badCode, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (1,10): error CS8950: Parameter 'i' is an argument to the interpolated string handler conversion on parameter 'c', but is specified after the interpolated string constant. Reorder the arguments to move 'i' before 'c'. // C.M($"", 1); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentLocatedAfterInterpolatedString, "1").WithArguments("i", "c").WithLocation(1, 10), // (6,27): warning CS8947: Parameter i occurs after CustomHandler 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. // public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, int i) => Console.WriteLine(c.ToString()); Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(6, 27) ); static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.First(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(1, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); Assert.False(cParam.HasInterpolatedStringHandlerArgumentError); } void verifyIL(CompilationVerifier verifier) { verifier.VerifyIL("<top-level-statements-entry-point>", extraConstructorArg == "" ? @" { // Code size 36 (0x24) .maxstack 4 .locals init (int V_0, int V_1, CustomHandler V_2) IL_0000: ldc.i4.s 10 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: stloc.1 IL_0005: ldloca.s V_2 IL_0007: ldc.i4.4 IL_0008: ldc.i4.0 IL_0009: ldloc.0 IL_000a: call ""CustomHandler..ctor(int, int, int)"" IL_000f: ldloca.s V_2 IL_0011: ldstr ""text"" IL_0016: call ""bool CustomHandler.AppendLiteral(string)"" IL_001b: pop IL_001c: ldloc.2 IL_001d: ldloc.1 IL_001e: call ""void C.M(CustomHandler, int)"" IL_0023: ret } " : @" { // Code size 43 (0x2b) .maxstack 4 .locals init (int V_0, int V_1, CustomHandler V_2, bool V_3) IL_0000: ldc.i4.s 10 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: stloc.1 IL_0005: ldc.i4.4 IL_0006: ldc.i4.0 IL_0007: ldloc.0 IL_0008: ldloca.s V_3 IL_000a: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000f: stloc.2 IL_0010: ldloc.3 IL_0011: brfalse.s IL_0021 IL_0013: ldloca.s V_2 IL_0015: ldstr ""text"" IL_001a: call ""bool CustomHandler.AppendLiteral(string)"" IL_001f: br.s IL_0022 IL_0021: ldc.i4.0 IL_0022: pop IL_0023: ldloc.2 IL_0024: ldloc.1 IL_0025: call ""void C.M(CustomHandler, int)"" IL_002a: ret } "); } } [Fact] public void InterpolatedStringHandlerArgumentAttributeWarn_ParameterAfterHandler_FromMetadata() { var vbCode = @" Imports System.Runtime.CompilerServices Public Class C Public Shared Sub M(<InterpolatedStringHandlerArgument(""i"")> c As CustomHandler, i As Integer) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vbCode, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var comp = CreateCompilation("", references: new[] { vbComp.EmitToImageReference() }); comp.VerifyEmitDiagnostics(); var customHandler = comp.GetTypeByMetadataName("CustomHandler"); Assert.True(customHandler.IsInterpolatedStringHandlerType); var cParam = comp.GetTypeByMetadataName("C").GetMethod("M").Parameters.First(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(1, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); Assert.False(cParam.HasInterpolatedStringHandlerArgumentError); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_OptionalNotSpecifiedAtCallsite() { var code = @" using System.Runtime.CompilerServices; C.M($""""); public class C { public static void M([InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c, int i = 0) { } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount) { } } "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, customHandler }); comp.VerifyDiagnostics( // (4,5): error CS8951: Parameter 'i' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter 'c'. Specify the value of 'i' before 'c'. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified, @"$""""").WithArguments("i", "c").WithLocation(4, 5), // (8,27): warning CS8947: Parameter i occurs after CustomHandler 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. // public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, params int[] i) { } Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(8, 27) ); } [Fact] public void InterpolatedStringHandlerArgumentAttributeError_ParamsNotSpecifiedAtCallsite() { var code = @" using System.Runtime.CompilerServices; C.M($""""); public class C { public static void M([InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c, params int[] i) { } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int[] i) : this(literalLength, formattedCount) { } } "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, customHandler }); comp.VerifyDiagnostics( // (4,5): error CS8951: Parameter 'i' is not explicitly provided, but is used as an argument to the interpolated string handler conversion on parameter 'c'. Specify the value of 'i' before 'c'. // C.M($""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerArgumentOptionalNotSpecified, @"$""""").WithArguments("i", "c").WithLocation(4, 5), // (8,27): warning CS8947: Parameter i occurs after CustomHandler 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. // public static void M([InterpolatedStringHandlerArgumentAttribute("i")] CustomHandler c, params int[] i) { } Diagnostic(ErrorCode.WRN_ParameterOccursAfterInterpolatedStringHandlerParameter, @"InterpolatedStringHandlerArgumentAttribute(""i"")").WithArguments("i", "CustomHandler").WithLocation(8, 27) ); } [Fact] public void InterpolatedStringHandlerArgumentAttribute_MissingConstructor() { var code = @" using System.Runtime.CompilerServices; public class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); // https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback. var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate).VerifyDiagnostics(); CreateCompilation(@"C.M(1, $"""");", new[] { comp.ToMetadataReference() }).VerifyDiagnostics( // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 4 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "4").WithLocation(1, 8) ); static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); Assert.False(cParam.HasInterpolatedStringHandlerArgumentError); } } [Fact] public void InterpolatedStringHandlerArgumentAttribute_InaccessibleConstructor_01() { var code = @" using System.Runtime.CompilerServices; public class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) {} } public partial struct CustomHandler { private CustomHandler(int literalLength, int formattedCount, int i) : this() {} static void InCustomHandler() { C.M(1, $""""); } } "; var executableCode = @"C.M(1, $"""");"; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (1,8): error CS0122: 'CustomHandler.CustomHandler(int, int, int)' is inaccessible due to its protection level // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadAccess, @"$""""").WithArguments("CustomHandler.CustomHandler(int, int, int)").WithLocation(1, 8) ); var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); // https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback. CompileAndVerify(dependency, symbolValidator: validate, sourceSymbolValidator: validate).VerifyDiagnostics(); comp = CreateCompilation(executableCode, new[] { dependency.EmitToImageReference() }); comp.VerifyDiagnostics( // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 4 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "4").WithLocation(1, 8), // (1,8): error CS1729: 'CustomHandler' does not contain a constructor that takes 3 arguments // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"$""""").WithArguments("CustomHandler", "3").WithLocation(1, 8) ); comp = CreateCompilation(executableCode, new[] { dependency.ToMetadataReference() }); comp.VerifyDiagnostics( // (1,8): error CS0122: 'CustomHandler.CustomHandler(int, int, int)' is inaccessible due to its protection level // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadAccess, @"$""""").WithArguments("CustomHandler.CustomHandler(int, int, int)").WithLocation(1, 8) ); static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); } } private void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes(string mRef, string customHandlerRef, params DiagnosticDescription[] expectedDiagnostics) { var code = @" using System.Runtime.CompilerServices; int i = 0; C.M(" + mRef + @" i, $""""); public class C { public static void M(" + mRef + @" int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) { " + (mRef == "out" ? "i = 0;" : "") + @" } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, " + customHandlerRef + @" int i) : this() { " + (customHandlerRef == "out" ? "i = 0;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics(expectedDiagnostics); var cParam = comp.SourceModule.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); } [Fact] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_RefNone() { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("ref", "", // (5,9): error CS1615: Argument 3 may not be passed with the 'ref' keyword // C.M(ref i, $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "ref").WithLocation(5, 9)); } [Fact] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_RefOut() { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("ref", "out", // (5,9): error CS1620: Argument 3 must be passed with the 'out' keyword // C.M(ref i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "out").WithLocation(5, 9)); } [Fact] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_RefIn() { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("ref", "in", // (5,9): error CS1615: Argument 3 may not be passed with the 'ref' keyword // C.M(ref i, $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "ref").WithLocation(5, 9)); } [Fact] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_InNone() { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("in", "", // (5,8): error CS1615: Argument 3 may not be passed with the 'in' keyword // C.M(in i, $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "in").WithLocation(5, 8)); } [Fact] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_InOut() { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("in", "out", // (5,8): error CS1620: Argument 3 must be passed with the 'out' keyword // C.M(in i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "out").WithLocation(5, 8)); } [Fact] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_InRef() { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("in", "ref", // (5,8): error CS1620: Argument 3 must be passed with the 'ref' keyword // C.M(in i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "ref").WithLocation(5, 8)); } [Fact] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_OutNone() { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("out", "", // (5,9): error CS1615: Argument 3 may not be passed with the 'out' keyword // C.M(out i, $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("3", "out").WithLocation(5, 9)); } [Fact] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_OutRef() { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("out", "ref", // (5,9): error CS1620: Argument 3 must be passed with the 'ref' keyword // C.M(out i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "ref").WithLocation(5, 9)); } [Fact] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_NoneRef() { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("", "ref", // (5,6): error CS1620: Argument 3 must be passed with the 'ref' keyword // C.M( i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "ref").WithLocation(5, 6)); } [Fact] public void InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes_NoneOut() { InterpolatedStringHandlerArgumentAttribute_MismatchedRefTypes("", "out", // (5,6): error CS1620: Argument 3 must be passed with the 'out' keyword // C.M( i, $""); Diagnostic(ErrorCode.ERR_BadArgRef, "i").WithArguments("3", "out").WithLocation(5, 6)); } [Theory] [InlineData("")] [InlineData(", out bool success")] public void InterpolatedStringHandlerArgumentAttribute_MismatchedType(string extraConstructorArg) { var code = @" using System.Runtime.CompilerServices; public class C { public static void M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) {} } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s" + extraConstructorArg + @") : this() { " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var executableCode = @"C.M(1, $"""");"; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var expectedDiagnostics = extraConstructorArg == "" ? new DiagnosticDescription[] { // (1,5): error CS1503: Argument 3: cannot convert from 'int' to 'string' // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("3", "int", "string").WithLocation(1, 5) } : new DiagnosticDescription[] { // (1,5): error CS1503: Argument 3: cannot convert from 'int' to 'string' // C.M(1, $""); Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("3", "int", "string").WithLocation(1, 5), // (1,8): error CS7036: There is no argument given that corresponds to the required formal parameter 'success' of 'CustomHandler.CustomHandler(int, int, string, out bool)' // C.M(1, $""); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, @"$""""").WithArguments("success", "CustomHandler.CustomHandler(int, int, string, out bool)").WithLocation(1, 8) }; var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics(expectedDiagnostics); // https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback. var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); CompileAndVerify(dependency, symbolValidator: validate, sourceSymbolValidator: validate).VerifyDiagnostics(); foreach (var d in new[] { dependency.EmitToImageReference(), dependency.ToMetadataReference() }) { comp = CreateCompilation(executableCode, new[] { d }); comp.VerifyDiagnostics(expectedDiagnostics); } static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); } } [Theory] [InlineData("")] [InlineData(", out bool success")] public void InterpolatedStringHandlerArgumentAttribute_SingleArg(string extraConstructorArg) { var code = @" using System.Runtime.CompilerServices; public class C { public static string M(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")] CustomHandler c) => c.ToString(); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var executableCode = @" using System; int i = 10; Console.WriteLine(C.M(i, $""2"")); "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" i:10 literal:2"); verifier.VerifyDiagnostics(); verifyIL(extraConstructorArg, verifier); var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); foreach (var d in new[] { dependency.EmitToImageReference(), dependency.ToMetadataReference() }) { verifier = CompileAndVerify(executableCode, new[] { d }, expectedOutput: @" i:10 literal:2"); verifier.VerifyDiagnostics(); verifyIL(extraConstructorArg, verifier); } static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(0, cParam.InterpolatedStringHandlerArgumentIndexes.Single()); } static void verifyIL(string extraConstructorArg, CompilationVerifier verifier) { verifier.VerifyIL("<top-level-statements-entry-point>", extraConstructorArg == "" ? @" { // Code size 39 (0x27) .maxstack 5 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.s 10 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldloca.s V_1 IL_0006: ldc.i4.1 IL_0007: ldc.i4.0 IL_0008: ldloc.0 IL_0009: call ""CustomHandler..ctor(int, int, int)"" IL_000e: ldloca.s V_1 IL_0010: ldstr ""2"" IL_0015: call ""bool CustomHandler.AppendLiteral(string)"" IL_001a: pop IL_001b: ldloc.1 IL_001c: call ""string C.M(int, CustomHandler)"" IL_0021: call ""void System.Console.WriteLine(string)"" IL_0026: ret } " : @" { // Code size 46 (0x2e) .maxstack 5 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: ldc.i4.s 10 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldc.i4.1 IL_0005: ldc.i4.0 IL_0006: ldloc.0 IL_0007: ldloca.s V_2 IL_0009: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000e: stloc.1 IL_000f: ldloc.2 IL_0010: brfalse.s IL_0020 IL_0012: ldloca.s V_1 IL_0014: ldstr ""2"" IL_0019: call ""bool CustomHandler.AppendLiteral(string)"" IL_001e: br.s IL_0021 IL_0020: ldc.i4.0 IL_0021: pop IL_0022: ldloc.1 IL_0023: call ""string C.M(int, CustomHandler)"" IL_0028: call ""void System.Console.WriteLine(string)"" IL_002d: ret } "); } } [Theory] [InlineData("")] [InlineData(", out bool success")] public void InterpolatedStringHandlerArgumentAttribute_MultipleArgs(string extraConstructorArg) { var code = @" using System; using System.Runtime.CompilerServices; public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i, string s" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); _builder.AppendLine(""s:"" + s); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var executableCode = @" int i = 10; string s = ""arg""; C.M(i, s, $""literal""); "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, executableCode, InterpolatedStringHandlerArgumentAttribute, handler }); string expectedOutput = @" i:10 s:arg literal:literal "; var verifier = base.CompileAndVerify((Compilation)comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: expectedOutput); verifier.VerifyDiagnostics(); verifyIL(extraConstructorArg, verifier); var dependency = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); foreach (var d in new[] { dependency.EmitToImageReference(), dependency.ToMetadataReference() }) { verifier = CompileAndVerify(executableCode, new[] { d }, expectedOutput: expectedOutput); verifier.VerifyDiagnostics(); verifyIL(extraConstructorArg, verifier); } static void validator(ModuleSymbol verifier) { var cParam = verifier.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } static void verifyIL(string extraConstructorArg, CompilationVerifier verifier) { verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 44 (0x2c) .maxstack 7 .locals init (string V_0, //s int V_1, string V_2, CustomHandler V_3) IL_0000: ldc.i4.s 10 IL_0002: ldstr ""arg"" IL_0007: stloc.0 IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldloc.0 IL_000b: stloc.2 IL_000c: ldloc.2 IL_000d: ldloca.s V_3 IL_000f: ldc.i4.7 IL_0010: ldc.i4.0 IL_0011: ldloc.1 IL_0012: ldloc.2 IL_0013: call ""CustomHandler..ctor(int, int, int, string)"" IL_0018: ldloca.s V_3 IL_001a: ldstr ""literal"" IL_001f: call ""bool CustomHandler.AppendLiteral(string)"" IL_0024: pop IL_0025: ldloc.3 IL_0026: call ""void C.M(int, string, CustomHandler)"" IL_002b: ret } " : @" { // Code size 52 (0x34) .maxstack 7 .locals init (string V_0, //s int V_1, string V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.s 10 IL_0002: ldstr ""arg"" IL_0007: stloc.0 IL_0008: stloc.1 IL_0009: ldloc.1 IL_000a: ldloc.0 IL_000b: stloc.2 IL_000c: ldloc.2 IL_000d: ldc.i4.7 IL_000e: ldc.i4.0 IL_000f: ldloc.1 IL_0010: ldloc.2 IL_0011: ldloca.s V_4 IL_0013: newobj ""CustomHandler..ctor(int, int, int, string, out bool)"" IL_0018: stloc.3 IL_0019: ldloc.s V_4 IL_001b: brfalse.s IL_002b IL_001d: ldloca.s V_3 IL_001f: ldstr ""literal"" IL_0024: call ""bool CustomHandler.AppendLiteral(string)"" IL_0029: br.s IL_002c IL_002b: ldc.i4.0 IL_002c: pop IL_002d: ldloc.3 IL_002e: call ""void C.M(int, string, CustomHandler)"" IL_0033: ret } "); } } [Theory] [InlineData("")] [InlineData(", out bool success")] public void InterpolatedStringHandlerArgumentAttribute_RefKindsMatch(string extraConstructorArg) { var code = @" using System; using System.Runtime.CompilerServices; int i = 1; string s = null; object o; C.M(i, ref s, out o, $""literal""); Console.WriteLine(s); Console.WriteLine(o); public class C { public static void M(in int i, ref string s, out object o, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"", ""o"")] CustomHandler c) { Console.WriteLine(s); o = ""o in M""; s = ""s in M""; Console.Write(c.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, in int i, ref string s, out object o" + extraConstructorArg + @") : this(literalLength, formattedCount) { o = null; s = ""s in constructor""; _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" s in constructor i:1 literal:literal s in M o in M "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 67 (0x43) .maxstack 8 .locals init (int V_0, //i string V_1, //s object V_2, //o int& V_3, string& V_4, object& V_5, CustomHandler V_6) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldnull IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: stloc.3 IL_0007: ldloc.3 IL_0008: ldloca.s V_1 IL_000a: stloc.s V_4 IL_000c: ldloc.s V_4 IL_000e: ldloca.s V_2 IL_0010: stloc.s V_5 IL_0012: ldloc.s V_5 IL_0014: ldc.i4.7 IL_0015: ldc.i4.0 IL_0016: ldloc.3 IL_0017: ldloc.s V_4 IL_0019: ldloc.s V_5 IL_001b: newobj ""CustomHandler..ctor(int, int, in int, ref string, out object)"" IL_0020: stloc.s V_6 IL_0022: ldloca.s V_6 IL_0024: ldstr ""literal"" IL_0029: call ""bool CustomHandler.AppendLiteral(string)"" IL_002e: pop IL_002f: ldloc.s V_6 IL_0031: call ""void C.M(in int, ref string, out object, CustomHandler)"" IL_0036: ldloc.1 IL_0037: call ""void System.Console.WriteLine(string)"" IL_003c: ldloc.2 IL_003d: call ""void System.Console.WriteLine(object)"" IL_0042: ret } " : @" { // Code size 76 (0x4c) .maxstack 9 .locals init (int V_0, //i string V_1, //s object V_2, //o int& V_3, string& V_4, object& V_5, CustomHandler V_6, bool V_7) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldnull IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: stloc.3 IL_0007: ldloc.3 IL_0008: ldloca.s V_1 IL_000a: stloc.s V_4 IL_000c: ldloc.s V_4 IL_000e: ldloca.s V_2 IL_0010: stloc.s V_5 IL_0012: ldloc.s V_5 IL_0014: ldc.i4.7 IL_0015: ldc.i4.0 IL_0016: ldloc.3 IL_0017: ldloc.s V_4 IL_0019: ldloc.s V_5 IL_001b: ldloca.s V_7 IL_001d: newobj ""CustomHandler..ctor(int, int, in int, ref string, out object, out bool)"" IL_0022: stloc.s V_6 IL_0024: ldloc.s V_7 IL_0026: brfalse.s IL_0036 IL_0028: ldloca.s V_6 IL_002a: ldstr ""literal"" IL_002f: call ""bool CustomHandler.AppendLiteral(string)"" IL_0034: br.s IL_0037 IL_0036: ldc.i4.0 IL_0037: pop IL_0038: ldloc.s V_6 IL_003a: call ""void C.M(in int, ref string, out object, CustomHandler)"" IL_003f: ldloc.1 IL_0040: call ""void System.Console.WriteLine(string)"" IL_0045: ldloc.2 IL_0046: call ""void System.Console.WriteLine(object)"" IL_004b: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(3).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 1, 2 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [InlineData("")] [InlineData(", out bool success")] public void InterpolatedStringHandlerArgumentAttribute_ReorderedAttributePositions(string extraConstructorArg) { var code = @" using System; using System.Runtime.CompilerServices; C.M(GetInt(), GetString(), $""literal""); int GetInt() { Console.WriteLine(""GetInt""); return 10; } string GetString() { Console.WriteLine(""GetString""); return ""str""; } public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""s"", ""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s, int i" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""s:"" + s); _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" GetInt GetString s:str i:10 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 45 (0x2d) .maxstack 7 .locals init (string V_0, int V_1, CustomHandler V_2) IL_0000: call ""int <Program>$.<<Main>$>g__GetInt|0_0()"" IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: call ""string <Program>$.<<Main>$>g__GetString|0_1()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: ldloca.s V_2 IL_0010: ldc.i4.7 IL_0011: ldc.i4.0 IL_0012: ldloc.0 IL_0013: ldloc.1 IL_0014: call ""CustomHandler..ctor(int, int, string, int)"" IL_0019: ldloca.s V_2 IL_001b: ldstr ""literal"" IL_0020: call ""bool CustomHandler.AppendLiteral(string)"" IL_0025: pop IL_0026: ldloc.2 IL_0027: call ""void C.M(int, string, CustomHandler)"" IL_002c: ret } " : @" { // Code size 52 (0x34) .maxstack 7 .locals init (string V_0, int V_1, CustomHandler V_2, bool V_3) IL_0000: call ""int <Program>$.<<Main>$>g__GetInt|0_0()"" IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: call ""string <Program>$.<<Main>$>g__GetString|0_1()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: ldc.i4.7 IL_000f: ldc.i4.0 IL_0010: ldloc.0 IL_0011: ldloc.1 IL_0012: ldloca.s V_3 IL_0014: newobj ""CustomHandler..ctor(int, int, string, int, out bool)"" IL_0019: stloc.2 IL_001a: ldloc.3 IL_001b: brfalse.s IL_002b IL_001d: ldloca.s V_2 IL_001f: ldstr ""literal"" IL_0024: call ""bool CustomHandler.AppendLiteral(string)"" IL_0029: br.s IL_002c IL_002b: ldc.i4.0 IL_002c: pop IL_002d: ldloc.2 IL_002e: call ""void C.M(int, string, CustomHandler)"" IL_0033: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 1, 0 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [InlineData("")] [InlineData(", out bool success")] public void InterpolatedStringHandlerArgumentAttribute_ParametersReordered(string extraConstructorArg) { var code = @" using System; using System.Runtime.CompilerServices; GetC().M(s: GetString(), i: GetInt(), c: $""literal""); C GetC() { Console.WriteLine(""GetC""); return new C { Field = 5 }; } int GetInt() { Console.WriteLine(""GetInt""); return 10; } string GetString() { Console.WriteLine(""GetString""); return ""str""; } public class C { public int Field; public void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""s"", """", ""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s, C c, int i" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""s:"" + s); _builder.AppendLine(""c.Field:"" + c.Field.ToString()); _builder.AppendLine(""i:"" + i.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" GetC GetString GetInt s:str c.Field:5 i:10 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 56 (0x38) .maxstack 9 .locals init (string V_0, C V_1, int V_2, string V_3, CustomHandler V_4) IL_0000: call ""C <Program>$.<<Main>$>g__GetC|0_0()"" IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: call ""string <Program>$.<<Main>$>g__GetString|0_2()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: stloc.3 IL_000f: call ""int <Program>$.<<Main>$>g__GetInt|0_1()"" IL_0014: stloc.2 IL_0015: ldloc.2 IL_0016: ldloc.3 IL_0017: ldloca.s V_4 IL_0019: ldc.i4.7 IL_001a: ldc.i4.0 IL_001b: ldloc.0 IL_001c: ldloc.1 IL_001d: ldloc.2 IL_001e: call ""CustomHandler..ctor(int, int, string, C, int)"" IL_0023: ldloca.s V_4 IL_0025: ldstr ""literal"" IL_002a: call ""bool CustomHandler.AppendLiteral(string)"" IL_002f: pop IL_0030: ldloc.s V_4 IL_0032: callvirt ""void C.M(int, string, CustomHandler)"" IL_0037: ret } " : @" { // Code size 65 (0x41) .maxstack 9 .locals init (string V_0, C V_1, int V_2, string V_3, CustomHandler V_4, bool V_5) IL_0000: call ""C <Program>$.<<Main>$>g__GetC|0_0()"" IL_0005: stloc.1 IL_0006: ldloc.1 IL_0007: call ""string <Program>$.<<Main>$>g__GetString|0_2()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: stloc.3 IL_000f: call ""int <Program>$.<<Main>$>g__GetInt|0_1()"" IL_0014: stloc.2 IL_0015: ldloc.2 IL_0016: ldloc.3 IL_0017: ldc.i4.7 IL_0018: ldc.i4.0 IL_0019: ldloc.0 IL_001a: ldloc.1 IL_001b: ldloc.2 IL_001c: ldloca.s V_5 IL_001e: newobj ""CustomHandler..ctor(int, int, string, C, int, out bool)"" IL_0023: stloc.s V_4 IL_0025: ldloc.s V_5 IL_0027: brfalse.s IL_0037 IL_0029: ldloca.s V_4 IL_002b: ldstr ""literal"" IL_0030: call ""bool CustomHandler.AppendLiteral(string)"" IL_0035: br.s IL_0038 IL_0037: ldc.i4.0 IL_0038: pop IL_0039: ldloc.s V_4 IL_003b: callvirt ""void C.M(int, string, CustomHandler)"" IL_0040: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 1, -1, 0 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [InlineData("")] [InlineData(", out bool success")] public void InterpolatedStringHandlerArgumentAttribute_Duplicated(string extraConstructorArg) { var code = @" using System; using System.Runtime.CompilerServices; C.M(GetInt(), """", $""literal""); int GetInt() { Console.WriteLine(""GetInt""); return 10; } public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""i"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i1, int i2" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i1:"" + i1.ToString()); _builder.AppendLine(""i2:"" + i2.ToString()); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" GetInt i1:10 i2:10 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 43 (0x2b) .maxstack 7 .locals init (int V_0, CustomHandler V_1) IL_0000: call ""int <Program>$.<<Main>$>g__GetInt|0_0()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr """" IL_000c: ldloca.s V_1 IL_000e: ldc.i4.7 IL_000f: ldc.i4.0 IL_0010: ldloc.0 IL_0011: ldloc.0 IL_0012: call ""CustomHandler..ctor(int, int, int, int)"" IL_0017: ldloca.s V_1 IL_0019: ldstr ""literal"" IL_001e: call ""bool CustomHandler.AppendLiteral(string)"" IL_0023: pop IL_0024: ldloc.1 IL_0025: call ""void C.M(int, string, CustomHandler)"" IL_002a: ret } " : @" { // Code size 50 (0x32) .maxstack 7 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: call ""int <Program>$.<<Main>$>g__GetInt|0_0()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr """" IL_000c: ldc.i4.7 IL_000d: ldc.i4.0 IL_000e: ldloc.0 IL_000f: ldloc.0 IL_0010: ldloca.s V_2 IL_0012: newobj ""CustomHandler..ctor(int, int, int, int, out bool)"" IL_0017: stloc.1 IL_0018: ldloc.2 IL_0019: brfalse.s IL_0029 IL_001b: ldloca.s V_1 IL_001d: ldstr ""literal"" IL_0022: call ""bool CustomHandler.AppendLiteral(string)"" IL_0027: br.s IL_002a IL_0029: ldc.i4.0 IL_002a: pop IL_002b: ldloc.1 IL_002c: call ""void C.M(int, string, CustomHandler)"" IL_0031: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 0 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [InlineData("")] [InlineData(", out bool success")] public void InterpolatedStringHandlerArgumentAttribute_EmptyWithMatchingConstructor(string extraConstructorArg) { var code = @" using System; using System.Runtime.CompilerServices; C.M(1, """", $""""); public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute()] CustomHandler c) => Console.WriteLine(c.ToString()); } [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount" + extraConstructorArg + @") { " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: "CustomHandler").VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 19 (0x13) .maxstack 4 IL_0000: ldc.i4.1 IL_0001: ldstr """" IL_0006: ldc.i4.0 IL_0007: ldc.i4.0 IL_0008: newobj ""CustomHandler..ctor(int, int)"" IL_000d: call ""void C.M(int, string, CustomHandler)"" IL_0012: ret } " : @" { // Code size 21 (0x15) .maxstack 5 .locals init (bool V_0) IL_0000: ldc.i4.1 IL_0001: ldstr """" IL_0006: ldc.i4.0 IL_0007: ldc.i4.0 IL_0008: ldloca.s V_0 IL_000a: newobj ""CustomHandler..ctor(int, int, out bool)"" IL_000f: call ""void C.M(int, string, CustomHandler)"" IL_0014: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [InlineData("")] [InlineData(", out bool success")] public void InterpolatedStringHandlerArgumentAttribute_EmptyWithoutMatchingConstructor(string extraConstructorArg) { var code = @" using System.Runtime.CompilerServices; public class C { public static void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute()] CustomHandler c) { } } [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i" + extraConstructorArg + @") { " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }); // https://github.com/dotnet/roslyn/issues/53981 tracks warning here in the future, with user feedback. CompileAndVerify(comp, symbolValidator: validate, sourceSymbolValidator: validate).VerifyDiagnostics(); CreateCompilation(@"C.M(1, """", $"""");", new[] { comp.EmitToImageReference() }).VerifyDiagnostics( (extraConstructorArg == "") ? new[] { // (1,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'CustomHandler.CustomHandler(int, int, int)' // C.M(1, "", $""); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, @"$""""").WithArguments("i", "CustomHandler.CustomHandler(int, int, int)").WithLocation(1, 12), // (1,12): error CS1615: Argument 3 may not be passed with the 'out' keyword // C.M(1, "", $""); Diagnostic(ErrorCode.ERR_BadArgExtraRef, @"$""""").WithArguments("3", "out").WithLocation(1, 12) } : new[] { // (1,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'i' of 'CustomHandler.CustomHandler(int, int, int, out bool)' // C.M(1, "", $""); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, @"$""""").WithArguments("i", "CustomHandler.CustomHandler(int, int, int, out bool)").WithLocation(1, 12), // (1,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'success' of 'CustomHandler.CustomHandler(int, int, int, out bool)' // C.M(1, "", $""); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, @"$""""").WithArguments("success", "CustomHandler.CustomHandler(int, int, int, out bool)").WithLocation(1, 12) } ); static void validate(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Empty(cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [InlineData("")] [InlineData(", out bool success")] public void InterpolatedStringHandlerArgumentAttribute_OnIndexerRvalue(string extraConstructorArg) { var code = @" using System; using System.Runtime.CompilerServices; var c = new C(); Console.WriteLine(c[10, ""str"", $""literal""]); public class C { public string this[int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"")] CustomHandler c] { get => c.ToString(); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i1, string s" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i1:"" + i1.ToString()); _builder.AppendLine(""s:"" + s); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" i1:10 s:str literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 52 (0x34) .maxstack 8 .locals init (int V_0, string V_1, CustomHandler V_2) IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.s 10 IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""str"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldloca.s V_2 IL_0012: ldc.i4.7 IL_0013: ldc.i4.0 IL_0014: ldloc.0 IL_0015: ldloc.1 IL_0016: call ""CustomHandler..ctor(int, int, int, string)"" IL_001b: ldloca.s V_2 IL_001d: ldstr ""literal"" IL_0022: call ""bool CustomHandler.AppendLiteral(string)"" IL_0027: pop IL_0028: ldloc.2 IL_0029: callvirt ""string C.this[int, string, CustomHandler].get"" IL_002e: call ""void System.Console.WriteLine(string)"" IL_0033: ret } " : @" { // Code size 59 (0x3b) .maxstack 8 .locals init (int V_0, string V_1, CustomHandler V_2, bool V_3) IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.s 10 IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""str"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldc.i4.7 IL_0011: ldc.i4.0 IL_0012: ldloc.0 IL_0013: ldloc.1 IL_0014: ldloca.s V_3 IL_0016: newobj ""CustomHandler..ctor(int, int, int, string, out bool)"" IL_001b: stloc.2 IL_001c: ldloc.3 IL_001d: brfalse.s IL_002d IL_001f: ldloca.s V_2 IL_0021: ldstr ""literal"" IL_0026: call ""bool CustomHandler.AppendLiteral(string)"" IL_002b: br.s IL_002e IL_002d: ldc.i4.0 IL_002e: pop IL_002f: ldloc.2 IL_0030: callvirt ""string C.this[int, string, CustomHandler].get"" IL_0035: call ""void System.Console.WriteLine(string)"" IL_003a: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetIndexer<PropertySymbol>("Item").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [InlineData("")] [InlineData(", out bool success")] public void InterpolatedStringHandlerArgumentAttribute_OnIndexerLvalue(string extraConstructorArg) { var code = @" using System; using System.Runtime.CompilerServices; var c = new C(); c[10, ""str"", $""literal""] = """"; public class C { public string this[int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", ""s"")] CustomHandler c] { set => Console.WriteLine(c.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i1, string s" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i1:"" + i1.ToString()); _builder.AppendLine(""s:"" + s); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" i1:10 s:str literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 52 (0x34) .maxstack 8 .locals init (int V_0, string V_1, CustomHandler V_2) IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.s 10 IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""str"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldloca.s V_2 IL_0012: ldc.i4.7 IL_0013: ldc.i4.0 IL_0014: ldloc.0 IL_0015: ldloc.1 IL_0016: call ""CustomHandler..ctor(int, int, int, string)"" IL_001b: ldloca.s V_2 IL_001d: ldstr ""literal"" IL_0022: call ""bool CustomHandler.AppendLiteral(string)"" IL_0027: pop IL_0028: ldloc.2 IL_0029: ldstr """" IL_002e: callvirt ""void C.this[int, string, CustomHandler].set"" IL_0033: ret } " : @" { // Code size 59 (0x3b) .maxstack 8 .locals init (int V_0, string V_1, CustomHandler V_2, bool V_3) IL_0000: newobj ""C..ctor()"" IL_0005: ldc.i4.s 10 IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldstr ""str"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldc.i4.7 IL_0011: ldc.i4.0 IL_0012: ldloc.0 IL_0013: ldloc.1 IL_0014: ldloca.s V_3 IL_0016: newobj ""CustomHandler..ctor(int, int, int, string, out bool)"" IL_001b: stloc.2 IL_001c: ldloc.3 IL_001d: brfalse.s IL_002d IL_001f: ldloca.s V_2 IL_0021: ldstr ""literal"" IL_0026: call ""bool CustomHandler.AppendLiteral(string)"" IL_002b: br.s IL_002e IL_002d: ldc.i4.0 IL_002e: pop IL_002f: ldloc.2 IL_0030: ldstr """" IL_0035: callvirt ""void C.this[int, string, CustomHandler].set"" IL_003a: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetIndexer<PropertySymbol>("Item").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [InlineData("")] [InlineData(", out bool success")] public void InterpolatedStringHandlerArgumentAttribute_ThisParameter(string extraConstructorArg) { var code = @" using System; using System.Runtime.CompilerServices; (new C(5)).M((int)10, ""str"", $""literal""); public class C { public int Prop { get; } public C(int i) => Prop = i; public void M(int i, string s, [InterpolatedStringHandlerArgumentAttribute(""i"", """", ""s"")] CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i1, C c, string s" + extraConstructorArg + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i1:"" + i1.ToString()); _builder.AppendLine(""c.Prop:"" + c.Prop.ToString()); _builder.AppendLine(""s:"" + s); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" i1:10 c.Prop:5 s:str literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 51 (0x33) .maxstack 9 .locals init (int V_0, C V_1, string V_2, CustomHandler V_3) IL_0000: ldc.i4.5 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.1 IL_0007: ldloc.1 IL_0008: ldc.i4.s 10 IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: ldstr ""str"" IL_0011: stloc.2 IL_0012: ldloc.2 IL_0013: ldloca.s V_3 IL_0015: ldc.i4.7 IL_0016: ldc.i4.0 IL_0017: ldloc.0 IL_0018: ldloc.1 IL_0019: ldloc.2 IL_001a: call ""CustomHandler..ctor(int, int, int, C, string)"" IL_001f: ldloca.s V_3 IL_0021: ldstr ""literal"" IL_0026: call ""bool CustomHandler.AppendLiteral(string)"" IL_002b: pop IL_002c: ldloc.3 IL_002d: callvirt ""void C.M(int, string, CustomHandler)"" IL_0032: ret } " : @" { // Code size 59 (0x3b) .maxstack 9 .locals init (int V_0, C V_1, string V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.5 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.1 IL_0007: ldloc.1 IL_0008: ldc.i4.s 10 IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: ldstr ""str"" IL_0011: stloc.2 IL_0012: ldloc.2 IL_0013: ldc.i4.7 IL_0014: ldc.i4.0 IL_0015: ldloc.0 IL_0016: ldloc.1 IL_0017: ldloc.2 IL_0018: ldloca.s V_4 IL_001a: newobj ""CustomHandler..ctor(int, int, int, C, string, out bool)"" IL_001f: stloc.3 IL_0020: ldloc.s V_4 IL_0022: brfalse.s IL_0032 IL_0024: ldloca.s V_3 IL_0026: ldstr ""literal"" IL_002b: call ""bool CustomHandler.AppendLiteral(string)"" IL_0030: br.s IL_0033 IL_0032: ldc.i4.0 IL_0033: pop IL_0034: ldloc.3 IL_0035: callvirt ""void C.M(int, string, CustomHandler)"" IL_003a: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(2).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0, -1, 1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Fact] public void InterpolatedStringHandlerArgumentAttribute_OnConstructor() { var code = @" using System; using System.Runtime.CompilerServices; _ = new C(5, $""literal""); public class C { public int Prop { get; } public C(int i, [InterpolatedStringHandlerArgumentAttribute(""i"")]CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int i) : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" i:5 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 34 (0x22) .maxstack 5 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.5 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldloca.s V_1 IL_0005: ldc.i4.7 IL_0006: ldc.i4.0 IL_0007: ldloc.0 IL_0008: call ""CustomHandler..ctor(int, int, int)"" IL_000d: ldloca.s V_1 IL_000f: ldstr ""literal"" IL_0014: call ""bool CustomHandler.AppendLiteral(string)"" IL_0019: pop IL_001a: ldloc.1 IL_001b: newobj ""C..ctor(int, CustomHandler)"" IL_0020: pop IL_0021: ret } "); } [Theory] [InlineData("")] [InlineData(", out bool success")] public void RefReturningMethodAsReceiver_Success(string extraConstructorArg) { var code = @" using System; using System.Runtime.CompilerServices; C c = new C(1); GetC(ref c).M($""literal""); Console.WriteLine(c.I); ref C GetC(ref C c) { Console.WriteLine(""GetC""); return ref c; } public class C { public int I; public C(int i) { I = i; } public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref C c" + extraConstructorArg + @") : this(literalLength, formattedCount) { c = new C(2); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, verify: ExecutionConditionUtil.IsWindowsDesktop ? Verification.Skipped : Verification.Passes, expectedOutput: @" GetC literal:literal 2 "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 57 (0x39) .maxstack 4 .locals init (C V_0, //c C& V_1, CustomHandler V_2) IL_0000: ldc.i4.1 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: call ""ref C <Program>$.<<Main>$>g__GetC|0_0(ref C)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldind.ref IL_0011: ldc.i4.7 IL_0012: ldc.i4.0 IL_0013: ldloc.1 IL_0014: newobj ""CustomHandler..ctor(int, int, ref C)"" IL_0019: stloc.2 IL_001a: ldloca.s V_2 IL_001c: ldstr ""literal"" IL_0021: call ""bool CustomHandler.AppendLiteral(string)"" IL_0026: pop IL_0027: ldloc.2 IL_0028: callvirt ""void C.M(CustomHandler)"" IL_002d: ldloc.0 IL_002e: ldfld ""int C.I"" IL_0033: call ""void System.Console.WriteLine(int)"" IL_0038: ret } " : @" { // Code size 65 (0x41) .maxstack 5 .locals init (C V_0, //c C& V_1, CustomHandler V_2, bool V_3) IL_0000: ldc.i4.1 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.0 IL_0007: ldloca.s V_0 IL_0009: call ""ref C <Program>$.<<Main>$>g__GetC|0_0(ref C)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: ldind.ref IL_0011: ldc.i4.7 IL_0012: ldc.i4.0 IL_0013: ldloc.1 IL_0014: ldloca.s V_3 IL_0016: newobj ""CustomHandler..ctor(int, int, ref C, out bool)"" IL_001b: stloc.2 IL_001c: ldloc.3 IL_001d: brfalse.s IL_002d IL_001f: ldloca.s V_2 IL_0021: ldstr ""literal"" IL_0026: call ""bool CustomHandler.AppendLiteral(string)"" IL_002b: br.s IL_002e IL_002d: ldc.i4.0 IL_002e: pop IL_002f: ldloc.2 IL_0030: callvirt ""void C.M(CustomHandler)"" IL_0035: ldloc.0 IL_0036: ldfld ""int C.I"" IL_003b: call ""void System.Console.WriteLine(int)"" IL_0040: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { -1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [InlineData("")] [InlineData(", out bool success")] public void RefReturningMethodAsReceiver_Success_StructReceiver(string extraConstructorArg) { var code = @" using System; using System.Runtime.CompilerServices; C c = new C(1); GetC(ref c).M($""literal""); Console.WriteLine(c.I); ref C GetC(ref C c) { Console.WriteLine(""GetC""); return ref c; } public struct C { public int I; public C(int i) { I = i; } public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref C c" + extraConstructorArg + @") : this(literalLength, formattedCount) { c = new C(2); " + (extraConstructorArg != "" ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, verify: ExecutionConditionUtil.IsWindowsDesktop ? Verification.Skipped : Verification.Passes, expectedOutput: @" GetC literal:literal 2 "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", (extraConstructorArg == "") ? @" { // Code size 57 (0x39) .maxstack 4 .locals init (C V_0, //c C& V_1, CustomHandler V_2) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: call ""C..ctor(int)"" IL_0008: ldloca.s V_0 IL_000a: call ""ref C <Program>$.<<Main>$>g__GetC|0_0(ref C)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.7 IL_0012: ldc.i4.0 IL_0013: ldloc.1 IL_0014: newobj ""CustomHandler..ctor(int, int, ref C)"" IL_0019: stloc.2 IL_001a: ldloca.s V_2 IL_001c: ldstr ""literal"" IL_0021: call ""bool CustomHandler.AppendLiteral(string)"" IL_0026: pop IL_0027: ldloc.2 IL_0028: call ""void C.M(CustomHandler)"" IL_002d: ldloc.0 IL_002e: ldfld ""int C.I"" IL_0033: call ""void System.Console.WriteLine(int)"" IL_0038: ret } " : @" { // Code size 65 (0x41) .maxstack 5 .locals init (C V_0, //c C& V_1, CustomHandler V_2, bool V_3) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.1 IL_0003: call ""C..ctor(int)"" IL_0008: ldloca.s V_0 IL_000a: call ""ref C <Program>$.<<Main>$>g__GetC|0_0(ref C)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.7 IL_0012: ldc.i4.0 IL_0013: ldloc.1 IL_0014: ldloca.s V_3 IL_0016: newobj ""CustomHandler..ctor(int, int, ref C, out bool)"" IL_001b: stloc.2 IL_001c: ldloc.3 IL_001d: brfalse.s IL_002d IL_001f: ldloca.s V_2 IL_0021: ldstr ""literal"" IL_0026: call ""bool CustomHandler.AppendLiteral(string)"" IL_002b: br.s IL_002e IL_002d: ldc.i4.0 IL_002e: pop IL_002f: ldloc.2 IL_0030: call ""void C.M(CustomHandler)"" IL_0035: ldloc.0 IL_0036: ldfld ""int C.I"" IL_003b: call ""void System.Console.WriteLine(int)"" IL_0040: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { -1 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [InlineData("ref readonly")] [InlineData("")] public void RefReturningMethodAsReceiver_MismatchedRefness_01(string refness) { var code = @" using System.Runtime.CompilerServices; C c = new C(1); GetC().M($""literal""); " + refness + @" C GetC() => throw null; public class C { public C(int i) { } public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) { } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref C c) : this(literalLength, formattedCount) { } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (5,10): error CS1620: Argument 3 must be passed with the 'ref' keyword // GetC().M($"literal"); Diagnostic(ErrorCode.ERR_BadArgRef, @"$""literal""").WithArguments("3", "ref").WithLocation(5, 10) ); } [Theory] [InlineData("in")] [InlineData("")] public void RefReturningMethodAsReceiver_MismatchedRefness_02(string refness) { var code = @" using System.Runtime.CompilerServices; C c = new C(1); GetC(ref c).M($""literal""); ref C GetC(ref C c) => ref c; public class C { public C(int i) { } public void M([InterpolatedStringHandlerArgument("""")]CustomHandler c) { } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount," + refness + @" C c) : this(literalLength, formattedCount) { } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (5,15): error CS1615: Argument 3 may not be passed with the 'ref' keyword // GetC(ref c).M($"literal"); Diagnostic(ErrorCode.ERR_BadArgExtraRef, @"$""literal""").WithArguments("3", "ref").WithLocation(5, 15) ); } [Fact] public void StructReceiver_Rvalue() { var code = @" using System; using System.Runtime.CompilerServices; S s1 = new S { I = 1 }; S s2 = new S { I = 2 }; s1.M(s2, $""""); public struct S { public int I; public void M(S s2, [InterpolatedStringHandlerArgument("""", ""s2"")]CustomHandler handler) { Console.WriteLine(""s1.I:"" + this.I.ToString()); Console.WriteLine(""s2.I:"" + s2.I.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, S s1, S s2) : this(literalLength, formattedCount) { s1.I = 3; s2.I = 4; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" s1.I:1 s2.I:2"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 56 (0x38) .maxstack 6 .locals init (S V_0, //s2 S V_1, S V_2) IL_0000: ldloca.s V_1 IL_0002: initobj ""S"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: stfld ""int S.I"" IL_0010: ldloc.1 IL_0011: ldloca.s V_1 IL_0013: initobj ""S"" IL_0019: ldloca.s V_1 IL_001b: ldc.i4.2 IL_001c: stfld ""int S.I"" IL_0021: ldloc.1 IL_0022: stloc.0 IL_0023: stloc.1 IL_0024: ldloca.s V_1 IL_0026: ldloc.0 IL_0027: stloc.2 IL_0028: ldloc.2 IL_0029: ldc.i4.0 IL_002a: ldc.i4.0 IL_002b: ldloc.1 IL_002c: ldloc.2 IL_002d: newobj ""CustomHandler..ctor(int, int, S, S)"" IL_0032: call ""void S.M(S, CustomHandler)"" IL_0037: ret } "); } [Fact] public void StructReceiver_Lvalue() { var code = @" using System; using System.Runtime.CompilerServices; S s1 = new S { I = 1 }; S s2 = new S { I = 2 }; s1.M(ref s2, $""""); public struct S { public int I; public void M(ref S s2, [InterpolatedStringHandlerArgument("""", ""s2"")]CustomHandler handler) { Console.WriteLine(""s1.I:"" + this.I.ToString()); Console.WriteLine(""s2.I:"" + s2.I.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref S s1, ref S s2) : this(literalLength, formattedCount) { s1.I = 3; s2.I = 4; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); comp.VerifyDiagnostics( // (8,14): error CS1620: Argument 3 must be passed with the 'ref' keyword // s1.M(ref s2, $""); Diagnostic(ErrorCode.ERR_BadArgRef, @"$""""").WithArguments("3", "ref").WithLocation(8, 14) ); } [Fact] public void StructParameter_ByVal() { var code = @" using System; using System.Runtime.CompilerServices; S s = new S { I = 1 }; S.M(s, $""""); public struct S { public int I; public static void M(S s, [InterpolatedStringHandlerArgument(""s"")]CustomHandler handler) { Console.WriteLine(""s.I:"" + s.I.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, S s) : this(literalLength, formattedCount) { s.I = 2; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @"s.I:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 33 (0x21) .maxstack 4 .locals init (S V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloca.s V_0 IL_000a: ldc.i4.1 IL_000b: stfld ""int S.I"" IL_0010: ldloc.0 IL_0011: stloc.0 IL_0012: ldloc.0 IL_0013: ldc.i4.0 IL_0014: ldc.i4.0 IL_0015: ldloc.0 IL_0016: newobj ""CustomHandler..ctor(int, int, S)"" IL_001b: call ""void S.M(S, CustomHandler)"" IL_0020: ret } "); } [Fact] public void StructParameter_ByRef() { var code = @" using System; using System.Runtime.CompilerServices; S s = new S { I = 1 }; S.M(ref s, $""""); public struct S { public int I; public static void M(ref S s, [InterpolatedStringHandlerArgument(""s"")]CustomHandler handler) { Console.WriteLine(""s.I:"" + s.I.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, ref S s) : this(literalLength, formattedCount) { s.I = 2; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @"s.I:2"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 36 (0x24) .maxstack 4 .locals init (S V_0, //s S V_1, S& V_2) IL_0000: ldloca.s V_1 IL_0002: initobj ""S"" IL_0008: ldloca.s V_1 IL_000a: ldc.i4.1 IL_000b: stfld ""int S.I"" IL_0010: ldloc.1 IL_0011: stloc.0 IL_0012: ldloca.s V_0 IL_0014: stloc.2 IL_0015: ldloc.2 IL_0016: ldc.i4.0 IL_0017: ldc.i4.0 IL_0018: ldloc.2 IL_0019: newobj ""CustomHandler..ctor(int, int, ref S)"" IL_001e: call ""void S.M(ref S, CustomHandler)"" IL_0023: ret } "); } [Theory] [CombinatorialData] public void SideEffects(bool useBoolReturns, bool validityParameter) { var code = @" using System; using System.Runtime.CompilerServices; GetReceiver().M( GetArg(""Unrelated parameter 1""), GetArg(""Second value""), GetArg(""Unrelated parameter 2""), GetArg(""First value""), $""literal"", GetArg(""Unrelated parameter 4"")); C GetReceiver() { Console.WriteLine(""GetReceiver""); return new C() { Prop = ""Prop"" }; } string GetArg(string s) { Console.WriteLine(s); return s; } public class C { public string Prop { get; set; } public void M(string param1, string param2, string param3, string param4, [InterpolatedStringHandlerArgument(""param4"", """", ""param2"")] CustomHandler c, string param6) => Console.WriteLine(c.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s1, C c, string s2" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""Handler constructor""); _builder.AppendLine(""s1:"" + s1); _builder.AppendLine(""c.Prop:"" + c.Prop); _builder.AppendLine(""s2:"" + s2); " + (validityParameter ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns); var verifier = CompileAndVerify(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }, expectedOutput: @" GetReceiver Unrelated parameter 1 Second value Unrelated parameter 2 First value Handler constructor Unrelated parameter 4 s1:First value c.Prop:Prop s2:Second value literal:literal "); verifier.VerifyDiagnostics(); } [Fact] public void InterpolatedStringHandlerArgumentsAttribute_ConversionFromArgumentType() { var code = @" using System; using System.Globalization; using System.Runtime.CompilerServices; int i = 1; C.M(i, $""literal""); public class C { public static implicit operator C(int i) => throw null; public static implicit operator C(double d) { Console.WriteLine(d.ToString(""G"", CultureInfo.InvariantCulture)); return new C(); } public override string ToString() => ""C""; public static void M(double d, [InterpolatedStringHandlerArgument(""d"")] CustomHandler handler) => Console.WriteLine(handler.ToString()); } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, C c) : this(literalLength, formattedCount) { } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: true); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, sourceSymbolValidator: validator, symbolValidator: validator, expectedOutput: @" 1 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 39 (0x27) .maxstack 5 .locals init (double V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: conv.r8 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: ldloca.s V_1 IL_0006: ldc.i4.7 IL_0007: ldc.i4.0 IL_0008: ldloc.0 IL_0009: call ""C C.op_Implicit(double)"" IL_000e: call ""CustomHandler..ctor(int, int, C)"" IL_0013: ldloca.s V_1 IL_0015: ldstr ""literal"" IL_001a: call ""bool CustomHandler.AppendLiteral(string)"" IL_001f: pop IL_0020: ldloc.1 IL_0021: call ""void C.M(double, CustomHandler)"" IL_0026: ret } "); static void validator(ModuleSymbol module) { var cParam = module.GlobalNamespace.GetTypeMember("C").GetMethod("M").Parameters.Skip(1).Single(); AssertEx.Equal("System.Runtime.CompilerServices.InterpolatedStringHandlerArgumentAttribute", cParam.GetAttributes().Single().AttributeClass.ToTestDisplayString()); Assert.Equal(new[] { 0 }, cParam.InterpolatedStringHandlerArgumentIndexes); } } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentsAttribute_CompoundAssignment_Indexer_01(bool useBoolReturns, bool validityParameter) { var code = @" using System; using System.Runtime.CompilerServices; int i = 3; GetC()[GetInt(1), $""literal{i}""] += GetInt(2); static C GetC() { Console.WriteLine(""GetC""); return new C() { Prop = 2 }; } static int GetInt(int i) { Console.WriteLine(""GetInt"" + i.ToString()); return 1; } public class C { public int Prop { get; set; } public int this[int arg1, [InterpolatedStringHandlerArgument(""arg1"", """")] CustomHandler c] { get { Console.WriteLine(""Indexer getter""); return 0; } set { Console.WriteLine(""Indexer setter""); Console.WriteLine(c.ToString()); } } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int arg1, C c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""Handler constructor""); _builder.AppendLine(""arg1:"" + arg1); _builder.AppendLine(""C.Prop:"" + c.Prop.ToString()); " + (validityParameter ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" GetC GetInt1 Handler constructor Indexer getter GetInt2 Indexer setter arg1:1 C.Prop:2 literal:literal value:3 alignment:0 format: "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 85 (0x55) .maxstack 6 .locals init (int V_0, //i int V_1, C V_2, int V_3, CustomHandler V_4, CustomHandler V_5) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldc.i4.1 IL_0009: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: stloc.3 IL_0011: ldloca.s V_5 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_5 IL_001e: ldstr ""literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_5 IL_002a: ldloc.0 IL_002b: box ""int"" IL_0030: ldc.i4.0 IL_0031: ldnull IL_0032: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0037: ldloc.s V_5 IL_0039: stloc.s V_4 IL_003b: ldloc.2 IL_003c: ldloc.3 IL_003d: ldloc.s V_4 IL_003f: ldloc.2 IL_0040: ldloc.3 IL_0041: ldloc.s V_4 IL_0043: callvirt ""int C.this[int, CustomHandler].get"" IL_0048: ldc.i4.2 IL_0049: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_004e: add IL_004f: callvirt ""void C.this[int, CustomHandler].set"" IL_0054: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 96 (0x60) .maxstack 6 .locals init (int V_0, //i int V_1, C V_2, int V_3, CustomHandler V_4, CustomHandler V_5, bool V_6) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldc.i4.1 IL_0009: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: stloc.3 IL_0011: ldc.i4.7 IL_0012: ldc.i4.1 IL_0013: ldloc.1 IL_0014: ldloc.2 IL_0015: ldloca.s V_6 IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001c: stloc.s V_5 IL_001e: ldloc.s V_6 IL_0020: brfalse.s IL_0040 IL_0022: ldloca.s V_5 IL_0024: ldstr ""literal"" IL_0029: call ""void CustomHandler.AppendLiteral(string)"" IL_002e: ldloca.s V_5 IL_0030: ldloc.0 IL_0031: box ""int"" IL_0036: ldc.i4.0 IL_0037: ldnull IL_0038: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_003d: ldc.i4.1 IL_003e: br.s IL_0041 IL_0040: ldc.i4.0 IL_0041: pop IL_0042: ldloc.s V_5 IL_0044: stloc.s V_4 IL_0046: ldloc.2 IL_0047: ldloc.3 IL_0048: ldloc.s V_4 IL_004a: ldloc.2 IL_004b: ldloc.3 IL_004c: ldloc.s V_4 IL_004e: callvirt ""int C.this[int, CustomHandler].get"" IL_0053: ldc.i4.2 IL_0054: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_0059: add IL_005a: callvirt ""void C.this[int, CustomHandler].set"" IL_005f: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 91 (0x5b) .maxstack 6 .locals init (int V_0, //i int V_1, C V_2, int V_3, CustomHandler V_4, CustomHandler V_5) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldc.i4.1 IL_0009: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: stloc.3 IL_0011: ldloca.s V_5 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_5 IL_001e: ldstr ""literal"" IL_0023: call ""bool CustomHandler.AppendLiteral(string)"" IL_0028: brfalse.s IL_003b IL_002a: ldloca.s V_5 IL_002c: ldloc.0 IL_002d: box ""int"" IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0039: br.s IL_003c IL_003b: ldc.i4.0 IL_003c: pop IL_003d: ldloc.s V_5 IL_003f: stloc.s V_4 IL_0041: ldloc.2 IL_0042: ldloc.3 IL_0043: ldloc.s V_4 IL_0045: ldloc.2 IL_0046: ldloc.3 IL_0047: ldloc.s V_4 IL_0049: callvirt ""int C.this[int, CustomHandler].get"" IL_004e: ldc.i4.2 IL_004f: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_0054: add IL_0055: callvirt ""void C.this[int, CustomHandler].set"" IL_005a: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 97 (0x61) .maxstack 6 .locals init (int V_0, //i int V_1, C V_2, int V_3, CustomHandler V_4, CustomHandler V_5, bool V_6) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldc.i4.1 IL_0009: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_000e: stloc.1 IL_000f: ldloc.1 IL_0010: stloc.3 IL_0011: ldc.i4.7 IL_0012: ldc.i4.1 IL_0013: ldloc.1 IL_0014: ldloc.2 IL_0015: ldloca.s V_6 IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001c: stloc.s V_5 IL_001e: ldloc.s V_6 IL_0020: brfalse.s IL_0041 IL_0022: ldloca.s V_5 IL_0024: ldstr ""literal"" IL_0029: call ""bool CustomHandler.AppendLiteral(string)"" IL_002e: brfalse.s IL_0041 IL_0030: ldloca.s V_5 IL_0032: ldloc.0 IL_0033: box ""int"" IL_0038: ldc.i4.0 IL_0039: ldnull IL_003a: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_003f: br.s IL_0042 IL_0041: ldc.i4.0 IL_0042: pop IL_0043: ldloc.s V_5 IL_0045: stloc.s V_4 IL_0047: ldloc.2 IL_0048: ldloc.3 IL_0049: ldloc.s V_4 IL_004b: ldloc.2 IL_004c: ldloc.3 IL_004d: ldloc.s V_4 IL_004f: callvirt ""int C.this[int, CustomHandler].get"" IL_0054: ldc.i4.2 IL_0055: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_005a: add IL_005b: callvirt ""void C.this[int, CustomHandler].set"" IL_0060: ret } ", }; } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentsAttribute_CompoundAssignment_Indexer_02(bool useBoolReturns, bool validityParameter) { var code = @" using System; using System.Runtime.CompilerServices; int i = 3; GetC()[GetInt(1), $""literal{i}""] += GetInt(2); static C GetC() { Console.WriteLine(""GetC""); return new C() { Prop = 2 }; } static int GetInt(int i) { Console.WriteLine(""GetInt"" + i.ToString()); return 1; } public class C { private int field; public int Prop { get; set; } public ref int this[int arg1, [InterpolatedStringHandlerArgument(""arg1"", """")] CustomHandler c] { get { Console.WriteLine(""Indexer getter""); Console.WriteLine(c.ToString()); return ref field; } } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int arg1, C c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""Handler constructor""); _builder.AppendLine(""arg1:"" + arg1); _builder.AppendLine(""C.Prop:"" + c.Prop.ToString()); " + (validityParameter ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" GetC GetInt1 Handler constructor Indexer getter arg1:1 C.Prop:2 literal:literal value:3 alignment:0 format: GetInt2 "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 72 (0x48) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldloca.s V_3 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_3 IL_001e: ldstr ""literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_3 IL_002a: ldloc.0 IL_002b: box ""int"" IL_0030: ldc.i4.0 IL_0031: ldnull IL_0032: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0037: ldloc.3 IL_0038: callvirt ""ref int C.this[int, CustomHandler].get"" IL_003d: dup IL_003e: ldind.i4 IL_003f: ldc.i4.2 IL_0040: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_0045: add IL_0046: stind.i4 IL_0047: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 82 (0x52) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.7 IL_0012: ldc.i4.1 IL_0013: ldloc.1 IL_0014: ldloc.2 IL_0015: ldloca.s V_4 IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001c: stloc.3 IL_001d: ldloc.s V_4 IL_001f: brfalse.s IL_003f IL_0021: ldloca.s V_3 IL_0023: ldstr ""literal"" IL_0028: call ""void CustomHandler.AppendLiteral(string)"" IL_002d: ldloca.s V_3 IL_002f: ldloc.0 IL_0030: box ""int"" IL_0035: ldc.i4.0 IL_0036: ldnull IL_0037: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_003c: ldc.i4.1 IL_003d: br.s IL_0040 IL_003f: ldc.i4.0 IL_0040: pop IL_0041: ldloc.3 IL_0042: callvirt ""ref int C.this[int, CustomHandler].get"" IL_0047: dup IL_0048: ldind.i4 IL_0049: ldc.i4.2 IL_004a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_004f: add IL_0050: stind.i4 IL_0051: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 78 (0x4e) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldloca.s V_3 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_3 IL_001e: ldstr ""literal"" IL_0023: call ""bool CustomHandler.AppendLiteral(string)"" IL_0028: brfalse.s IL_003b IL_002a: ldloca.s V_3 IL_002c: ldloc.0 IL_002d: box ""int"" IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0039: br.s IL_003c IL_003b: ldc.i4.0 IL_003c: pop IL_003d: ldloc.3 IL_003e: callvirt ""ref int C.this[int, CustomHandler].get"" IL_0043: dup IL_0044: ldind.i4 IL_0045: ldc.i4.2 IL_0046: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_004b: add IL_004c: stind.i4 IL_004d: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 83 (0x53) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.7 IL_0012: ldc.i4.1 IL_0013: ldloc.1 IL_0014: ldloc.2 IL_0015: ldloca.s V_4 IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001c: stloc.3 IL_001d: ldloc.s V_4 IL_001f: brfalse.s IL_0040 IL_0021: ldloca.s V_3 IL_0023: ldstr ""literal"" IL_0028: call ""bool CustomHandler.AppendLiteral(string)"" IL_002d: brfalse.s IL_0040 IL_002f: ldloca.s V_3 IL_0031: ldloc.0 IL_0032: box ""int"" IL_0037: ldc.i4.0 IL_0038: ldnull IL_0039: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_003e: br.s IL_0041 IL_0040: ldc.i4.0 IL_0041: pop IL_0042: ldloc.3 IL_0043: callvirt ""ref int C.this[int, CustomHandler].get"" IL_0048: dup IL_0049: ldind.i4 IL_004a: ldc.i4.2 IL_004b: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_0050: add IL_0051: stind.i4 IL_0052: ret } ", }; } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentsAttribute_CompoundAssignment_RefReturningMethod(bool useBoolReturns, bool validityParameter) { var code = @" using System; using System.Runtime.CompilerServices; int i = 3; GetC().M(GetInt(1), $""literal{i}"") += GetInt(2); static C GetC() { Console.WriteLine(""GetC""); return new C() { Prop = 2 }; } static int GetInt(int i) { Console.WriteLine(""GetInt"" + i.ToString()); return 1; } public class C { private int field; public int Prop { get; set; } public ref int M(int arg1, [InterpolatedStringHandlerArgument(""arg1"", """")] CustomHandler c) { Console.WriteLine(""M""); Console.WriteLine(c.ToString()); return ref field; } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, int arg1, C c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""Handler constructor""); _builder.AppendLine(""arg1:"" + arg1); _builder.AppendLine(""C.Prop:"" + c.Prop.ToString()); " + (validityParameter ? "success = true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" GetC GetInt1 Handler constructor M arg1:1 C.Prop:2 literal:literal value:3 alignment:0 format: GetInt2 "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 72 (0x48) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldloca.s V_3 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_3 IL_001e: ldstr ""literal"" IL_0023: call ""void CustomHandler.AppendLiteral(string)"" IL_0028: ldloca.s V_3 IL_002a: ldloc.0 IL_002b: box ""int"" IL_0030: ldc.i4.0 IL_0031: ldnull IL_0032: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0037: ldloc.3 IL_0038: callvirt ""ref int C.M(int, CustomHandler)"" IL_003d: dup IL_003e: ldind.i4 IL_003f: ldc.i4.2 IL_0040: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_0045: add IL_0046: stind.i4 IL_0047: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 82 (0x52) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.7 IL_0012: ldc.i4.1 IL_0013: ldloc.1 IL_0014: ldloc.2 IL_0015: ldloca.s V_4 IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001c: stloc.3 IL_001d: ldloc.s V_4 IL_001f: brfalse.s IL_003f IL_0021: ldloca.s V_3 IL_0023: ldstr ""literal"" IL_0028: call ""void CustomHandler.AppendLiteral(string)"" IL_002d: ldloca.s V_3 IL_002f: ldloc.0 IL_0030: box ""int"" IL_0035: ldc.i4.0 IL_0036: ldnull IL_0037: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_003c: ldc.i4.1 IL_003d: br.s IL_0040 IL_003f: ldc.i4.0 IL_0040: pop IL_0041: ldloc.3 IL_0042: callvirt ""ref int C.M(int, CustomHandler)"" IL_0047: dup IL_0048: ldind.i4 IL_0049: ldc.i4.2 IL_004a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_004f: add IL_0050: stind.i4 IL_0051: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 78 (0x4e) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldloca.s V_3 IL_0013: ldc.i4.7 IL_0014: ldc.i4.1 IL_0015: ldloc.1 IL_0016: ldloc.2 IL_0017: call ""CustomHandler..ctor(int, int, int, C)"" IL_001c: ldloca.s V_3 IL_001e: ldstr ""literal"" IL_0023: call ""bool CustomHandler.AppendLiteral(string)"" IL_0028: brfalse.s IL_003b IL_002a: ldloca.s V_3 IL_002c: ldloc.0 IL_002d: box ""int"" IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0039: br.s IL_003c IL_003b: ldc.i4.0 IL_003c: pop IL_003d: ldloc.3 IL_003e: callvirt ""ref int C.M(int, CustomHandler)"" IL_0043: dup IL_0044: ldind.i4 IL_0045: ldc.i4.2 IL_0046: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_004b: add IL_004c: stind.i4 IL_004d: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 83 (0x53) .maxstack 7 .locals init (int V_0, //i int V_1, C V_2, CustomHandler V_3, bool V_4) IL_0000: ldc.i4.3 IL_0001: stloc.0 IL_0002: call ""C <Program>$.<<Main>$>g__GetC|0_0()"" IL_0007: stloc.2 IL_0008: ldloc.2 IL_0009: ldc.i4.1 IL_000a: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_000f: stloc.1 IL_0010: ldloc.1 IL_0011: ldc.i4.7 IL_0012: ldc.i4.1 IL_0013: ldloc.1 IL_0014: ldloc.2 IL_0015: ldloca.s V_4 IL_0017: newobj ""CustomHandler..ctor(int, int, int, C, out bool)"" IL_001c: stloc.3 IL_001d: ldloc.s V_4 IL_001f: brfalse.s IL_0040 IL_0021: ldloca.s V_3 IL_0023: ldstr ""literal"" IL_0028: call ""bool CustomHandler.AppendLiteral(string)"" IL_002d: brfalse.s IL_0040 IL_002f: ldloca.s V_3 IL_0031: ldloc.0 IL_0032: box ""int"" IL_0037: ldc.i4.0 IL_0038: ldnull IL_0039: call ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_003e: br.s IL_0041 IL_0040: ldc.i4.0 IL_0041: pop IL_0042: ldloc.3 IL_0043: callvirt ""ref int C.M(int, CustomHandler)"" IL_0048: dup IL_0049: ldind.i4 IL_004a: ldc.i4.2 IL_004b: call ""int <Program>$.<<Main>$>g__GetInt|0_1(int)"" IL_0050: add IL_0051: stind.i4 IL_0052: ret } ", }; } [Fact] public void InterpolatedStringHandlerArgumentsAttribute_CollectionInitializerAdd() { var code = @" using System; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; _ = new C(1) { $""literal"" }; public class C : IEnumerable<int> { public int Field; public C(int i) { Field = i; } public void Add([InterpolatedStringHandlerArgument("""")] CustomHandler c) { Console.WriteLine(c.ToString()); } public IEnumerator<int> GetEnumerator() => throw null; IEnumerator IEnumerable.GetEnumerator() => throw null; } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, C c) : this(literalLength, formattedCount) { _builder.AppendLine(""c.Field:"" + c.Field.ToString()); } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" c.Field:1 literal:literal "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 37 (0x25) .maxstack 5 .locals init (C V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: newobj ""C..ctor(int)"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldloca.s V_1 IL_000a: ldc.i4.7 IL_000b: ldc.i4.0 IL_000c: ldloc.0 IL_000d: call ""CustomHandler..ctor(int, int, C)"" IL_0012: ldloca.s V_1 IL_0014: ldstr ""literal"" IL_0019: call ""void CustomHandler.AppendLiteral(string)"" IL_001e: ldloc.1 IL_001f: callvirt ""void C.Add(CustomHandler)"" IL_0024: ret } "); } [Theory] [CombinatorialData] public void InterpolatedStringHandlerArgumentAttribute_AttributeOnAppendFormatCall(bool useBoolReturns, bool validityParameter) { var code = @" using System; using System.Runtime.CompilerServices; C.M(1, $""{$""Inner string""}{2}""); class C { public static void M(int i, [InterpolatedStringHandlerArgument(""i"")]CustomHandler handler) { Console.WriteLine(handler.ToString()); } } public partial class CustomHandler { private int I = 0; public CustomHandler(int literalLength, int formattedCount, int i" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""int constructor""); I = i; " + (validityParameter ? "success = true;" : "") + @" } public CustomHandler(int literalLength, int formattedCount, CustomHandler c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { Console.WriteLine(""CustomHandler constructor""); _builder.AppendLine(""c.I:"" + c.I.ToString()); " + (validityParameter ? "success = true;" : "") + @" } public " + (useBoolReturns ? "bool" : "void") + @" AppendFormatted([InterpolatedStringHandlerArgument("""")]CustomHandler c) { _builder.AppendLine(""CustomHandler AppendFormatted""); _builder.Append(c.ToString()); " + (useBoolReturns ? "return true;" : "") + @" } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns: useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @" int constructor CustomHandler constructor CustomHandler AppendFormatted c.I:1 literal:Inner string value:2 alignment:0 format: "); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 59 (0x3b) .maxstack 6 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.2 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: dup IL_000c: stloc.1 IL_000d: ldloc.1 IL_000e: ldc.i4.s 12 IL_0010: ldc.i4.0 IL_0011: ldloc.1 IL_0012: newobj ""CustomHandler..ctor(int, int, CustomHandler)"" IL_0017: dup IL_0018: ldstr ""Inner string"" IL_001d: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0022: callvirt ""void CustomHandler.AppendFormatted(CustomHandler)"" IL_0027: dup IL_0028: ldc.i4.2 IL_0029: box ""int"" IL_002e: ldc.i4.0 IL_002f: ldnull IL_0030: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0035: call ""void C.M(int, CustomHandler)"" IL_003a: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 87 (0x57) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2, CustomHandler V_3, CustomHandler V_4, bool V_5) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.2 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000d: stloc.1 IL_000e: ldloc.2 IL_000f: brfalse.s IL_004e IL_0011: ldloc.1 IL_0012: stloc.3 IL_0013: ldloc.3 IL_0014: ldc.i4.s 12 IL_0016: ldc.i4.0 IL_0017: ldloc.3 IL_0018: ldloca.s V_5 IL_001a: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)"" IL_001f: stloc.s V_4 IL_0021: ldloc.s V_5 IL_0023: brfalse.s IL_0034 IL_0025: ldloc.s V_4 IL_0027: ldstr ""Inner string"" IL_002c: callvirt ""void CustomHandler.AppendLiteral(string)"" IL_0031: ldc.i4.1 IL_0032: br.s IL_0035 IL_0034: ldc.i4.0 IL_0035: pop IL_0036: ldloc.s V_4 IL_0038: callvirt ""void CustomHandler.AppendFormatted(CustomHandler)"" IL_003d: ldloc.1 IL_003e: ldc.i4.2 IL_003f: box ""int"" IL_0044: ldc.i4.0 IL_0045: ldnull IL_0046: callvirt ""void CustomHandler.AppendFormatted(object, int, string)"" IL_004b: ldc.i4.1 IL_004c: br.s IL_004f IL_004e: ldc.i4.0 IL_004f: pop IL_0050: ldloc.1 IL_0051: call ""void C.M(int, CustomHandler)"" IL_0056: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 68 (0x44) .maxstack 5 .locals init (int V_0, CustomHandler V_1, CustomHandler V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.2 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: stloc.2 IL_000e: ldloc.2 IL_000f: ldc.i4.s 12 IL_0011: ldc.i4.0 IL_0012: ldloc.2 IL_0013: newobj ""CustomHandler..ctor(int, int, CustomHandler)"" IL_0018: dup IL_0019: ldstr ""Inner string"" IL_001e: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0023: pop IL_0024: callvirt ""bool CustomHandler.AppendFormatted(CustomHandler)"" IL_0029: brfalse.s IL_003b IL_002b: ldloc.1 IL_002c: ldc.i4.2 IL_002d: box ""int"" IL_0032: ldc.i4.0 IL_0033: ldnull IL_0034: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_0039: br.s IL_003c IL_003b: ldc.i4.0 IL_003c: pop IL_003d: ldloc.1 IL_003e: call ""void C.M(int, CustomHandler)"" IL_0043: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 87 (0x57) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2, CustomHandler V_3, CustomHandler V_4, bool V_5) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.2 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000d: stloc.1 IL_000e: ldloc.2 IL_000f: brfalse.s IL_004e IL_0011: ldloc.1 IL_0012: stloc.3 IL_0013: ldloc.3 IL_0014: ldc.i4.s 12 IL_0016: ldc.i4.0 IL_0017: ldloc.3 IL_0018: ldloca.s V_5 IL_001a: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)"" IL_001f: stloc.s V_4 IL_0021: ldloc.s V_5 IL_0023: brfalse.s IL_0033 IL_0025: ldloc.s V_4 IL_0027: ldstr ""Inner string"" IL_002c: callvirt ""bool CustomHandler.AppendLiteral(string)"" IL_0031: br.s IL_0034 IL_0033: ldc.i4.0 IL_0034: pop IL_0035: ldloc.s V_4 IL_0037: callvirt ""bool CustomHandler.AppendFormatted(CustomHandler)"" IL_003c: brfalse.s IL_004e IL_003e: ldloc.1 IL_003f: ldc.i4.2 IL_0040: box ""int"" IL_0045: ldc.i4.0 IL_0046: ldnull IL_0047: callvirt ""bool CustomHandler.AppendFormatted(object, int, string)"" IL_004c: br.s IL_004f IL_004e: ldc.i4.0 IL_004f: pop IL_0050: ldloc.1 IL_0051: call ""void C.M(int, CustomHandler)"" IL_0056: ret } ", }; } [Fact] public void DiscardsUsedAsParameters() { var code = @" using System; using System.Runtime.CompilerServices; C.M(out _, $""literal""); public class C { public static void M(out int i, [InterpolatedStringHandlerArgument(""i"")]CustomHandler c) { i = 0; Console.WriteLine(c.ToString()); } } public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, out int i) : this(literalLength, formattedCount) { i = 1; } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: @"literal:literal"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 31 (0x1f) .maxstack 4 .locals init (int V_0, CustomHandler V_1) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.0 IL_0004: ldloca.s V_0 IL_0006: newobj ""CustomHandler..ctor(int, int, out int)"" IL_000b: stloc.1 IL_000c: ldloca.s V_1 IL_000e: ldstr ""literal"" IL_0013: call ""void CustomHandler.AppendLiteral(string)"" IL_0018: ldloc.1 IL_0019: call ""void C.M(out int, CustomHandler)"" IL_001e: ret } "); } [Fact] public void DiscardsUsedAsParameters_DefinedInVB() { var vb = @" Imports System Imports System.Runtime.CompilerServices Imports System.Runtime.InteropServices Public Class C Public Shared Sub M(<Out> ByRef i As Integer, <InterpolatedStringHandlerArgument(""i"")>c As CustomHandler) Console.WriteLine(i) End Sub End Class <InterpolatedStringHandler> Public Structure CustomHandler Public Sub New(literalLength As Integer, formattedCount As Integer, <Out> ByRef i As Integer) i = 1 End Sub End Structure "; var vbComp = CreateVisualBasicCompilation(new[] { vb, InterpolatedStringHandlerAttributesVB }); vbComp.VerifyDiagnostics(); var code = @"C.M(out _, $"""");"; var comp = CreateCompilation(code, new[] { vbComp.EmitToImageReference() }); var verifier = CompileAndVerify(comp, expectedOutput: @"1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 17 (0x11) .maxstack 4 .locals init (int V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.0 IL_0003: ldc.i4.0 IL_0004: ldloca.s V_0 IL_0006: newobj ""CustomHandler..ctor(int, int, out int)"" IL_000b: call ""void C.M(out int, CustomHandler)"" IL_0010: ret } "); } [Fact] public void DisallowedInExpressionTrees() { var code = @" using System; using System.Linq.Expressions; Expression<Func<CustomHandler>> expr = () => $""""; "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, handler }); comp.VerifyDiagnostics( // (5,46): error CS8952: An expression tree may not contain an interpolated string handler conversion. // Expression<Func<CustomHandler>> expr = () => $""; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsInterpolatedStringHandlerConversion, @"$""""").WithLocation(5, 46) ); } [Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")] public void AsStringInExpressionTrees_01() { var code = @" using System; using System.Linq.Expressions; Expression<Func<string, string>> e = o => $""{o.Length}"";"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 127 (0x7f) .maxstack 7 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: ldtoken ""string"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""o"" IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0014: stloc.0 IL_0015: ldnull IL_0016: ldtoken ""string string.Format(string, object)"" IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0020: castclass ""System.Reflection.MethodInfo"" IL_0025: ldc.i4.2 IL_0026: newarr ""System.Linq.Expressions.Expression"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldstr ""{0}"" IL_0032: ldtoken ""string"" IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.1 IL_0044: ldloc.0 IL_0045: ldtoken ""int string.Length.get"" IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_004f: castclass ""System.Reflection.MethodInfo"" IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0059: ldtoken ""object"" IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0068: stelem.ref IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_006e: ldc.i4.1 IL_006f: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0074: dup IL_0075: ldc.i4.0 IL_0076: ldloc.0 IL_0077: stelem.ref IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_007d: pop IL_007e: ret } "); } [Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")] public void AsStringInExpressionTrees_02() { var code = @" using System.Linq.Expressions; Expression e = (string o) => $""{o.Length}"";"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 127 (0x7f) .maxstack 7 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: ldtoken ""string"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""o"" IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0014: stloc.0 IL_0015: ldnull IL_0016: ldtoken ""string string.Format(string, object)"" IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0020: castclass ""System.Reflection.MethodInfo"" IL_0025: ldc.i4.2 IL_0026: newarr ""System.Linq.Expressions.Expression"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldstr ""{0}"" IL_0032: ldtoken ""string"" IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.1 IL_0044: ldloc.0 IL_0045: ldtoken ""int string.Length.get"" IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_004f: castclass ""System.Reflection.MethodInfo"" IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0059: ldtoken ""object"" IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0068: stelem.ref IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_006e: ldc.i4.1 IL_006f: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0074: dup IL_0075: ldc.i4.0 IL_0076: ldloc.0 IL_0077: stelem.ref IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_007d: pop IL_007e: ret } "); } [Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")] public void AsStringInExpressionTrees_03() { var code = @" using System; using System.Linq.Expressions; Expression<Func<Func<string, string>>> e = () => o => $""{o.Length}"";"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 137 (0x89) .maxstack 7 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: ldtoken ""string"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""o"" IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0014: stloc.0 IL_0015: ldnull IL_0016: ldtoken ""string string.Format(string, object)"" IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0020: castclass ""System.Reflection.MethodInfo"" IL_0025: ldc.i4.2 IL_0026: newarr ""System.Linq.Expressions.Expression"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldstr ""{0}"" IL_0032: ldtoken ""string"" IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.1 IL_0044: ldloc.0 IL_0045: ldtoken ""int string.Length.get"" IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_004f: castclass ""System.Reflection.MethodInfo"" IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0059: ldtoken ""object"" IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0068: stelem.ref IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_006e: ldc.i4.1 IL_006f: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0074: dup IL_0075: ldc.i4.0 IL_0076: ldloc.0 IL_0077: stelem.ref IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_007d: call ""System.Linq.Expressions.ParameterExpression[] System.Array.Empty<System.Linq.Expressions.ParameterExpression>()"" IL_0082: call ""System.Linq.Expressions.Expression<System.Func<System.Func<string, string>>> System.Linq.Expressions.Expression.Lambda<System.Func<System.Func<string, string>>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0087: pop IL_0088: ret } "); } [Fact, WorkItem(55114, "https://github.com/dotnet/roslyn/issues/55114")] public void AsStringInExpressionTrees_04() { var code = @" using System; using System.Linq.Expressions; Expression e = Func<string, string> () => (string o) => $""{o.Length}"";"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 137 (0x89) .maxstack 7 .locals init (System.Linq.Expressions.ParameterExpression V_0) IL_0000: ldtoken ""string"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ldstr ""o"" IL_000f: call ""System.Linq.Expressions.ParameterExpression System.Linq.Expressions.Expression.Parameter(System.Type, string)"" IL_0014: stloc.0 IL_0015: ldnull IL_0016: ldtoken ""string string.Format(string, object)"" IL_001b: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_0020: castclass ""System.Reflection.MethodInfo"" IL_0025: ldc.i4.2 IL_0026: newarr ""System.Linq.Expressions.Expression"" IL_002b: dup IL_002c: ldc.i4.0 IL_002d: ldstr ""{0}"" IL_0032: ldtoken ""string"" IL_0037: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003c: call ""System.Linq.Expressions.ConstantExpression System.Linq.Expressions.Expression.Constant(object, System.Type)"" IL_0041: stelem.ref IL_0042: dup IL_0043: ldc.i4.1 IL_0044: ldloc.0 IL_0045: ldtoken ""int string.Length.get"" IL_004a: call ""System.Reflection.MethodBase System.Reflection.MethodBase.GetMethodFromHandle(System.RuntimeMethodHandle)"" IL_004f: castclass ""System.Reflection.MethodInfo"" IL_0054: call ""System.Linq.Expressions.MemberExpression System.Linq.Expressions.Expression.Property(System.Linq.Expressions.Expression, System.Reflection.MethodInfo)"" IL_0059: ldtoken ""object"" IL_005e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0063: call ""System.Linq.Expressions.UnaryExpression System.Linq.Expressions.Expression.Convert(System.Linq.Expressions.Expression, System.Type)"" IL_0068: stelem.ref IL_0069: call ""System.Linq.Expressions.MethodCallExpression System.Linq.Expressions.Expression.Call(System.Linq.Expressions.Expression, System.Reflection.MethodInfo, params System.Linq.Expressions.Expression[])"" IL_006e: ldc.i4.1 IL_006f: newarr ""System.Linq.Expressions.ParameterExpression"" IL_0074: dup IL_0075: ldc.i4.0 IL_0076: ldloc.0 IL_0077: stelem.ref IL_0078: call ""System.Linq.Expressions.Expression<System.Func<string, string>> System.Linq.Expressions.Expression.Lambda<System.Func<string, string>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_007d: call ""System.Linq.Expressions.ParameterExpression[] System.Array.Empty<System.Linq.Expressions.ParameterExpression>()"" IL_0082: call ""System.Linq.Expressions.Expression<System.Func<System.Func<string, string>>> System.Linq.Expressions.Expression.Lambda<System.Func<System.Func<string, string>>>(System.Linq.Expressions.Expression, params System.Linq.Expressions.ParameterExpression[])"" IL_0087: pop IL_0088: ret } "); } [Theory] [CombinatorialData] public void CustomHandlerUsedAsArgumentToCustomHandler(bool useBoolReturns, bool validityParameter) { var code = @" using System; using System.Runtime.CompilerServices; C.M(1, $"""", $""""); public class C { public static void M(int i, [InterpolatedStringHandlerArgument(""i"")] CustomHandler c1, [InterpolatedStringHandlerArgument(""c1"")] CustomHandler c2) => Console.WriteLine(c2.ToString()); } public partial class CustomHandler { private int i; public CustomHandler(int literalLength, int formattedCount, int i" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { _builder.AppendLine(""i:"" + i.ToString()); this.i = i; " + (validityParameter ? "success = true;" : "") + @" } public CustomHandler(int literalLength, int formattedCount, CustomHandler c" + (validityParameter ? ", out bool success" : "") + @") : this(literalLength, formattedCount) { _builder.AppendLine(""c.i:"" + c.i.ToString()); " + (validityParameter ? "success = true;" : "") + @" } }"; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial class", useBoolReturns); var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerArgumentAttribute, handler }); var verifier = CompileAndVerify(comp, expectedOutput: "c.i:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", getIl()); string getIl() => (useBoolReturns, validityParameter) switch { (useBoolReturns: false, validityParameter: false) => @" { // Code size 27 (0x1b) .maxstack 5 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: ldc.i4.0 IL_000e: ldc.i4.0 IL_000f: ldloc.1 IL_0010: newobj ""CustomHandler..ctor(int, int, CustomHandler)"" IL_0015: call ""void C.M(int, CustomHandler, CustomHandler)"" IL_001a: ret } ", (useBoolReturns: false, validityParameter: true) => @" { // Code size 31 (0x1f) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000d: stloc.1 IL_000e: ldloc.1 IL_000f: ldc.i4.0 IL_0010: ldc.i4.0 IL_0011: ldloc.1 IL_0012: ldloca.s V_2 IL_0014: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)"" IL_0019: call ""void C.M(int, CustomHandler, CustomHandler)"" IL_001e: ret } ", (useBoolReturns: true, validityParameter: false) => @" { // Code size 27 (0x1b) .maxstack 5 .locals init (int V_0, CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: newobj ""CustomHandler..ctor(int, int, int)"" IL_000b: stloc.1 IL_000c: ldloc.1 IL_000d: ldc.i4.0 IL_000e: ldc.i4.0 IL_000f: ldloc.1 IL_0010: newobj ""CustomHandler..ctor(int, int, CustomHandler)"" IL_0015: call ""void C.M(int, CustomHandler, CustomHandler)"" IL_001a: ret } ", (useBoolReturns: true, validityParameter: true) => @" { // Code size 31 (0x1f) .maxstack 6 .locals init (int V_0, CustomHandler V_1, bool V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: ldloca.s V_2 IL_0008: newobj ""CustomHandler..ctor(int, int, int, out bool)"" IL_000d: stloc.1 IL_000e: ldloc.1 IL_000f: ldc.i4.0 IL_0010: ldc.i4.0 IL_0011: ldloc.1 IL_0012: ldloca.s V_2 IL_0014: newobj ""CustomHandler..ctor(int, int, CustomHandler, out bool)"" IL_0019: call ""void C.M(int, CustomHandler, CustomHandler)"" IL_001e: ret } ", }; } [Theory] [CombinatorialData] public void DefiniteAssignment_01(bool useBoolReturns, bool trailingOutParameter) { var code = @" int i; string s; CustomHandler c = $""{i = 1}{M(out var o)}{s = o.ToString()}""; _ = i.ToString(); _ = o.ToString(); _ = s.ToString(); string M(out object o) { o = null; return null; } "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns, includeTrailingOutConstructorParameter: trailingOutParameter); var comp = CreateCompilation(new[] { code, customHandler }); if (trailingOutParameter) { comp.VerifyDiagnostics( // (6,5): error CS0165: Use of unassigned local variable 'i' // _ = i.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(6, 5), // (7,5): error CS0165: Use of unassigned local variable 'o' // _ = o.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "o").WithArguments("o").WithLocation(7, 5), // (8,5): error CS0165: Use of unassigned local variable 's' // _ = s.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "s").WithArguments("s").WithLocation(8, 5) ); } else if (useBoolReturns) { comp.VerifyDiagnostics( // (7,5): error CS0165: Use of unassigned local variable 'o' // _ = o.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "o").WithArguments("o").WithLocation(7, 5), // (8,5): error CS0165: Use of unassigned local variable 's' // _ = s.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "s").WithArguments("s").WithLocation(8, 5) ); } else { comp.VerifyDiagnostics(); } } [Theory] [CombinatorialData] public void DefiniteAssignment_02(bool useBoolReturns, bool trailingOutParameter) { var code = @" int i; CustomHandler c = $""{i = 1}""; _ = i.ToString(); "; var customHandler = GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns, includeTrailingOutConstructorParameter: trailingOutParameter); var comp = CreateCompilation(new[] { code, customHandler }); if (trailingOutParameter) { comp.VerifyDiagnostics( // (5,5): error CS0165: Use of unassigned local variable 'i' // _ = i.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "i").WithArguments("i").WithLocation(5, 5) ); } else { comp.VerifyDiagnostics(); } } [Fact] public void DynamicConstruction_01() { var code = @" using System.Runtime.CompilerServices; dynamic d = 1; M(d, $""""); void M(dynamic d, [InterpolatedStringHandlerArgument(""d"")]CustomHandler c) {} public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, dynamic d) : this() {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute }); comp.VerifyDiagnostics( // (4,6): error CS8953: An interpolated string handler construction cannot use dynamic. Manually construct an instance of 'CustomHandler'. // M(d, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, @"$""""").WithArguments("CustomHandler").WithLocation(4, 6) ); } [Fact] public void DynamicConstruction_02() { var code = @" using System.Runtime.CompilerServices; int i = 1; M(i, $""""); void M(dynamic d, [InterpolatedStringHandlerArgument(""d"")]CustomHandler c) {} public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, dynamic d) : this() {} } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false); var comp = CreateCompilation(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute }); comp.VerifyDiagnostics( // (4,6): error CS8953: An interpolated string handler construction cannot use dynamic. Manually construct an instance of 'CustomHandler'. // M(d, $""); Diagnostic(ErrorCode.ERR_InterpolatedStringHandlerCreationCannotUseDynamic, @"$""""").WithArguments("CustomHandler").WithLocation(4, 6) ); } [Fact] public void DynamicConstruction_03() { var code = @" using System; using System.Runtime.CompilerServices; int i = 1; M(i, $""""); void M(int i, [InterpolatedStringHandlerArgument(""i"")]CustomHandler c) {} public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, dynamic d) : this(literalLength, formattedCount) { Console.WriteLine(""d:"" + d.ToString()); } } "; var handler = GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns: false, includeOneTimeHelpers: false); var comp = CreateCompilation(new[] { code, handler, InterpolatedStringHandlerArgumentAttribute, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "d:1"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 22 (0x16) .maxstack 4 .locals init (int V_0) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.0 IL_0004: ldc.i4.0 IL_0005: ldloc.0 IL_0006: box ""int"" IL_000b: newobj ""CustomHandler..ctor(int, int, dynamic)"" IL_0010: call ""void <Program>$.<<Main>$>g__M|0_0(int, CustomHandler)"" IL_0015: ret } "); } [Fact] public void DynamicConstruction_04() { var code = @" using System; using System.Runtime.CompilerServices; M($""""); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(dynamic literalLength, int formattedCount) { Console.WriteLine(""ctor""); } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "ctor"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 18 (0x12) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: box ""int"" IL_0006: ldc.i4.0 IL_0007: newobj ""CustomHandler..ctor(dynamic, int)"" IL_000c: call ""void <Program>$.<<Main>$>g__M|0_0(CustomHandler)"" IL_0011: ret } "); } [Fact] public void DynamicConstruction_05() { var code = @" using System; using System.Runtime.CompilerServices; M($""""); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { Console.WriteLine(""ctor""); } public CustomHandler(dynamic literalLength, int formattedCount) { throw null; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "ctor"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: ldc.i4.0 IL_0002: newobj ""CustomHandler..ctor(int, int)"" IL_0007: call ""void <Program>$.<<Main>$>g__M|0_0(CustomHandler)"" IL_000c: ret } "); } [Fact] public void DynamicConstruction_06() { var code = @" using System; using System.Runtime.CompilerServices; M($""Literal""); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } public void AppendLiteral(dynamic d) { Console.WriteLine(""AppendLiteral""); } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "AppendLiteral"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 28 (0x1c) .maxstack 3 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.7 IL_0003: ldc.i4.0 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldstr ""Literal"" IL_0010: call ""void CustomHandler.AppendLiteral(dynamic)"" IL_0015: ldloc.0 IL_0016: call ""void <Program>$.<<Main>$>g__M|0_0(CustomHandler)"" IL_001b: ret } "); } [Fact] public void DynamicConstruction_07() { var code = @" using System; using System.Runtime.CompilerServices; M($""{1}""); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } public void AppendFormatted(dynamic d) { Console.WriteLine(""AppendFormatted""); } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: "AppendFormatted"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 29 (0x1d) .maxstack 3 .locals init (CustomHandler V_0) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.0 IL_0003: ldc.i4.1 IL_0004: call ""CustomHandler..ctor(int, int)"" IL_0009: ldloca.s V_0 IL_000b: ldc.i4.1 IL_000c: box ""int"" IL_0011: call ""void CustomHandler.AppendFormatted(dynamic)"" IL_0016: ldloc.0 IL_0017: call ""void <Program>$.<<Main>$>g__M|0_0(CustomHandler)"" IL_001c: ret } "); } [Fact] public void DynamicConstruction_08() { var code = @" using System; using System.Runtime.CompilerServices; dynamic d = 1; M($""literal{d}""); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } public void AppendLiteral(dynamic d) { Console.WriteLine(""AppendLiteral""); } public void AppendFormatted(dynamic d) { Console.WriteLine(""AppendFormatted""); } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: @" AppendLiteral AppendFormatted"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 128 (0x80) .maxstack 9 .locals init (object V_0, //d CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldloca.s V_1 IL_0009: ldc.i4.7 IL_000a: ldc.i4.1 IL_000b: call ""CustomHandler..ctor(int, int)"" IL_0010: ldloca.s V_1 IL_0012: ldstr ""literal"" IL_0017: call ""void CustomHandler.AppendLiteral(dynamic)"" IL_001c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000002}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> <Program>$.<>o__0.<>p__0"" IL_0021: brtrue.s IL_0062 IL_0023: ldc.i4 0x100 IL_0028: ldstr ""AppendFormatted"" IL_002d: ldnull IL_002e: ldtoken ""<Program>$"" IL_0033: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0038: ldc.i4.2 IL_0039: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_003e: dup IL_003f: ldc.i4.0 IL_0040: ldc.i4.s 9 IL_0042: ldnull IL_0043: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0048: stelem.ref IL_0049: dup IL_004a: ldc.i4.1 IL_004b: ldc.i4.0 IL_004c: ldnull IL_004d: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0052: stelem.ref IL_0053: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0058: call ""System.Runtime.CompilerServices.CallSite<<>A{00000002}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> System.Runtime.CompilerServices.CallSite<<>A{00000002}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_005d: stsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000002}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> <Program>$.<>o__0.<>p__0"" IL_0062: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000002}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> <Program>$.<>o__0.<>p__0"" IL_0067: ldfld ""<>A{00000002}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic> System.Runtime.CompilerServices.CallSite<<>A{00000002}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>>.Target"" IL_006c: ldsfld ""System.Runtime.CompilerServices.CallSite<<>A{00000002}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>> <Program>$.<>o__0.<>p__0"" IL_0071: ldloca.s V_1 IL_0073: ldloc.0 IL_0074: callvirt ""void <>A{00000002}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, ref CustomHandler, dynamic)"" IL_0079: ldloc.1 IL_007a: call ""void <Program>$.<<Main>$>g__M|0_0(CustomHandler)"" IL_007f: ret } "); } [Fact] public void DynamicConstruction_09() { var code = @" using System; using System.Runtime.CompilerServices; dynamic d = 1; M($""literal{d}""); void M(CustomHandler c) {} [InterpolatedStringHandler] public struct CustomHandler { public CustomHandler(int literalLength, int formattedCount) { } public bool AppendLiteral(dynamic d) { Console.WriteLine(""AppendLiteral""); return true; } public bool AppendFormatted(dynamic d) { Console.WriteLine(""AppendFormatted""); return true; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.Mscorlib45AndCSharp); var verifier = CompileAndVerify(comp, expectedOutput: @" AppendLiteral AppendFormatted"); verifier.VerifyDiagnostics(); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 196 (0xc4) .maxstack 11 .locals init (object V_0, //d CustomHandler V_1) IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: stloc.0 IL_0007: ldloca.s V_1 IL_0009: ldc.i4.7 IL_000a: ldc.i4.1 IL_000b: call ""CustomHandler..ctor(int, int)"" IL_0010: ldloca.s V_1 IL_0012: ldstr ""literal"" IL_0017: call ""bool CustomHandler.AppendLiteral(dynamic)"" IL_001c: brfalse IL_00bb IL_0021: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <Program>$.<>o__0.<>p__1"" IL_0026: brtrue.s IL_004c IL_0028: ldc.i4.0 IL_0029: ldtoken ""bool"" IL_002e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0033: ldtoken ""<Program>$"" IL_0038: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_003d: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.Convert(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, System.Type, System.Type)"" IL_0042: call ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0047: stsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <Program>$.<>o__0.<>p__1"" IL_004c: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <Program>$.<>o__0.<>p__1"" IL_0051: ldfld ""System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool> System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>>.Target"" IL_0056: ldsfld ""System.Runtime.CompilerServices.CallSite<System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>> <Program>$.<>o__0.<>p__1"" IL_005b: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000002}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> <Program>$.<>o__0.<>p__0"" IL_0060: brtrue.s IL_009d IL_0062: ldc.i4.0 IL_0063: ldstr ""AppendFormatted"" IL_0068: ldnull IL_0069: ldtoken ""<Program>$"" IL_006e: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_0073: ldc.i4.2 IL_0074: newarr ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo"" IL_0079: dup IL_007a: ldc.i4.0 IL_007b: ldc.i4.s 9 IL_007d: ldnull IL_007e: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_0083: stelem.ref IL_0084: dup IL_0085: ldc.i4.1 IL_0086: ldc.i4.0 IL_0087: ldnull IL_0088: call ""Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfoFlags, string)"" IL_008d: stelem.ref IL_008e: call ""System.Runtime.CompilerServices.CallSiteBinder Microsoft.CSharp.RuntimeBinder.Binder.InvokeMember(Microsoft.CSharp.RuntimeBinder.CSharpBinderFlags, string, System.Collections.Generic.IEnumerable<System.Type>, System.Type, System.Collections.Generic.IEnumerable<Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo>)"" IL_0093: call ""System.Runtime.CompilerServices.CallSite<<>F{00000002}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> System.Runtime.CompilerServices.CallSite<<>F{00000002}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>>.Create(System.Runtime.CompilerServices.CallSiteBinder)"" IL_0098: stsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000002}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> <Program>$.<>o__0.<>p__0"" IL_009d: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000002}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> <Program>$.<>o__0.<>p__0"" IL_00a2: ldfld ""<>F{00000002}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic> System.Runtime.CompilerServices.CallSite<<>F{00000002}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>>.Target"" IL_00a7: ldsfld ""System.Runtime.CompilerServices.CallSite<<>F{00000002}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>> <Program>$.<>o__0.<>p__0"" IL_00ac: ldloca.s V_1 IL_00ae: ldloc.0 IL_00af: callvirt ""dynamic <>F{00000002}<System.Runtime.CompilerServices.CallSite, CustomHandler, dynamic, dynamic>.Invoke(System.Runtime.CompilerServices.CallSite, ref CustomHandler, dynamic)"" IL_00b4: callvirt ""bool System.Func<System.Runtime.CompilerServices.CallSite, dynamic, bool>.Invoke(System.Runtime.CompilerServices.CallSite, dynamic)"" IL_00b9: br.s IL_00bc IL_00bb: ldc.i4.0 IL_00bc: pop IL_00bd: ldloc.1 IL_00be: call ""void <Program>$.<<Main>$>g__M|0_0(CustomHandler)"" IL_00c3: ret } "); } [Fact] public void RefEscape_01() { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount) : this() {} public void AppendFormatted(Span<char> s) => this.s = s; public static CustomHandler M() { Span<char> s = stackalloc char[10]; return $""{s}""; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (17,19): error CS8352: Cannot use local 's' in this context because it may expose referenced variables outside of their declaration scope // return $"{s}"; Diagnostic(ErrorCode.ERR_EscapeLocal, "s").WithArguments("s").WithLocation(17, 19) ); } [Fact] public void RefEscape_02() { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount) : this() {} public void AppendFormatted(Span<char> s) => this.s = s; public static ref CustomHandler M() { Span<char> s = stackalloc char[10]; return $""{s}""; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (17,9): error CS8150: By-value returns may only be used in methods that return by value // return $"{s}"; Diagnostic(ErrorCode.ERR_MustHaveRefReturn, "return").WithLocation(17, 9) ); } [Fact] public void RefEscape_03() { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount) : this() {} public void AppendFormatted(Span<char> s) => this.s = s; public static ref CustomHandler M() { Span<char> s = stackalloc char[10]; return ref $""{s}""; } } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (17,20): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // return ref $"{s}"; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, @"$""{s}""").WithLocation(17, 20) ); } [Fact] public void RefEscape_04() { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { S1 s1; public CustomHandler(int literalLength, int formattedCount, ref S1 s1) : this() { this.s1 = s1; } public void AppendFormatted(Span<char> s) => this.s1.s = s; public static void M(ref S1 s1) { Span<char> s = stackalloc char[10]; M2(ref s1, $""{s}""); } public static void M2(ref S1 s1, [InterpolatedStringHandlerArgument(""s1"")] ref CustomHandler handler) {} } public ref struct S1 { public Span<char> s; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (17,9): error CS8350: This combination of arguments to 'CustomHandler.M2(ref S1, ref CustomHandler)' is disallowed because it may expose variables referenced by parameter 'handler' outside of their declaration scope // M2(ref s1, $"{s}"); Diagnostic(ErrorCode.ERR_CallArgMixing, @"M2(ref s1, $""{s}"")").WithArguments("CustomHandler.M2(ref S1, ref CustomHandler)", "handler").WithLocation(17, 9), // (17,23): error CS8352: Cannot use local 's' in this context because it may expose referenced variables outside of their declaration scope // M2(ref s1, $"{s}"); Diagnostic(ErrorCode.ERR_EscapeLocal, "s").WithArguments("s").WithLocation(17, 23) ); } [Fact] public void RefEscape_05() { var code = @" using System; using System.Runtime.CompilerServices; [InterpolatedStringHandler] public ref struct CustomHandler { Span<char> s; public CustomHandler(int literalLength, int formattedCount, ref Span<char> s) : this() { this.s = s; } public void AppendFormatted(S1 s1) => s1.s = this.s; public static void M(ref S1 s1) { Span<char> s = stackalloc char[10]; M2(ref s, $""{s1}""); } public static void M2(ref Span<char> s, [InterpolatedStringHandlerArgument(""s"")] CustomHandler handler) {} } public ref struct S1 { public Span<char> s; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics(); } [Fact] public void RefEscape_06() { var code = @" using System; using System.Runtime.CompilerServices; Span<char> s = stackalloc char[5]; Span<char> s2 = stackalloc char[10]; s.TryWrite($""{s2}""); public static class MemoryExtensions { public static bool TryWrite(this Span<char> span, [InterpolatedStringHandlerArgument(""span"")] CustomHandler builder) => true; } [InterpolatedStringHandler] public ref struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, Span<char> s) : this() { } public bool AppendFormatted(Span<char> s) => true; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics(); } [Fact] public void RefEscape_07() { var code = @" using System; using System.Runtime.CompilerServices; Span<char> s = stackalloc char[5]; Span<char> s2 = stackalloc char[10]; s.TryWrite($""{s2}""); public static class MemoryExtensions { public static bool TryWrite(this Span<char> span, [InterpolatedStringHandlerArgument(""span"")] ref CustomHandler builder) => true; } [InterpolatedStringHandler] public ref struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, Span<char> s) : this() { } public bool AppendFormatted(Span<char> s) => true; } "; var comp = CreateCompilation(new[] { code, InterpolatedStringHandlerAttribute, InterpolatedStringHandlerArgumentAttribute }, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics(); } [Fact, WorkItem(54703, "https://github.com/dotnet/roslyn/issues/54703")] public void BracesAreEscaped_01() { var code = @" int i = 1; System.Console.WriteLine($""{{ {i} }}"");"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringHandlerDefinition(includeSpanOverloads: false, useDefaultParameters: false, useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" { value:1 }"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 56 (0x38) .maxstack 3 .locals init (int V_0, //i System.Runtime.CompilerServices.DefaultInterpolatedStringHandler V_1) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_1 IL_0004: ldc.i4.4 IL_0005: ldc.i4.1 IL_0006: call ""System.Runtime.CompilerServices.DefaultInterpolatedStringHandler..ctor(int, int)"" IL_000b: ldloca.s V_1 IL_000d: ldstr ""{ "" IL_0012: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_0017: ldloca.s V_1 IL_0019: ldloc.0 IL_001a: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendFormatted<int>(int)"" IL_001f: ldloca.s V_1 IL_0021: ldstr "" }"" IL_0026: call ""void System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.AppendLiteral(string)"" IL_002b: ldloca.s V_1 IL_002d: call ""string System.Runtime.CompilerServices.DefaultInterpolatedStringHandler.ToStringAndClear()"" IL_0032: call ""void System.Console.WriteLine(string)"" IL_0037: ret } "); } [Fact, WorkItem(54703, "https://github.com/dotnet/roslyn/issues/54703")] public void BracesAreEscaped_02() { var code = @" int i = 1; CustomHandler c = $""{{ {i} }}""; System.Console.WriteLine(c.ToString());"; var comp = CreateCompilation(new[] { code, GetInterpolatedStringCustomHandlerType("CustomHandler", "struct", useBoolReturns: false) }); var verifier = CompileAndVerify(comp, expectedOutput: @" literal:{ value:1 alignment:0 format: literal: }"); verifier.VerifyIL("<top-level-statements-entry-point>", @" { // Code size 71 (0x47) .maxstack 4 .locals init (int V_0, //i CustomHandler V_1, //c CustomHandler V_2) IL_0000: ldc.i4.1 IL_0001: stloc.0 IL_0002: ldloca.s V_2 IL_0004: ldc.i4.4 IL_0005: ldc.i4.1 IL_0006: call ""CustomHandler..ctor(int, int)"" IL_000b: ldloca.s V_2 IL_000d: ldstr ""{ "" IL_0012: call ""void CustomHandler.AppendLiteral(string)"" IL_0017: ldloca.s V_2 IL_0019: ldloc.0 IL_001a: box ""int"" IL_001f: ldc.i4.0 IL_0020: ldnull IL_0021: call ""void CustomHandler.AppendFormatted(object, int, string)"" IL_0026: ldloca.s V_2 IL_0028: ldstr "" }"" IL_002d: call ""void CustomHandler.AppendLiteral(string)"" IL_0032: ldloc.2 IL_0033: stloc.1 IL_0034: ldloca.s V_1 IL_0036: constrained. ""CustomHandler"" IL_003c: callvirt ""string object.ToString()"" IL_0041: call ""void System.Console.WriteLine(string)"" IL_0046: ret } "); } } }
1
dotnet/roslyn
55,125
Don't use DefaultInterpolatedStringHandler in expression trees
Introduces a binder flag to track whether we are currently in an expression tree or not. Fixes https://github.com/dotnet/roslyn/issues/55114.
333fred
2021-07-26T22:08:39Z
2021-07-27T19:33:24Z
5840335153dcca42570a853cdacd06d660fe9596
cfc12ce93ce377c4b9581ccf88403e6740d63977
Don't use DefaultInterpolatedStringHandler in expression trees. Introduces a binder flag to track whether we are currently in an expression tree or not. Fixes https://github.com/dotnet/roslyn/issues/55114.
./src/Features/CSharp/Portable/MakeLocalFunctionStatic/MakeLocalFunctionStaticCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.MakeLocalFunctionStatic { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.MakeLocalFunctionStatic), Shared] internal class MakeLocalFunctionStaticCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public MakeLocalFunctionStaticCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(IDEDiagnosticIds.MakeLocalFunctionStaticDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeQuality; public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(new MyCodeAction( c => FixAsync(context.Document, context.Diagnostics[0], c)), context.Diagnostics); return Task.CompletedTask; } protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var localFunctions = diagnostics.SelectAsArray(d => d.AdditionalLocations[0].FindNode(cancellationToken)); foreach (var localFunction in localFunctions) { editor.ReplaceNode( localFunction, (current, generator) => MakeLocalFunctionStaticCodeFixHelper.AddStaticModifier(current, generator)); } return Task.CompletedTask; } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpAnalyzersResources.Make_local_function_static, createChangedDocument, CSharpAnalyzersResources.Make_local_function_static) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.MakeLocalFunctionStatic { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.MakeLocalFunctionStatic), Shared] internal class MakeLocalFunctionStaticCodeFixProvider : SyntaxEditorBasedCodeFixProvider { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public MakeLocalFunctionStaticCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(IDEDiagnosticIds.MakeLocalFunctionStaticDiagnosticId); internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeQuality; public override Task RegisterCodeFixesAsync(CodeFixContext context) { context.RegisterCodeFix(new MyCodeAction( c => FixAsync(context.Document, context.Diagnostics[0], c)), context.Diagnostics); return Task.CompletedTask; } protected override Task FixAllAsync( Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken) { var localFunctions = diagnostics.SelectAsArray(d => d.AdditionalLocations[0].FindNode(cancellationToken)); foreach (var localFunction in localFunctions) { editor.ReplaceNode( localFunction, (current, generator) => MakeLocalFunctionStaticCodeFixHelper.AddStaticModifier(current, generator)); } return Task.CompletedTask; } private class MyCodeAction : CustomCodeActions.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpAnalyzersResources.Make_local_function_static, createChangedDocument, CSharpAnalyzersResources.Make_local_function_static) { } } } }
-1
dotnet/roslyn
55,125
Don't use DefaultInterpolatedStringHandler in expression trees
Introduces a binder flag to track whether we are currently in an expression tree or not. Fixes https://github.com/dotnet/roslyn/issues/55114.
333fred
2021-07-26T22:08:39Z
2021-07-27T19:33:24Z
5840335153dcca42570a853cdacd06d660fe9596
cfc12ce93ce377c4b9581ccf88403e6740d63977
Don't use DefaultInterpolatedStringHandler in expression trees. Introduces a binder flag to track whether we are currently in an expression tree or not. Fixes https://github.com/dotnet/roslyn/issues/55114.
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/CPS/IWorkspaceProjectContextFactory.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; namespace Microsoft.VisualStudio.LanguageServices.ProjectSystem { /// <summary> /// Factory to create a project context for a new Workspace project that can be initialized on a background thread. /// </summary> internal interface IWorkspaceProjectContextFactory { /// <inheritdoc cref="CreateProjectContextAsync"/> [Obsolete("Use CreateProjectContextAsync instead")] IWorkspaceProjectContext CreateProjectContext(string languageName, string projectUniqueName, string projectFilePath, Guid projectGuid, object? hierarchy, string? binOutputPath); /// <inheritdoc cref="CreateProjectContextAsync"/> [Obsolete("Use CreateProjectContextAsync instead")] IWorkspaceProjectContext CreateProjectContext(string languageName, string projectUniqueName, string projectFilePath, Guid projectGuid, object? hierarchy, string? binOutputPath, string? assemblyName); /// <summary> /// Creates and initializes a new Workspace project and returns a <see /// cref="IWorkspaceProjectContext"/> to lazily initialize the properties and items for the /// project. This method guarantees that either the project is added (and the returned task /// completes) or cancellation is observed and no project is added. /// </summary> /// <param name="languageName">Project language.</param> /// <param name="projectUniqueName">Unique name for the project.</param> /// <param name="projectFilePath">Full path to the project file for the project.</param> /// <param name="projectGuid">Project guid.</param> /// <param name="hierarchy">The IVsHierarchy for the project; this is used to track linked files across multiple projects when determining contexts.</param> /// <param name="binOutputPath">Initial project binary output path.</param> Task<IWorkspaceProjectContext> CreateProjectContextAsync( string languageName, string projectUniqueName, string projectFilePath, Guid projectGuid, object? hierarchy, string? binOutputPath, string? assemblyName, 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; using System.Threading; using System.Threading.Tasks; namespace Microsoft.VisualStudio.LanguageServices.ProjectSystem { /// <summary> /// Factory to create a project context for a new Workspace project that can be initialized on a background thread. /// </summary> internal interface IWorkspaceProjectContextFactory { /// <inheritdoc cref="CreateProjectContextAsync"/> [Obsolete("Use CreateProjectContextAsync instead")] IWorkspaceProjectContext CreateProjectContext(string languageName, string projectUniqueName, string projectFilePath, Guid projectGuid, object? hierarchy, string? binOutputPath); /// <inheritdoc cref="CreateProjectContextAsync"/> [Obsolete("Use CreateProjectContextAsync instead")] IWorkspaceProjectContext CreateProjectContext(string languageName, string projectUniqueName, string projectFilePath, Guid projectGuid, object? hierarchy, string? binOutputPath, string? assemblyName); /// <summary> /// Creates and initializes a new Workspace project and returns a <see /// cref="IWorkspaceProjectContext"/> to lazily initialize the properties and items for the /// project. This method guarantees that either the project is added (and the returned task /// completes) or cancellation is observed and no project is added. /// </summary> /// <param name="languageName">Project language.</param> /// <param name="projectUniqueName">Unique name for the project.</param> /// <param name="projectFilePath">Full path to the project file for the project.</param> /// <param name="projectGuid">Project guid.</param> /// <param name="hierarchy">The IVsHierarchy for the project; this is used to track linked files across multiple projects when determining contexts.</param> /// <param name="binOutputPath">Initial project binary output path.</param> Task<IWorkspaceProjectContext> CreateProjectContextAsync( string languageName, string projectUniqueName, string projectFilePath, Guid projectGuid, object? hierarchy, string? binOutputPath, string? assemblyName, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
55,125
Don't use DefaultInterpolatedStringHandler in expression trees
Introduces a binder flag to track whether we are currently in an expression tree or not. Fixes https://github.com/dotnet/roslyn/issues/55114.
333fred
2021-07-26T22:08:39Z
2021-07-27T19:33:24Z
5840335153dcca42570a853cdacd06d660fe9596
cfc12ce93ce377c4b9581ccf88403e6740d63977
Don't use DefaultInterpolatedStringHandler in expression trees. Introduces a binder flag to track whether we are currently in an expression tree or not. Fixes https://github.com/dotnet/roslyn/issues/55114.
./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
55,125
Don't use DefaultInterpolatedStringHandler in expression trees
Introduces a binder flag to track whether we are currently in an expression tree or not. Fixes https://github.com/dotnet/roslyn/issues/55114.
333fred
2021-07-26T22:08:39Z
2021-07-27T19:33:24Z
5840335153dcca42570a853cdacd06d660fe9596
cfc12ce93ce377c4b9581ccf88403e6740d63977
Don't use DefaultInterpolatedStringHandler in expression trees. Introduces a binder flag to track whether we are currently in an expression tree or not. Fixes https://github.com/dotnet/roslyn/issues/55114.
./src/Workspaces/Remote/ServiceHub/Host/Storage/RemoteCloudCacheStorageServiceFactory.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; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Remote.Host; using Microsoft.CodeAnalysis.Storage; using Microsoft.CodeAnalysis.Storage.CloudCache; using Microsoft.VisualStudio; using Microsoft.VisualStudio.LanguageServices.Storage; using Microsoft.VisualStudio.RpcContracts.Caching; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote.Storage { [ExportWorkspaceService(typeof(ICloudCacheStorageServiceFactory), WorkspaceKind.RemoteWorkspace), Shared] internal class RemoteCloudCacheStorageServiceFactory : ICloudCacheStorageServiceFactory { private readonly IGlobalServiceBroker _globalServiceBroker; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RemoteCloudCacheStorageServiceFactory(IGlobalServiceBroker globalServiceBroker) { _globalServiceBroker = globalServiceBroker; } public AbstractPersistentStorageService Create(IPersistentStorageLocationService locationService) => new RemoteCloudCachePersistentStorageService(_globalServiceBroker, locationService); private class RemoteCloudCachePersistentStorageService : AbstractCloudCachePersistentStorageService { private readonly IGlobalServiceBroker _globalServiceBroker; public RemoteCloudCachePersistentStorageService(IGlobalServiceBroker globalServiceBroker, IPersistentStorageLocationService locationService) : base(locationService) { _globalServiceBroker = globalServiceBroker; } protected override void DisposeCacheService(ICacheService cacheService) { if (cacheService is IAsyncDisposable asyncDisposable) { asyncDisposable.DisposeAsync().AsTask().Wait(); } else if (cacheService is IDisposable disposable) { disposable.Dispose(); } } protected override async ValueTask<ICacheService> CreateCacheServiceAsync(CancellationToken cancellationToken) { var serviceBroker = _globalServiceBroker.Instance; #pragma warning disable ISB001 // Dispose of proxies // cache service will be disposed inside RemoteCloudCacheService.Dispose var cacheService = await serviceBroker.GetProxyAsync<ICacheService>(VisualStudioServices.VS2019_10.CacheService, cancellationToken: cancellationToken).ConfigureAwait(false); #pragma warning restore ISB001 // Dispose of proxies Contract.ThrowIfNull(cacheService); return cacheService; } } } }
// Licensed to the .NET Foundation under one or more 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; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Remote.Host; using Microsoft.CodeAnalysis.Storage; using Microsoft.CodeAnalysis.Storage.CloudCache; using Microsoft.VisualStudio; using Microsoft.VisualStudio.LanguageServices.Storage; using Microsoft.VisualStudio.RpcContracts.Caching; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Remote.Storage { [ExportWorkspaceService(typeof(ICloudCacheStorageServiceFactory), WorkspaceKind.RemoteWorkspace), Shared] internal class RemoteCloudCacheStorageServiceFactory : ICloudCacheStorageServiceFactory { private readonly IGlobalServiceBroker _globalServiceBroker; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public RemoteCloudCacheStorageServiceFactory(IGlobalServiceBroker globalServiceBroker) { _globalServiceBroker = globalServiceBroker; } public AbstractPersistentStorageService Create(IPersistentStorageLocationService locationService) => new RemoteCloudCachePersistentStorageService(_globalServiceBroker, locationService); private class RemoteCloudCachePersistentStorageService : AbstractCloudCachePersistentStorageService { private readonly IGlobalServiceBroker _globalServiceBroker; public RemoteCloudCachePersistentStorageService(IGlobalServiceBroker globalServiceBroker, IPersistentStorageLocationService locationService) : base(locationService) { _globalServiceBroker = globalServiceBroker; } protected override void DisposeCacheService(ICacheService cacheService) { if (cacheService is IAsyncDisposable asyncDisposable) { asyncDisposable.DisposeAsync().AsTask().Wait(); } else if (cacheService is IDisposable disposable) { disposable.Dispose(); } } protected override async ValueTask<ICacheService> CreateCacheServiceAsync(CancellationToken cancellationToken) { var serviceBroker = _globalServiceBroker.Instance; #pragma warning disable ISB001 // Dispose of proxies // cache service will be disposed inside RemoteCloudCacheService.Dispose var cacheService = await serviceBroker.GetProxyAsync<ICacheService>(VisualStudioServices.VS2019_10.CacheService, cancellationToken: cancellationToken).ConfigureAwait(false); #pragma warning restore ISB001 // Dispose of proxies Contract.ThrowIfNull(cacheService); return cacheService; } } } }
-1
dotnet/roslyn
55,125
Don't use DefaultInterpolatedStringHandler in expression trees
Introduces a binder flag to track whether we are currently in an expression tree or not. Fixes https://github.com/dotnet/roslyn/issues/55114.
333fred
2021-07-26T22:08:39Z
2021-07-27T19:33:24Z
5840335153dcca42570a853cdacd06d660fe9596
cfc12ce93ce377c4b9581ccf88403e6740d63977
Don't use DefaultInterpolatedStringHandler in expression trees. Introduces a binder flag to track whether we are currently in an expression tree or not. Fixes https://github.com/dotnet/roslyn/issues/55114.
./src/Compilers/Core/Portable/Compilation/SemanticModelProvider.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 { /// <summary> /// Provides semantic models for syntax trees in a compilation. /// This provider can be attached to a compilation, see <see cref="Compilation.SemanticModelProvider"/>. /// </summary> internal abstract class SemanticModelProvider { /// <summary> /// Gets a <see cref="SemanticModel"/> for the given <paramref name="tree"/> that belongs to the given <paramref name="compilation"/>. /// </summary> public abstract SemanticModel GetSemanticModel(SyntaxTree tree, Compilation compilation, bool ignoreAccessibility = 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. namespace Microsoft.CodeAnalysis { /// <summary> /// Provides semantic models for syntax trees in a compilation. /// This provider can be attached to a compilation, see <see cref="Compilation.SemanticModelProvider"/>. /// </summary> internal abstract class SemanticModelProvider { /// <summary> /// Gets a <see cref="SemanticModel"/> for the given <paramref name="tree"/> that belongs to the given <paramref name="compilation"/>. /// </summary> public abstract SemanticModel GetSemanticModel(SyntaxTree tree, Compilation compilation, bool ignoreAccessibility = false); } }
-1
dotnet/roslyn
55,125
Don't use DefaultInterpolatedStringHandler in expression trees
Introduces a binder flag to track whether we are currently in an expression tree or not. Fixes https://github.com/dotnet/roslyn/issues/55114.
333fred
2021-07-26T22:08:39Z
2021-07-27T19:33:24Z
5840335153dcca42570a853cdacd06d660fe9596
cfc12ce93ce377c4b9581ccf88403e6740d63977
Don't use DefaultInterpolatedStringHandler in expression trees. Introduces a binder flag to track whether we are currently in an expression tree or not. Fixes https://github.com/dotnet/roslyn/issues/55114.
./src/Compilers/Core/CommandLine/ConsoleUtil.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; using System; using System.IO; using System.Text; namespace Microsoft.CodeAnalysis.CommandLine { internal static class ConsoleUtil { private static readonly Encoding s_utf8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); /// <summary> /// This will update the <see cref="Console.Out"/> value to have UTF8 encoding for the duration of the /// provided call back. The newly created <see cref="TextWriter"/> will be passed down to the callback. /// </summary> internal static T RunWithUtf8Output<T>(Func<TextWriter, T> func) { Encoding savedEncoding = Console.OutputEncoding; try { Console.OutputEncoding = s_utf8Encoding; return func(Console.Out); } finally { try { Console.OutputEncoding = savedEncoding; } catch { // Nothing to do if we can't reset the console. } } } internal static T RunWithUtf8Output<T>(bool utf8Output, TextWriter textWriter, Func<TextWriter, T> func) { if (utf8Output && textWriter.Encoding.CodePage != s_utf8Encoding.CodePage) { if (textWriter != Console.Out) { throw new InvalidOperationException("Utf8Output is only supported when writing to Console.Out"); } return RunWithUtf8Output(func); } return func(textWriter); } } }
// Licensed to the .NET Foundation under one or more 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; using System; using System.IO; using System.Text; namespace Microsoft.CodeAnalysis.CommandLine { internal static class ConsoleUtil { private static readonly Encoding s_utf8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); /// <summary> /// This will update the <see cref="Console.Out"/> value to have UTF8 encoding for the duration of the /// provided call back. The newly created <see cref="TextWriter"/> will be passed down to the callback. /// </summary> internal static T RunWithUtf8Output<T>(Func<TextWriter, T> func) { Encoding savedEncoding = Console.OutputEncoding; try { Console.OutputEncoding = s_utf8Encoding; return func(Console.Out); } finally { try { Console.OutputEncoding = savedEncoding; } catch { // Nothing to do if we can't reset the console. } } } internal static T RunWithUtf8Output<T>(bool utf8Output, TextWriter textWriter, Func<TextWriter, T> func) { if (utf8Output && textWriter.Encoding.CodePage != s_utf8Encoding.CodePage) { if (textWriter != Console.Out) { throw new InvalidOperationException("Utf8Output is only supported when writing to Console.Out"); } return RunWithUtf8Output(func); } return func(textWriter); } } }
-1