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 < 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 > 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 <see> or <seealso> documentation comment tag).
/// For example, the M in <see cref="M" />.
/// </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<T>", 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<T>" 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 < 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 > 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 <see> or <seealso> documentation comment tag).
/// For example, the M in <see cref="M" />.
/// </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<T>", 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<T>" 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.
$ PE L xN ! ' @ @ @ & |