public override SyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node) { if (node.Declaration.Variables.Count > 1) { return(node); } if (node.Declaration.Variables[0].Initializer == null) { return(node); } VariableDeclaratorSyntax declarator = node.Declaration.Variables.First(); TypeSyntax variableTypeName = node.Declaration.Type; ITypeSymbol variableType = (ITypeSymbol)SemanticModel.GetSymbolInfo(variableTypeName).Symbol; TypeInfo initializerInfo = SemanticModel.GetTypeInfo(declarator.Initializer.Value); if (variableType == initializerInfo.Type) { TypeSyntax varTypeName = SyntaxFactory.IdentifierName("var") .WithLeadingTrivia(variableTypeName.GetLeadingTrivia()) .WithTrailingTrivia(variableTypeName.GetTrailingTrivia()); return(node.ReplaceNode(variableTypeName, varTypeName)); } else { return(node); } }
public override SyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node) { // e.g. int x, y = 0; if (node.Declaration.Variables.Count > 1) { return(node); } // e.g. int x; if (node.Declaration.Variables[0].Initializer == null) { return(node); } VariableDeclaratorSyntax declarator = node.Declaration.Variables.First(); TypeSyntax variableTypeName = node.Declaration.Type; TypeSymbol variableType = (TypeSymbol)semanticModel.GetSymbolInfo(variableTypeName).Symbol; TypeInfo initializerInfo = semanticModel.GetTypeInfo(declarator.Initializer.Value); // only when type is the same, (e.g. no base class casting) if (variableType == initializerInfo.Type) { TypeSyntax varTypeName = Syntax.IdentifierName("var") .WithLeadingTrivia(variableTypeName.GetLeadingTrivia()) .WithTrailingTrivia(variableTypeName.GetTrailingTrivia()); return(node.ReplaceNode <LocalDeclarationStatementSyntax, TypeSyntax>(variableTypeName, varTypeName)); } else { return(node); } }
private SyntaxNode ProcessTypeSyntax(TypeSyntax typeSyntax) { this.CancellationToken.ThrowIfCancellationRequested(); // Only simplify if us, or a parent, was marked as needing simplification. if (!alwaysSimplify && !typeSyntax.HasAnnotation(Simplifier.Annotation)) { return(typeSyntax); } // Definitely do not simplify us if we were told to not simplify. if (typeSyntax.HasAnnotation(SimplificationHelpers.DontSimplifyAnnotation)) { return(typeSyntax); } var typeStyle = CSharpUseImplicitTypeHelper.Instance.AnalyzeTypeName( typeSyntax, this.SemanticModel, this.OptionSet, this.CancellationToken); if (!typeStyle.IsStylePreferred || !typeStyle.CanConvert()) { return(typeSyntax); } return(SyntaxFactory.IdentifierName("var") .WithLeadingTrivia(typeSyntax.GetLeadingTrivia()) .WithTrailingTrivia(typeSyntax.GetTrailingTrivia())); }
public static TypeSyntax ToSyntax(this ITypeSymbol type, SemanticModel model, TypeSyntax typeSyntax) { if (type == null) { throw new ArgumentNullException(nameof(type)); } return(SyntaxFactory.ParseTypeName(type.ToMinimalDisplayString(model, typeSyntax.SpanStart)) .WithLeadingTrivia(typeSyntax.GetLeadingTrivia()) .WithTrailingTrivia(typeSyntax.GetTrailingTrivia())); }
public static Microsoft.CodeAnalysis.VisualBasic.Syntax.TypeSyntax ToVbSyntax(this ITypeSymbol type, SemanticModel model, TypeSyntax typeSyntax) { if (type == null) { throw new ArgumentNullException(nameof(type)); } return(VBasic.SyntaxFactory.ParseTypeName(type.ToMinimalDisplayString(model, typeSyntax.SpanStart)) .WithLeadingTrivia(typeSyntax.GetLeadingTrivia().ConvertTrivia()) .WithTrailingTrivia(typeSyntax.GetTrailingTrivia().ConvertTrivia())); }
internal static Document PerformAction(Document document, SyntaxNode root, TypeSyntax type) { var newRoot = root.ReplaceNode((SyntaxNode) type, SyntaxFactory.IdentifierName("var") .WithLeadingTrivia(type.GetLeadingTrivia()) .WithTrailingTrivia(type.GetTrailingTrivia()) ); return(document.WithSyntaxRoot(newRoot)); }
static Document PerformAction(Document document, SemanticModel model, SyntaxNode root, ITypeSymbol type, TypeSyntax typeSyntax) { var newRoot = root.ReplaceNode((SyntaxNode) typeSyntax, SyntaxFactory.ParseTypeName(type.ToMinimalDisplayString(model, typeSyntax.SpanStart)) .WithLeadingTrivia(typeSyntax.GetLeadingTrivia()) .WithTrailingTrivia(typeSyntax.GetTrailingTrivia()) ); return(document.WithSyntaxRoot(newRoot)); }
public ICodeActionEdit GetEdit(CancellationToken cancellationToken) { var syntaxTree = (SyntaxTree)document.GetSyntaxTree(); TypeSyntax newDeclarationType = Syntax.IdentifierName(typeName) .WithLeadingTrivia( typeSyntax.GetLeadingTrivia()) .WithTrailingTrivia( typeSyntax.GetTrailingTrivia()); return(editFactory.CreateTreeTransformEdit(document.Project.Solution, syntaxTree, syntaxTree.Root.ReplaceNode(typeSyntax, newDeclarationType))); }
public override SyntaxNode VisitLocalDeclarationStatement( LocalDeclarationStatementSyntax node) { if (node.Declaration.Variables.Count > 1) { return(node); } if (node.Declaration.Variables[0].Initializer == null) { return(node); } if (node.Modifiers.Count() > 0) { foreach (SyntaxToken token in node.Modifiers) { if (token.ValueText.Equals(kExclusionModifier)) { return(node); } } } VariableDeclaratorSyntax declarator = node.Declaration.Variables.First(); TypeSyntax variableTypeName = node.Declaration.Type; ITypeSymbol variableType = (ITypeSymbol)SemanticModel.GetSymbolInfo(variableTypeName) .Symbol; TypeInfo initializerInfo = SemanticModel.GetTypeInfo(declarator .Initializer .Value); if (variableType == initializerInfo.Type) { TypeSyntax varTypeName = IdentifierName(kTypeInference) .WithLeadingTrivia( variableTypeName.GetLeadingTrivia()) .WithTrailingTrivia( variableTypeName.GetTrailingTrivia()); return(node.ReplaceNode(variableTypeName, varTypeName)); } else { return(node); } }
private static string?TryGetNameFromMultilineComment(TypeSyntax typeArgumentSyntax) { var allTrivia = typeArgumentSyntax.GetTrailingTrivia().Where(z => z.Kind() == SyntaxKind.MultiLineCommentTrivia) .ToList(); if (allTrivia.Count != 1) { return(null); } var trivia = allTrivia.First(); return(GetContentOfMultilineCommentTrivia(trivia)); }
public static Task <Document> RefactorAsync( Document document, ObjectCreationExpressionSyntax objectCreationExpression, CancellationToken cancellationToken) { ArgumentListSyntax argumentList = objectCreationExpression.ArgumentList; InitializerExpressionSyntax initializer = objectCreationExpression.Initializer; ObjectCreationExpressionSyntax newNode = objectCreationExpression.WithInitializer(null); if (argumentList == null) { TypeSyntax type = objectCreationExpression.Type; SyntaxTriviaList trailingTrivia = type.GetTrailingTrivia(); ArgumentListSyntax newArgumentList = SyntaxFactory.ArgumentList(); IEnumerable <SyntaxTrivia> trivia = objectCreationExpression.DescendantTrivia(TextSpan.FromBounds(type.Span.End, initializer.Span.End)); if (trivia.Any(f => !f.IsWhitespaceOrEndOfLineTrivia())) { newArgumentList = newArgumentList.WithTrailingTrivia(trivia); } newNode = newNode .WithType(type.WithoutTrailingTrivia()) .WithArgumentList(newArgumentList); } else { IEnumerable <SyntaxTrivia> trivia = objectCreationExpression.DescendantTrivia(TextSpan.FromBounds(argumentList.Span.End, initializer.Span.End)); if (trivia.Any(f => !f.IsWhitespaceOrEndOfLineTrivia())) { newNode = newNode.WithTrailingTrivia(trivia); } else { newNode = newNode.WithoutTrailingTrivia(); } } newNode = newNode .AppendToTrailingTrivia(initializer.GetTrailingTrivia()) .WithFormatterAnnotation(); return(document.ReplaceNodeAsync(objectCreationExpression, newNode, cancellationToken)); }
private static Task <Document> RefactorAsync( Document document, TypeSyntax type, string name, CancellationToken cancellationToken = default) { SyntaxTrivia endOfLine = type.GetTrailingTrivia() .SkipWhile(f => f.IsWhitespaceTrivia()) .First(); return(document.WithTextChangeAsync( TextSpan.FromBounds(type.Span.End, endOfLine.SpanStart), " " + name, cancellationToken)); }
private static Task <Document> RefactorAsync( Document document, TypeSyntax type, string name, CancellationToken cancellationToken = default(CancellationToken)) { SyntaxTrivia endOfLine = type.GetTrailingTrivia() .SkipWhile(f => f.IsKind(SyntaxKind.WhitespaceTrivia)) .First(); TextSpan span = TextSpan.FromBounds(type.Span.End, endOfLine.Span.Start); var textChange = new TextChange(span, " " + name); return(document.WithTextChangeAsync(textChange, cancellationToken)); }
async Task <Document> MakeUseVar( Document document, TypeSyntax type, CancellationToken cancellationToken) { var newType = SyntaxFactory.IdentifierName( SyntaxFactory.Identifier( type.GetLeadingTrivia(), "var", type.GetTrailingTrivia())); var oldRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var newRoot = oldRoot.ReplaceNode(type, newType); return(document.WithSyntaxRoot(newRoot)); }
public static async Task ComputeRefactoringAsync(RefactoringContext context, LocalDeclarationStatementSyntax localDeclaration) { VariableDeclarationSyntax declaration = localDeclaration.Declaration; TypeSyntax type = declaration?.Type; if (type?.IsVar == false) { VariableDeclaratorSyntax declarator = declaration.Variables.FirstOrDefault(); if (declarator != null && context.Span.Start >= type.Span.Start) { SyntaxTriviaList triviaList = type.GetTrailingTrivia(); if (triviaList.Any()) { SyntaxTrivia trivia = triviaList .SkipWhile(f => f.IsWhitespaceTrivia()) .FirstOrDefault(); if (trivia.IsEndOfLineTrivia() && context.Span.End <= trivia.Span.Start) { SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(type, context.CancellationToken); string name = NameGenerator.Default.CreateUniqueLocalName( typeSymbol, semanticModel, declarator.SpanStart, cancellationToken: context.CancellationToken); if (name != null) { context.RegisterRefactoring( $"Add identifier '{name}'", c => RefactorAsync(context.Document, type, name, c)); } } } } } }
public static async Task ComputeRefactoringAsync(RefactoringContext context, LocalDeclarationStatementSyntax localDeclaration) { VariableDeclarationSyntax declaration = localDeclaration.Declaration; TypeSyntax type = declaration?.Type; if (type?.IsVar == false) { VariableDeclaratorSyntax declarator = declaration.Variables.FirstOrDefault(); if (declarator != null && context.Span.Start >= type.Span.Start) { SyntaxTriviaList triviaList = type.GetTrailingTrivia(); if (triviaList.Any()) { SyntaxTrivia trivia = triviaList .SkipWhile(f => f.IsKind(SyntaxKind.WhitespaceTrivia)) .FirstOrDefault(); if (trivia.IsKind(SyntaxKind.EndOfLineTrivia) && context.Span.End <= trivia.Span.Start) { SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(type, context.CancellationToken); if (typeSymbol?.IsErrorType() == false) { string name = Identifier.CreateName(typeSymbol, firstCharToLower: true); name = Identifier.EnsureUniqueLocalName(name, declarator.SpanStart, semanticModel, context.CancellationToken); if (!string.IsNullOrEmpty(name)) { context.RegisterRefactoring( $"Add identifier '{name}'", c => RefactorAsync(context.Document, type, name, c)); } } } } } } }
private static async Task <Document> RefactorAsync( Document document, VariableDeclaratorSyntax declarator, TypeSyntax type, string name, CancellationToken cancellationToken = default(CancellationToken)) { SourceText sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false); SyntaxTrivia endOfLine = type.GetTrailingTrivia() .SkipWhile(f => f.IsKind(SyntaxKind.WhitespaceTrivia)) .First(); TextSpan span = TextSpan.FromBounds(type.Span.End, endOfLine.Span.Start); var textChange = new TextChange(span, " " + name); SourceText newSourceText = sourceText.WithChanges(textChange); return(document.WithText(newSourceText)); }
private static SyntaxToken GetIdentifierTokenAndTrivia(SyntaxToken identifier, TypeSyntax typeSyntax) { if (typeSyntax != null) { var identifierLeadingTrivia = new SyntaxTriviaList(); var identifierTrailingTrivia = new SyntaxTriviaList(); if (typeSyntax.HasLeadingTrivia) { identifierLeadingTrivia = identifierLeadingTrivia.AddRange(typeSyntax.GetLeadingTrivia()); } if (typeSyntax.HasTrailingTrivia) { identifierLeadingTrivia = identifierLeadingTrivia.AddRange(typeSyntax.GetTrailingTrivia()); } identifierLeadingTrivia = identifierLeadingTrivia.AddRange(identifier.LeadingTrivia); identifierTrailingTrivia = identifierTrailingTrivia.AddRange(identifier.TrailingTrivia); identifier = identifier.WithLeadingTrivia(identifierLeadingTrivia) .WithTrailingTrivia(identifierTrailingTrivia); } return(identifier); }
private static async Task <Document> MakeConstAsync(Document document, LocalDeclarationStatementSyntax localDeclaration, CancellationToken cancellationToken) { // Remove the leading trivia from the local declaration. SyntaxToken firstToken = localDeclaration.GetFirstToken(); SyntaxTriviaList leadingTrivia = firstToken.LeadingTrivia; LocalDeclarationStatementSyntax trimmedLocal = localDeclaration.ReplaceToken( firstToken, firstToken.WithLeadingTrivia(SyntaxTriviaList.Empty)); // Create a const token with the leading trivia. SyntaxToken constToken = SyntaxFactory.Token(leadingTrivia, SyntaxKind.ConstKeyword, SyntaxFactory.TriviaList(SyntaxFactory.ElasticMarker)); // Insert the const token into the modifiers list, creating a new modifiers list. SyntaxTokenList newModifiers = trimmedLocal.Modifiers.Insert(0, constToken); // If the type of declaration is 'var', create a new type name for the // type inferred for 'var'. VariableDeclarationSyntax variableDeclaration = localDeclaration.Declaration; TypeSyntax variableTypeName = variableDeclaration.Type; if (variableTypeName.IsVar) { SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); // Special case: Ensure that 'var' isn't actually an alias to another type // (e.g. using var = System.String). IAliasSymbol aliasInfo = semanticModel.GetAliasInfo(variableTypeName, cancellationToken); if (aliasInfo == null) { // Retrieve the type inferred for var. ITypeSymbol type = semanticModel.GetTypeInfo(variableTypeName, cancellationToken).ConvertedType; // Special case: Ensure that 'var' isn't actually a type named 'var'. if (type.Name != "var") { // Create a new TypeSyntax for the inferred type. Be careful // to keep any leading and trailing trivia from the var keyword. TypeSyntax typeName = SyntaxFactory.ParseTypeName(type.ToDisplayString()) .WithLeadingTrivia(variableTypeName.GetLeadingTrivia()) .WithTrailingTrivia(variableTypeName.GetTrailingTrivia()); // Add an annotation to simplify the type name. TypeSyntax simplifiedTypeName = typeName.WithAdditionalAnnotations(Simplifier.Annotation); // Replace the type in the variable declaration. variableDeclaration = variableDeclaration.WithType(simplifiedTypeName); } } } // Produce the new local declaration. LocalDeclarationStatementSyntax newLocal = trimmedLocal.WithModifiers(newModifiers) .WithDeclaration(variableDeclaration); // Add an annotation to format the new local declaration. LocalDeclarationStatementSyntax formattedLocal = newLocal.WithAdditionalAnnotations(Formatter.Annotation); // Replace the old local declaration with the new local declaration. SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); SyntaxNode newRoot = root.ReplaceNode(localDeclaration, formattedLocal); // Return document with transformed tree. return(document.WithSyntaxRoot(newRoot)); }
private static Task <Document> RefactorAsync( Document document, StatementListInfo statementsInfo, StatementSyntax statement, InitializerExpressionSyntax initializer, ExpressionSyntax initializedExpression, CancellationToken cancellationToken) { ExpressionStatementSyntax[] expressions = CreateExpressionStatements(initializer, initializedExpression).ToArray(); expressions[expressions.Length - 1] = expressions[expressions.Length - 1] .WithTrailingTrivia(statement.GetTrailingTrivia()); var objectCreationExpression = (ObjectCreationExpressionSyntax)initializer.Parent; ObjectCreationExpressionSyntax newObjectCreationExpression = objectCreationExpression.WithInitializer(null); if (newObjectCreationExpression.ArgumentList == null) { TypeSyntax type = newObjectCreationExpression.Type; newObjectCreationExpression = newObjectCreationExpression .WithArgumentList(ArgumentList().WithTrailingTrivia(type.GetTrailingTrivia())) .WithType(type.WithoutTrailingTrivia()); } SyntaxList <StatementSyntax> statements = statementsInfo.Statements; int index = statements.IndexOf(statement); StatementSyntax newStatement = statement.ReplaceNode(objectCreationExpression, newObjectCreationExpression); SyntaxKind statementKind = statement.Kind(); if (statementKind == SyntaxKind.ExpressionStatement) { var expressionStatement = (ExpressionStatementSyntax)newStatement; newStatement = expressionStatement .WithExpression(expressionStatement.Expression.WithoutTrailingTrivia()); } else if (statementKind == SyntaxKind.LocalDeclarationStatement) { var localDeclaration = (LocalDeclarationStatementSyntax)newStatement; newStatement = localDeclaration .WithDeclaration(localDeclaration.Declaration.WithoutTrailingTrivia()); } SyntaxList <StatementSyntax> newStatements = statements.Replace(statement, newStatement); SyntaxNode newNode = statementsInfo .WithStatements(newStatements.InsertRange(index + 1, expressions)) .Parent .WithFormatterAnnotation(); return(document.ReplaceNodeAsync(statementsInfo.Parent, newNode, cancellationToken)); }
public static TRoot ReplaceType <TRoot>(this TRoot node, TypeSyntax type) where TRoot : SyntaxNode { string value = HlslKnownTypes.GetMappedName(type.ToString()); // If the HLSL mapped full type name equals the original type, just return the input node if (value == type.ToString()) { return(node); } // Process and return the type name TypeSyntax newType = SyntaxFactory.ParseTypeName(value).WithLeadingTrivia(type.GetLeadingTrivia()).WithTrailingTrivia(type.GetTrailingTrivia()); return(node.ReplaceNode(type, newType)); }
private SyntaxNode ConvertType(IDeclarationConverter converter, SemanticModel semanticModel, TypeSyntax original) { return(SyntaxFactory.IdentifierName(converter.ConvertTypeName(original, semanticModel)) .WithLeadingTrivia(original.GetLeadingTrivia()) .WithTrailingTrivia(original.GetTrailingTrivia())); }
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { Diagnostic diagnostic = context.Diagnostics[0]; if (!Settings.IsEnabled(diagnostic.Id, CodeFixIdentifiers.MoveInitializerExpressionsToConstructor)) { return; } SyntaxNode root = await context.GetSyntaxRootAsync().ConfigureAwait(false); ObjectCreationExpressionSyntax objectCreationExpression = root .FindNode(context.Span, getInnermostNodeForTie: true)? .FirstAncestorOrSelf <ObjectCreationExpressionSyntax>(); if (objectCreationExpression == null) { return; } switch (diagnostic.Id) { case CompilerDiagnosticIdentifiers.ThereIsNoArgumentGivenThatCorrespondsToRequiredFormalParameter: { if (!Settings.IsEnabled(diagnostic.Id, CodeFixIdentifiers.MoveInitializerExpressionsToConstructor)) { break; } if (!objectCreationExpression.Type.Span.Contains(diagnostic.Location.SourceSpan)) { return; } ArgumentListSyntax argumentList = objectCreationExpression.ArgumentList; if (argumentList?.Arguments.Any() == true) { return; } InitializerExpressionSyntax initializer = objectCreationExpression.Initializer; if (initializer == null) { return; } SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); List <ExpressionSyntax> expressions = null; foreach (ExpressionSyntax expression in initializer.Expressions) { if (expression is AssignmentExpressionSyntax assignment && semanticModel.GetDiagnostic( CompilerDiagnosticIdentifiers.PropertyOrIndexerCannotBeUsedInThisContextBecauseSetAccessorIsAccessible, assignment.Left.Span, context.CancellationToken) != null) { (expressions ??= new List <ExpressionSyntax>()).Add(expression); } } if (expressions == null) { return; } TypeSyntax type = objectCreationExpression.Type; if (argumentList == null) { argumentList = ArgumentList().WithTrailingTrivia(type.GetTrailingTrivia()); type = type.WithoutTrailingTrivia(); } SeparatedSyntaxList <ArgumentSyntax> arguments = expressions .Select(f => Argument(((AssignmentExpressionSyntax)f).Right)) .ToSeparatedSyntaxList(); argumentList = argumentList.WithArguments(arguments); ObjectCreationExpressionSyntax newObjectCreationExpression = objectCreationExpression.Update( objectCreationExpression.NewKeyword, type, argumentList, initializer); SymbolInfo symbolInfo = semanticModel.GetSpeculativeSymbolInfo( objectCreationExpression.SpanStart, newObjectCreationExpression, SpeculativeBindingOption.BindAsExpression); if (symbolInfo.Symbol is IMethodSymbol methodSymbol && methodSymbol.MethodKind == MethodKind.Constructor) { CodeAction codeAction = CodeAction.Create( "Move initializer expressions to constructor", ct => { InitializerExpressionSyntax newInitializer = initializer.RemoveNodes(expressions, SyntaxRefactorings.DefaultRemoveOptions); if (newInitializer.Expressions.Count == 0 && newInitializer .DescendantTrivia(TextSpan.FromBounds(newInitializer.OpenBraceToken.SpanStart, newInitializer.CloseBraceToken.SpanStart)) .All(f => f.IsWhitespaceOrEndOfLineTrivia())) { newInitializer = null; ArgumentListSyntax newArgumentList = newObjectCreationExpression .ArgumentList .TrimTrailingTrivia() .AppendToTrailingTrivia(initializer.GetTrailingTrivia()); newObjectCreationExpression = newObjectCreationExpression .WithArgumentList(newArgumentList); } newObjectCreationExpression = newObjectCreationExpression .WithInitializer(newInitializer) .WithFormatterAnnotation(); return(context.Document.ReplaceNodeAsync(objectCreationExpression, newObjectCreationExpression, ct)); }, GetEquivalenceKey(diagnostic)); context.RegisterCodeFix(codeAction, diagnostic); } break; } } }