Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions eng/validate-roslyn-sdk-samples.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ $buildArgs = @(
$solutionPath
"-c", $configuration
"--no-incremental"
"--warnaserror"
"/p:RoslynEnforceCodeStyle=true"
)

if ($ci) {
Expand Down
3 changes: 0 additions & 3 deletions src/RoslynSdk/Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,6 @@
<Import Project="$([MSBuild]::GetPathOfFileAbove('Directory.Packages.props', '$(MSBuildThisFileDirectory)../'))" />

<PropertyGroup>
<!-- Preserve the older dependency versions required for Roslyn 4.12 compatibility. -->
<CentralPackageTransitivePinningEnabled>false</CentralPackageTransitivePinningEnabled>

<RoslynSdkNuGetApiVersion Condition="'$(TargetFramework)' == 'net472' OR '$(TargetFramework)' == '$(NetRoslyn)'">7.0.3</RoslynSdkNuGetApiVersion>
<RoslynSdkNuGetApiVersion Condition="'$(RoslynSdkNuGetApiVersion)' == ''">6.3.4</RoslynSdkNuGetApiVersion>
</PropertyGroup>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<Project>
<Import Project="$([MSBuild]::GetPathOfFileAbove('Directory.Packages.props', '$(MSBuildThisFileDirectory)../'))" />

<PropertyGroup>
<!--
These packages compile against Roslyn 4.12 and support downlevel consumers. Transitive pinning
would promote repository-wide package versions into their package dependencies, raising the
minimum dependency versions required by consumers.
-->
<CentralPackageTransitivePinningEnabled>false</CentralPackageTransitivePinningEnabled>
</PropertyGroup>
</Project>
38 changes: 6 additions & 32 deletions src/RoslynSdk/Samples/.editorconfig
Original file line number Diff line number Diff line change
@@ -1,37 +1,11 @@
# Avoid "this." and "Me." if not necessary
dotnet_style_qualification_for_field = true:error
dotnet_style_qualification_for_property = true:error
dotnet_style_qualification_for_method = true:error
dotnet_style_qualification_for_event = true:error
[*.{cs,vb}]

# Use language keywords instead of framework type names for type references
dotnet_style_predefined_type_for_locals_parameters_members = true:error
dotnet_style_predefined_type_for_member_access = true:error
# Samples consume public Roslyn APIs and cannot use the internal alternatives required by the main repo.
dotnet_diagnostic.RS0030.severity = none

# Suggest more modern language features when available
dotnet_style_object_initializer = true:error
dotnet_style_collection_initializer = true:error
dotnet_style_coalesce_expression = true:error
dotnet_style_null_propagation = true:error
dotnet_style_explicit_tuple_names = true:error

# CSharp code style settings:
[*.cs]
# Prefer "var" everywhere
csharp_style_var_for_built_in_types = false:error
csharp_style_var_when_type_is_apparent = false:error
csharp_style_var_elsewhere = false:error

# Suggest more modern language features when available
csharp_style_pattern_matching_over_is_with_cast_check = true:error
csharp_style_pattern_matching_over_as_with_null_check = true:error
csharp_style_inlined_variable_declaration = true:error
csharp_style_throw_expression = true:error
csharp_style_conditional_delegate_call = true:error
# Samples do not use the repository-internal MEF construction convention.
dotnet_diagnostic.RS0033.severity = none
dotnet_diagnostic.RS0034.severity = none

# Samples preserve unused parameters to demonstrate extensibility points.
dotnet_diagnostic.IDE0060.severity = none

# Require the repository license header in all sample source files.
file_header_template = Licensed to the .NET Foundation under one or more agreements.\nThe .NET Foundation licenses this file to you under the MIT license.\nSee the LICENSE file in the project root for more information.
dotnet_diagnostic.IDE0073.severity = error
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ namespace Sample.Analyzers
class SimpleAdditionalFileAnalyzer : DiagnosticAnalyzer
{
private const string Title = "Type name contains invalid term";
private const string MessageFormat = "The term '{0}' is not allowed in a type name.";
private const string MessageFormat = "The term '{0}' is not allowed in a type name";

private static readonly DiagnosticDescriptor Rule =
new DiagnosticDescriptor(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ namespace Sample.Analyzers
class XmlAdditionalFileAnalyzer : DiagnosticAnalyzer
{
private const string Title = "Type name contains invalid term";
private const string MessageFormat = "The term '{0}' is not allowed in a type name.";
private const string MessageFormat = "The term '{0}' is not allowed in a type name";

private static readonly DiagnosticDescriptor Rule =
new DiagnosticDescriptor(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ namespace Sample.Analyzers
public class CodeBlockStartedAnalyzer : DiagnosticAnalyzer
{
private const string Title = "Remove unused parameters";
public const string MessageFormat = "Parameter '{0}' is unused in the method '{1}'.";
public const string MessageFormat = "Parameter '{0}' is unused in the method '{1}'";
private const string Description = "Remove unused parameters.";

internal static DiagnosticDescriptor Rule =
Expand All @@ -42,10 +42,11 @@ public class CodeBlockStartedAnalyzer : DiagnosticAnalyzer

public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);

#pragma warning disable RS1026 // Enable concurrent execution. This analyzer uses mutable per-code-block state.
public override void Initialize(AnalysisContext context)
#pragma warning restore RS1026
{
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.EnableConcurrentExecution();
context.RegisterCodeBlockStartAction<SyntaxKind>(startCodeBlockContext =>
{
// We only care about method bodies.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ namespace Sample.Analyzers
public class CompilationStartedAnalyzerWithCompilationWideAnalysis : DiagnosticAnalyzer
{
private const string Title = "Secure types must not implement interfaces with unsecure methods";
public const string MessageFormat = "Type '{0}' is a secure type as it implements interface '{1}', but it also implements interface '{2}' which has unsecure method(s).";
public const string MessageFormat = "Type '{0}' is a secure type as it implements interface '{1}', but it also implements interface '{2}' which has unsecure method(s)";
private const string Description = "Secure types must not implement interfaces with unsecure methods.";

internal static DiagnosticDescriptor Rule =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ namespace Sample.Analyzers
public class CompilationAnalyzer : DiagnosticAnalyzer
{
private const string Title = "Dont suppress analyzer diagnostics";
public const string MessageFormat = "Analyzer diagnostic '{0}' is suppressed, consider removing this compilation wide suppression.";
public const string MessageFormat = "Analyzer diagnostic '{0}' is suppressed, consider removing this compilation wide suppression";
private const string Description = "Dont suppress analyzer diagnostics.";

internal static DiagnosticDescriptor Rule =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ namespace Sample.Analyzers.StatelessAnalyzers
public class IOperationAnalyzer : DiagnosticAnalyzer
{
private const string Title = "Reduce allocations and use Array.Empty";
private const string MessageFormat = "Replace empty array allocation with Array.Empty.";
private const string MessageFormat = "Replace empty array allocation with Array.Empty";
private const string Description = "Reduce allocations and use Array.Empty.";

internal static DiagnosticDescriptor Rule =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ namespace Sample.Analyzers
public class SymbolAnalyzer : DiagnosticAnalyzer
{
private const string Title = "Do not declare members with same name as containing type";
public const string MessageFormat = "Type '{0}' has one or more members with the same name, considering renaming the type or the members.";
public const string MessageFormat = "Type '{0}' has one or more members with the same name, considering renaming the type or the members";
private const string Description = "Do not declare members with same name as containing type.";

internal static DiagnosticDescriptor Rule =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ namespace Sample.Analyzers
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class SyntaxNodeAnalyzer : DiagnosticAnalyzer
{
private const string Title = "Declare explicit type for local declarations.";
private const string Title = "Declare explicit type for local declarations";
public const string MessageFormat = "Local '{0}' is implicitly typed. Consider specifying its type explicitly in the declaration.";
private const string Description = "Declare explicit type for local declarations.";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ namespace Sample.Analyzers
public class SyntaxTreeAnalyzer : DiagnosticAnalyzer
{
private const string Title = "Do not suppress documentation comment diagnostics";
public const string MessageFormat = "Enable documentation comment diagnostics on source file '{0}'.";
public const string MessageFormat = "Enable documentation comment diagnostics on source file '{0}'";
private const string Description = "Do not suppress documentation comment diagnostics.";

internal static DiagnosticDescriptor Rule =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -376,23 +376,6 @@ public override SyntaxNode VisitTypeParameterList(CS.Syntax.TypeParameterListSyn
return VB.SyntaxFactory.TypeParameterList(parameters);
}

private VB.Syntax.TypeParameterListSyntax ConvertTypeParameters(SeparatedSyntaxList<CS.Syntax.TypeParameterSyntax> list)
{
VB.Syntax.TypeParameterSyntax[] parameters = list.Select(t =>
{
SyntaxToken variance = t.VarianceKeyword.IsKind(CS.SyntaxKind.None)
? new SyntaxToken()
: t.VarianceKeyword.IsKind(CS.SyntaxKind.InKeyword)
? VB.SyntaxFactory.Token(VB.SyntaxKind.InKeyword)
: VB.SyntaxFactory.Token(VB.SyntaxKind.OutKeyword);

// TODO: get the constraints.
return VB.SyntaxFactory.TypeParameter(ConvertIdentifier(t.Identifier)).WithVarianceKeyword(variance);
}).ToArray();

return VB.SyntaxFactory.TypeParameterList(parameters);
}

public override SyntaxNode VisitNamespaceDeclaration(CS.Syntax.NamespaceDeclarationSyntax node)
{
return VB.SyntaxFactory.NamespaceBlock(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,27 +38,6 @@ public StatementVisitor(NodeVisitor nodeVisitor, SourceText text)
return Visit(node);
}

private static VB.Syntax.StatementSyntax ConvertToStatement(SyntaxNode node)
{
if (node == null)
{
return null;
}
else if (node is VB.Syntax.StatementSyntax)
{
return (VB.Syntax.StatementSyntax)node;
}
else if (node is VB.Syntax.InvocationExpressionSyntax)
{
return VB.SyntaxFactory.ExpressionStatement((VB.Syntax.InvocationExpressionSyntax)node);
}
else
{
// can happen in error scenarios
return CreateBadStatement(((SyntaxNode)node).ToFullString(), typeof(VB.Syntax.StatementSyntax));
}
}

public override SyntaxList<VB.Syntax.StatementSyntax> VisitBlock(CS.Syntax.BlockSyntax node)
{
List<VB.Syntax.StatementSyntax> statements = node.Statements.SelectMany(VisitStatementEnumerable).ToList();
Expand Down
6 changes: 3 additions & 3 deletions src/RoslynSdk/Samples/CSharp/ConsoleClassifier/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,10 @@ static void Main()
WriteLine(""Hello, World!"");
}
}");
document = await Formatter.FormatAsync(document);
SourceText text = await document.GetTextAsync();
document = await Formatter.FormatAsync(document).ConfigureAwait(false);
SourceText text = await document.GetTextAsync().ConfigureAwait(false);

IEnumerable<ClassifiedSpan> classifiedSpans = await Classifier.GetClassifiedSpansAsync(document, TextSpan.FromBounds(0, text.Length));
IEnumerable<ClassifiedSpan> classifiedSpans = await Classifier.GetClassifiedSpansAsync(document, TextSpan.FromBounds(0, text.Length)).ConfigureAwait(false);
Console.BackgroundColor = ConsoleColor.Black;

IEnumerable<Range> ranges = classifiedSpans.Select(classifiedSpan =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContex
(c) => ConvertToAutoPropertyAsync(document, propertyDeclaration, c)));
}


/// <summary>
/// Returns true if both get and set accessors exist on the given property; otherwise false.
/// </summary>
Expand Down Expand Up @@ -74,7 +73,7 @@ private async Task<Document> ConvertToAutoPropertyAsync(Document document, Prope
AccessorDeclarationSyntax getter = property.AccessorList.Accessors.FirstOrDefault(ad => ad.Kind() == SyntaxKind.GetAccessorDeclaration);

// Retrieves the type that contains the specified property
INamedTypeSymbol containingType = semanticModel.GetDeclaredSymbol(property).ContainingType;
INamedTypeSymbol containingType = semanticModel.GetDeclaredSymbol(property, cancellationToken).ContainingType;

// Find the backing field of the property
ISymbol backingField = await GetBackingFieldAsync(document, getter, containingType, cancellationToken).ConfigureAwait(false);
Expand All @@ -95,7 +94,7 @@ private async Task<ISymbol> GetBackingFieldAsync(Document document, AccessorDecl
if (statements.FirstOrDefault() is ReturnStatementSyntax returnStatement && returnStatement.Expression != null)
{
SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
SymbolInfo symbolInfo = semanticModel.GetSymbolInfo(returnStatement.Expression);
SymbolInfo symbolInfo = semanticModel.GetSymbolInfo(returnStatement.Expression, cancellationToken);

if (symbolInfo.Symbol is IFieldSymbol fieldSymbol && Equals(fieldSymbol.OriginalDefinition.ContainingType, containingType))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;


namespace ConvertToAutoProperty
{
internal class PropertyRewriter : CSharpSyntaxRewriter
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ private Document ConvertToConditional(Document document,
StatementSyntax replacementStatement,
CancellationToken cancellationToken)
{
SyntaxNode oldRoot = semanticModel.SyntaxTree.GetRoot();
SyntaxNode oldRoot = semanticModel.SyntaxTree.GetRoot(cancellationToken);
SyntaxNode newRoot = oldRoot.ReplaceNode(
oldNode: ifStatement,
newNode: replacementStatement.WithAdditionalAnnotations(Formatter.Annotation));
Expand Down
4 changes: 2 additions & 2 deletions src/RoslynSdk/Samples/CSharp/FormatSolution/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ static async Task Main(string[] args)
MSBuildWorkspace workspace = MSBuildWorkspace.Create();

// Open the solution within the workspace.
Solution originalSolution = await workspace.OpenSolutionAsync(args[0]);
Solution originalSolution = await workspace.OpenSolutionAsync(args[0]).ConfigureAwait(false);

// Declare a variable to store the intermediate solution snapshot at each step.
Solution newSolution = originalSolution;
Expand All @@ -42,7 +42,7 @@ static async Task Main(string[] args)

// Get a transformed version of the document (a new solution snapshot is created
// under the covers to contain it - none of the existing objects are modified).
Document newDocument = await Formatter.FormatAsync(document);
Document newDocument = await Formatter.FormatAsync(document).ConfigureAwait(false);

// Store the solution implicitly constructed in the previous step as the latest
// one so we can continue building it up in the next iteration.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ namespace Roslyn.Samples.AddOrRemoveRefOutModifier
{
internal class ApplicableActionFinder
{
private Document document;
private readonly Document document;
private readonly int position;
private readonly CancellationToken cancellationToken;

Expand Down Expand Up @@ -128,7 +128,7 @@ private async Task<ArgumentSyntax> GetArgumentAsync(IMethodSymbol methodSymbol,

InvocationExpressionSyntax invocation = result.Single()
.Locations
.Cast<Location>()
.Select(location => location.Location)
Comment thread
dibarbet marked this conversation as resolved.
.Select(l => l.FindToken().AncestorAndSelf<InvocationExpressionSyntax>())
.Single();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public NotifyTaskCompletion(Task<TResult> task)

private async Task WatchTaskAsync(Task task)
{
await task;
await task.ConfigureAwait(true);

PropertyChangedEventHandler handler = PropertyChanged;
if (handler == null)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// See the LICENSE file in the project root for more information.

using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

Expand Down Expand Up @@ -48,6 +49,18 @@ protected ICommand RegisterCommand(string text, string name, Action executed, Fu
canExecute: (s, e) => e.CanExecute = canExecute());
}

protected ICommand RegisterCommand(string text, string name, Func<Task> executed, Func<bool> canExecute, params InputGesture[] inputGestures)
{
#pragma warning disable VSTHRD100 // WPF command handlers must return void.
async void OnExecuted(object sender, ExecutedRoutedEventArgs e)
=> await executed().ConfigureAwait(true);
#pragma warning restore VSTHRD100

return RegisterCommand(text, name, inputGestures,
executed: OnExecuted,
canExecute: (s, e) => e.CanExecute = canExecute());
}

protected ICommand RegisterCommand<T>(string text, string name, Action<T> executed, Func<T, bool> canExecute, params InputGesture[] inputGestures)
{
T cast(object x) => x != null ? (T)x : default;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@

//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]


[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public async Task OpenSolutionAsync(string solutionFilePath)
LogHeader();

Stopwatch watch = Stopwatch.StartNew();
Solution solution = await Workspace.OpenSolutionAsync(solutionFilePath, new LoaderProgress(Logger));
Solution solution = await Workspace.OpenSolutionAsync(solutionFilePath, new LoaderProgress(Logger)).ConfigureAwait(false);

watch.Stop();
Logger.LogInformation($"\r\nSolution opened: {watch.Elapsed:m\\:ss\\.fffffff}");
Expand All @@ -60,7 +60,7 @@ public async Task OpenProjectAsync(string projectFilePath)
LogHeader();

Stopwatch watch = Stopwatch.StartNew();
Project project = await Workspace.OpenProjectAsync(projectFilePath, new LoaderProgress(Logger));
Project project = await Workspace.OpenProjectAsync(projectFilePath, new LoaderProgress(Logger)).ConfigureAwait(false);

watch.Stop();
Logger.LogInformation($"\r\nProject opened: {watch.Elapsed:m\\:ss\\.fffffff}");
Expand Down
Loading
Loading