private static string GetParameterNameThatMatchStringLiteral(LiteralExpressionSyntax stringLiteral) { var ancestorThatMightHaveParameters = stringLiteral.FirstAncestorOfType(typeof(AttributeListSyntax), typeof(MethodDeclarationSyntax), typeof(ConstructorDeclarationSyntax), typeof(IndexerDeclarationSyntax)); var parameterName = string.Empty; if (ancestorThatMightHaveParameters != null) { var parameters = new SeparatedSyntaxList<ParameterSyntax>(); switch (ancestorThatMightHaveParameters.Kind()) { case SyntaxKind.MethodDeclaration: case SyntaxKind.ConstructorDeclaration: var method = (BaseMethodDeclarationSyntax)ancestorThatMightHaveParameters; parameters = method.ParameterList.Parameters; break; case SyntaxKind.IndexerDeclaration: var indexer = (IndexerDeclarationSyntax)ancestorThatMightHaveParameters; parameters = indexer.ParameterList.Parameters; break; case SyntaxKind.AttributeList: break; } parameterName = GetParameterWithIdentifierEqualToStringLiteral(stringLiteral, parameters)?.Identifier.Text; } return parameterName; }
/// <summary> /// Initializes a new instance of the <see cref="UvssPropertyTriggerSyntax"/> class. /// </summary> internal UvssPropertyTriggerSyntax( SyntaxToken triggerKeyword, SyntaxToken propertyKeyword, SeparatedSyntaxList<UvssPropertyTriggerConditionSyntax> conditions, SyntaxToken qualifierToken, UvssBlockSyntax body) : base(SyntaxKind.PropertyTrigger) { this.TriggerKeyword = triggerKeyword; ChangeParent(triggerKeyword); this.PropertyKeyword = propertyKeyword; ChangeParent(propertyKeyword); this.Conditions = conditions; ChangeParent(conditions.Node); this.QualifierToken = qualifierToken; ChangeParent(qualifierToken); this.Body = body; ChangeParent(body); SlotCount = 5; UpdateIsMissing(); }
static void Check(SyntaxNodeAnalysisContext nodeContext, SeparatedSyntaxList<ParameterSyntax> syntaxParams, ImmutableArray<IParameterSymbol> list1, ImmutableArray<IParameterSymbol> list2) { var upper = Math.Min(list1.Length, list2.Length); for (int i = 0; i < upper; i++) { var arg = list1[i]; var baseArg = list2[i]; if (arg.Name != baseArg.Name) { nodeContext.ReportDiagnostic(Diagnostic.Create( descriptor.Id, descriptor.Category, descriptor.MessageFormat, descriptor.DefaultSeverity, descriptor.DefaultSeverity, descriptor.IsEnabledByDefault, 4, descriptor.Title, descriptor.Description, descriptor.HelpLinkUri, Location.Create(nodeContext.SemanticModel.SyntaxTree, syntaxParams[i].Identifier.Span), null, new[] { baseArg.Name } )); } } }
static void CheckParameters(SyntaxNodeAnalysisContext ctx, ISymbol member, List<ISymbol> overloads, SeparatedSyntaxList<ParameterSyntax> parameterListNodes) { var memberParameters = member.GetParameters(); for (int i = 0; i < memberParameters.Length; i++) { if (!memberParameters[i].IsOptional) continue; foreach (var overload in overloads) { if (overload.GetParameters().Length != i) continue; bool equal = true; for (int j = 0; j < i; j++) { if (overload.GetParameters()[j].Type != memberParameters[j].Type) { equal = false; break; } } if (equal) { ctx.ReportDiagnostic( Diagnostic.Create( descriptor, parameterListNodes[i].GetLocation(), member.IsKind(SymbolKind.Method) ? GettextCatalog.GetString("Method") : GettextCatalog.GetString("Indexer") )); } } } }
public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node) { var typesList = new List<TypeSyntax> { _baseTypeSyntax }; if (node.BaseList != null) typesList.AddRange(node.BaseList.Types); var types = new SeparatedSyntaxList<TypeSyntax>(); types = types.AddRange(typesList); var identifier = SyntaxFactory.Identifier(FurnaceTypeIdentifier + _typeName); var newNode = node.Update( node.AttributeLists, node.Modifiers, node.Keyword, identifier, node.TypeParameterList, SyntaxFactory.BaseList(types), node.ConstraintClauses, node.OpenBraceToken, node.Members, node.CloseBraceToken, node.SemicolonToken).NormalizeWhitespace(); return base.VisitClassDeclaration(newNode); }
private SyntaxTriviaList CreatePragmaDirectiveTrivia(SyntaxToken disableOrRestoreKeyword, Diagnostic diagnostic, bool needsLeadingEndOfLine, bool needsTrailingEndOfLine) { var id = SyntaxFactory.IdentifierName(diagnostic.Id); var ids = new SeparatedSyntaxList<ExpressionSyntax>().Add(id); var pragmaDirective = SyntaxFactory.PragmaWarningDirectiveTrivia(disableOrRestoreKeyword, ids, true); var pragmaDirectiveTrivia = SyntaxFactory.Trivia(pragmaDirective.WithAdditionalAnnotations(Formatter.Annotation)); var endOfLineTrivia = SyntaxFactory.EndOfLine(@" "); var triviaList = SyntaxFactory.TriviaList(pragmaDirectiveTrivia); var title = diagnostic.Descriptor.Title.ToString(CultureInfo.CurrentUICulture); if (!string.IsNullOrWhiteSpace(title)) { var titleComment = SyntaxFactory.Comment(string.Format(" // {0}", title)).WithAdditionalAnnotations(Formatter.Annotation); triviaList = triviaList.Add(titleComment); } if (needsLeadingEndOfLine) { triviaList = triviaList.Insert(0, endOfLineTrivia); } if (needsTrailingEndOfLine) { triviaList = triviaList.Add(endOfLineTrivia); } return triviaList; }
private async Task<SyntaxTriviaList> CreatePragmaDirectiveTriviaAsync( SyntaxToken disableOrRestoreKeyword, Diagnostic diagnostic, Func<SyntaxNode, Task<SyntaxNode>> formatNode, bool needsLeadingEndOfLine, bool needsTrailingEndOfLine) { var id = SyntaxFactory.IdentifierName(diagnostic.Id); var ids = new SeparatedSyntaxList<ExpressionSyntax>().Add(id); var pragmaDirective = SyntaxFactory.PragmaWarningDirectiveTrivia(disableOrRestoreKeyword, ids, true); pragmaDirective = (PragmaWarningDirectiveTriviaSyntax)await formatNode(pragmaDirective).ConfigureAwait(false); var pragmaDirectiveTrivia = SyntaxFactory.Trivia(pragmaDirective); var endOfLineTrivia = SyntaxFactory.ElasticCarriageReturnLineFeed; var triviaList = SyntaxFactory.TriviaList(pragmaDirectiveTrivia); var title = diagnostic.Descriptor.Title.ToString(CultureInfo.CurrentUICulture); if (!string.IsNullOrWhiteSpace(title)) { var titleComment = SyntaxFactory.Comment(string.Format(" // {0}", title)).WithAdditionalAnnotations(Formatter.Annotation); triviaList = triviaList.Add(titleComment); } if (needsLeadingEndOfLine) { triviaList = triviaList.Insert(0, endOfLineTrivia); } if (needsTrailingEndOfLine) { triviaList = triviaList.Add(endOfLineTrivia); } return triviaList; }
static void GetDiagnostics(SyntaxNodeAnalysisContext nodeContext, SeparatedSyntaxList<AttributeArgumentSyntax>? arguments) { if (!arguments.HasValue) return; var node = nodeContext.Node; CheckParameters(nodeContext, nodeContext.SemanticModel.GetSymbolInfo(node).Symbol, arguments.Value); }
public MacroArgumentListSyntax ParseArgumentList() { var openParen = Match(SyntaxKind.OpenParenToken); var arguments = new List<SyntaxNode>(); CommaIsSeparatorStack.Push(true); try { var currentArg = new List<SyntaxToken>(); var parenStack = 0; while ((Current.Kind != SyntaxKind.CloseParenToken || parenStack > 0) && Current.Kind != SyntaxKind.EndOfFileToken) { switch (Current.Kind) { case SyntaxKind.OpenParenToken: CommaIsSeparatorStack.Push(false); parenStack++; currentArg.Add(NextToken()); break; case SyntaxKind.CloseParenToken: CommaIsSeparatorStack.Pop(); parenStack--; currentArg.Add(NextToken()); break; case SyntaxKind.CommaToken: if (CommaIsSeparatorStack.Peek() == false) goto default; arguments.Add(new MacroArgumentSyntax(currentArg)); currentArg = new List<SyntaxToken>(); arguments.Add(Match(SyntaxKind.CommaToken)); break; default: currentArg.Add(NextToken()); break; } } if (currentArg.Any()) arguments.Add(new MacroArgumentSyntax(currentArg)); } finally { CommaIsSeparatorStack.Pop(); } var argumentList = new SeparatedSyntaxList<MacroArgumentSyntax>(arguments); var closeParen = Match(SyntaxKind.CloseParenToken); return new MacroArgumentListSyntax(openParen, argumentList, closeParen); }
public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node) { node = (ClassDeclarationSyntax)base.VisitClassDeclaration(node); SyntaxList<MemberDeclarationSyntax> newMembers = new SyntaxList<MemberDeclarationSyntax>(); foreach (MemberDeclarationSyntax member in node.Members) { if (member.Kind == SyntaxKind.PropertyDeclaration) { PropertyDeclarationSyntax prop = (PropertyDeclarationSyntax)member; SyntaxList<AccessorDeclarationSyntax> newAccessors = new SyntaxList<AccessorDeclarationSyntax>(); bool implementfield = false; foreach (AccessorDeclarationSyntax accessor in prop.AccessorList.Accessors) { if (accessor.Body == null) { switch (accessor.Kind) { case SyntaxKind.GetAccessorDeclaration: implementfield = true; newAccessors = newAccessors.Add(accessor.WithBody(Syntax.Block(Syntax.ReturnStatement(Syntax.IdentifierName("_" + prop.Identifier.ValueText))))); break; case SyntaxKind.SetAccessorDeclaration: implementfield = true; newAccessors = newAccessors.Add(accessor.WithBody(Syntax.Block(Syntax.ExpressionStatement(Syntax.BinaryExpression(SyntaxKind.AssignExpression, Syntax.IdentifierName("_" + prop.Identifier.ValueText), Syntax.IdentifierName("value")))))); break; default: newAccessors = newAccessors.Add(accessor); break; } } else { newAccessors = newAccessors.Add(accessor); } } if (implementfield) { SeparatedSyntaxList<VariableDeclaratorSyntax> variables = new SeparatedSyntaxList<VariableDeclaratorSyntax>(); variables = variables.Add(Syntax.VariableDeclarator("_" + prop.Identifier.ValueText)); newMembers = newMembers.Add(Syntax.FieldDeclaration(Syntax.VariableDeclaration(prop.Type, variables))); } newMembers = newMembers.Add(prop.WithAccessorList(prop.AccessorList.WithAccessors(newAccessors))); } else { newMembers = newMembers.Add(member); } } return node.WithMembers(newMembers); }
public static BaseParameterListSyntax WithParameters( this BaseParameterListSyntax parameterList, SeparatedSyntaxList<ParameterSyntax> parameters) { switch (parameterList.Kind()) { case SyntaxKind.BracketedParameterList: return ((BracketedParameterListSyntax)parameterList).WithParameters(parameters); case SyntaxKind.ParameterList: return ((ParameterListSyntax)parameterList).WithParameters(parameters); } throw ExceptionUtilities.Unreachable; }
/// <summary> /// Initializes a new instance of the <see cref="UvssRuleSetSyntax"/> class. /// </summary> internal UvssRuleSetSyntax( SeparatedSyntaxList<UvssSelectorWithNavigationExpressionSyntax> selectors, UvssBlockSyntax body) : base(SyntaxKind.RuleSet) { this.Selectors = selectors; ChangeParent(selectors.Node); this.Body = body; ChangeParent(body); SlotCount = 2; UpdateIsMissing(); }
public static BaseParameterListSyntax WithParameters( this BaseParameterListSyntax parameterList, SeparatedSyntaxList<ParameterSyntax> parameters) { switch (parameterList.CSharpKind()) { case SyntaxKind.BracketedParameterList: return ((BracketedParameterListSyntax)parameterList).WithParameters(parameters); case SyntaxKind.ParameterList: return ((ParameterListSyntax)parameterList).WithParameters(parameters); } throw Contract.Unreachable; }
protected SeparatedSyntaxList<ExpressionSyntax> RewritePostfixUnarys(SeparatedSyntaxList<ExpressionSyntax> nodes) { if (nodes.Count == 0) return nodes; List<ExpressionSyntax> expressions = new List<ExpressionSyntax> (nodes.Count); foreach (var node in nodes) { var newNode = RewritePostfixUnarys (node); if (newNode != null) expressions.Add (newNode); } return Syntax.SeparatedList (expressions, Enumerable.Repeat (Syntax.Token (SyntaxKind.CommaToken), expressions.Count - 1)); }
/// <summary>Creates a new ForStatementSyntax instance.</summary> public static ForStatementSyntax ForStatement(VariableDeclarationSyntax declaration, SeparatedSyntaxList<ExpressionSyntax> initializers, ExpressionSyntax condition, SeparatedSyntaxList<ExpressionSyntax> incrementors, StatementSyntax statement) { return ForStatement( SyntaxFactory.Token(SyntaxKind.ForKeyword), SyntaxFactory.Token(SyntaxKind.OpenParenToken), default(SyntaxToken), null, declaration, initializers, SyntaxFactory.Token(SyntaxKind.SemicolonToken), condition, SyntaxFactory.Token(SyntaxKind.SemicolonToken), incrementors, SyntaxFactory.Token(SyntaxKind.CloseParenToken), statement); }
/// <summary>Creates a new ForStatementSyntax instance.</summary> public static ForStatementSyntax ForStatement(SyntaxToken forKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax declaration, SeparatedSyntaxList<ExpressionSyntax> initializers, SyntaxToken firstSemicolonToken, ExpressionSyntax condition, SyntaxToken secondSemicolonToken, SeparatedSyntaxList<ExpressionSyntax> incrementors, SyntaxToken closeParenToken, StatementSyntax statement) { return ForStatement( forKeyword: forKeyword, openParenToken: openParenToken, refKeyword: default(SyntaxToken), deconstruction: null, declaration: declaration, initializers: initializers, firstSemicolonToken: firstSemicolonToken, condition: condition, secondSemicolonToken: secondSemicolonToken, incrementors: incrementors, closeParenToken: closeParenToken, statement: statement); }
public override SyntaxNode VisitInvocationExpression(InvocationExpressionSyntax node) { var memAccess = node.Expression as MemberAccessExpressionSyntax; if (memAccess != null) { var expression = GetRoleMethodInvocation(memAccess); var arguments = from arg in node.ArgumentList.Arguments select (ArgumentSyntax)Visit(arg); var args = new SeparatedSyntaxList<ArgumentSyntax>().Add(arguments.ToArray()); node = node.WithArgumentList(Syntax.ArgumentList(args)); if (expression != node.Expression) { node = node.ReplaceNode(node.Expression, expression); } } return base.VisitInvocationExpression(node); }
/// <summary> /// Initializes a new instance of the <see cref="UvssTransitionArgumentListSyntax"/> class. /// </summary> internal UvssTransitionArgumentListSyntax( SyntaxToken openParenToken, SeparatedSyntaxList<SyntaxNode> arguments, SyntaxToken closeParenToken) : base(SyntaxKind.TransitionArgumentList) { this.OpenParenToken = openParenToken; ChangeParent(openParenToken); this.Arguments = arguments; ChangeParent(arguments.Node); this.CloseParenToken = closeParenToken; ChangeParent(closeParenToken); SlotCount = 3; UpdateIsMissing(); }
/// <summary> /// Initializes a new instance of the <see cref="UvssEventTriggerArgumentList"/> class. /// </summary> internal UvssEventTriggerArgumentList( SyntaxToken openParenToken, SeparatedSyntaxList<SyntaxNode> argumentList, SyntaxToken closeParenToken) : base(SyntaxKind.EventTriggerArgumentList) { this.OpenParenToken = openParenToken; ChangeParent(openParenToken); this.Arguments = argumentList; ChangeParent(argumentList.Node); this.CloseParenToken = closeParenToken; ChangeParent(closeParenToken); SlotCount = 3; UpdateIsMissing(); }
private static TypeSyntax FindTypeSyntaxFromParametersList(SeparatedSyntaxList<ParameterSyntax> parameterList, string typeName) { TypeSyntax result = null; foreach(var parameter in parameterList) { var valueText = GetLastIdentifierValueText(parameter.Type); if (!string.IsNullOrEmpty(valueText)) { if (string.Equals(valueText, typeName, StringComparison.Ordinal)) { result = parameter.Type; break; } } } return result; }
public static void Go(OutputWriter writer, UsingStatementSyntax usingStatement) { var expression = usingStatement.Expression; writer.WriteLine("//using block ... " + usingStatement.Declaration); writer.OpenBrace(); //Ensure the using statement is a local variable - we can't deal with things we can't reliably repeat in the finally block var resource = Utility.TryGetIdentifier(expression); // if (resource == null) // throw new Exception("Using statements must reference a local variable. " + Utility.Descriptor(usingStatement)); var variables = new SeparatedSyntaxList<VariableDeclaratorSyntax>();//.Select(o => o.Identifier.ValueText); if (usingStatement.Declaration != null) { Core.Write(writer, usingStatement.Declaration); variables = usingStatement.Declaration.Variables; } writer.WriteLine("try"); Core.WriteStatementAsBlock(writer, usingStatement.Statement); writer.WriteLine("finally"); writer.OpenBrace(); foreach (var variable in variables) { var typeInfo = TypeProcessor.GetTypeInfo(usingStatement.Declaration.Type); if (!typeInfo.Type.IsValueType) writer.WriteLine("if(" + variable.Identifier.Text + " !is null)"); else if (typeInfo.Type.Name == "Nullable") writer.WriteLine("if(" + variable.Identifier.Text + ".HasValue)"); writer.WriteLine(variable.Identifier.Text + ".Dispose(cast(IDisposable)null);"); } if (resource != null) { writer.WriteLine("if(" + resource + " !is null)"); writer.WriteLine(resource + ".Dispose(cast(IDisposable)null);"); } writer.CloseBrace(); writer.CloseBrace(); }
private static NameSyntax BuildQualifiedSyntax(SeparatedSyntaxList<NameSyntax> tokens) { SyntaxToken? dot = null; NameSyntax right = null; // Start grabbing NameSyntaxii from the back right = tokens.GetAndRemoveLastSyntax (); // There's only 1 NameSyntax, so it's a SimpleNameSyntax if (tokens.SeparatorCount == 0) return right; // Remove and save the dot dot = tokens.GetAndRemoveLastSeparator (); // Recurse to build the left part var left = BuildQualifiedSyntax (tokens); return Syntax.QualifiedName (left, dot.Value, (SimpleNameSyntax)right); }
private void ParseArgumentList(SyntaxKind openKind, SyntaxKind closeKind, bool atLeastOneArg, out SyntaxToken openToken, out SeparatedSyntaxList<ExpressionSyntax> arguments, out SyntaxToken closeToken) { openToken = Match(openKind); var args = new List<SyntaxNode>(); if (atLeastOneArg || Current.Kind != closeKind) { args.Add(ParseExpression()); while (Current.Kind == SyntaxKind.CommaToken) { args.Add(Match(SyntaxKind.CommaToken)); args.Add(ParseExpression()); } } arguments = new SeparatedSyntaxList<ExpressionSyntax>(args); closeToken = Match(closeKind); }
public MacroArgumentListSyntax ParseArgumentList() { var openParen = Match(SyntaxKind.OpenParenToken); var arguments = new List<SyntaxNode>(); var currentArg = new List<SyntaxToken>(); var parenStack = 0; while ((Current.Kind != SyntaxKind.CloseParenToken || parenStack > 0) && Current.Kind != SyntaxKind.EndOfFileToken) { switch (Current.Kind) { case SyntaxKind.OpenParenToken: parenStack++; currentArg.Add(NextToken()); break; case SyntaxKind.CloseParenToken: parenStack--; currentArg.Add(NextToken()); break; case SyntaxKind.CommaToken: arguments.Add(new MacroArgumentSyntax(currentArg)); currentArg = new List<SyntaxToken>(); arguments.Add(Match(SyntaxKind.CommaToken)); break; default: currentArg.Add(NextToken()); break; } } if (currentArg.Any()) arguments.Add(new MacroArgumentSyntax(currentArg)); var argumentList = new SeparatedSyntaxList<MacroArgumentSyntax>(arguments); var closeParen = Match(SyntaxKind.CloseParenToken); return new MacroArgumentListSyntax(openParen, argumentList, closeParen); }
public override SyntaxNode VisitElementAccessExpression(ElementAccessExpressionSyntax node) { var elements = GetListCollectionInitializerElements(node); if (elements != null) { if (elements.Count > 0) { var type = GetArgumentType(elements[0]); var syntaxList = new SeparatedSyntaxList<ExpressionSyntax>(); var intializerExpr = Syntax.InitializerExpression(SyntaxKind.CollectionInitializerExpression, syntaxList.Add(elements.ToArray())); return Syntax.ParseExpression(string.Format("new System.Collections.Generic.List<{1}>{0}", intializerExpr, type)); } else { //no elements of list - returning empty list of objects return Syntax.ParseExpression("new System.Collections.Generic.List<Object>()"); } } return base.VisitElementAccessExpression(node); }
/// <summary> /// Initializes a new instance of the <see cref="UvssStoryboardTargetSyntax"/> class. /// </summary> internal UvssStoryboardTargetSyntax( SyntaxToken targetKeyword, SeparatedSyntaxList<UvssIdentifierBaseSyntax> filters, UvssSelectorWithParenthesesSyntax selector, UvssBlockSyntax body) : base(SyntaxKind.StoryboardTarget) { this.TargetKeyword = targetKeyword; ChangeParent(targetKeyword); this.Filters = filters; ChangeParent(filters.Node); this.Selector = selector; ChangeParent(selector); this.Body = body; ChangeParent(body); SlotCount = 4; UpdateIsMissing(); }
static ExpressionSyntax BuildHasFlagExpression(ExpressionSyntax target, ExpressionSyntax expr) { var bOp = expr as BinaryExpressionSyntax; if (bOp != null) { if (bOp.IsKind(SyntaxKind.BitwiseOrExpression)) { return SyntaxFactory.BinaryExpression( SyntaxKind.BitwiseOrExpression, BuildHasFlagExpression(target, bOp.Left), BuildHasFlagExpression(target, bOp.Right) ); } } var arguments = new SeparatedSyntaxList<ArgumentSyntax>(); arguments = arguments.Add(SyntaxFactory.Argument(MakeFlatExpression(expr, SyntaxKind.BitwiseOrExpression))); return SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, target, SyntaxFactory.IdentifierName("HasFlag")), SyntaxFactory.ArgumentList(arguments) ); }
internal static void FindExpressionVariables( Binder binder, ArrayBuilder<LocalSymbol> builder, SeparatedSyntaxList<ExpressionSyntax> nodes) { if (nodes.Count == 0) { return; } var finder = s_poolInstance.Allocate(); finder._scopeBinder = binder; finder._localsBuilder = builder; foreach (var n in nodes) { finder.Visit(n); } finder._scopeBinder = null; finder._localsBuilder = null; s_poolInstance.Free(finder); }
// TODO : not sure if this makes sense // Test and enable or add comment with reason //public override FixAllProvider GetFixAllProvider() //{ // return WellKnownFixAllProviders.BatchFixer; //} public async override Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var cancellationToken = context.CancellationToken; var span = context.Span; var diagnostics = context.Diagnostics; var root = await document.GetSyntaxRootAsync(cancellationToken); var diagnostic = diagnostics.First(); var node = root.FindNode(context.Span) as InvocationExpressionSyntax; if (node == null) return; context.RegisterCodeFix(CodeActionFactory.Create(node.Span, diagnostic.Severity, "Change invocation to call 'object.ReferenceEquals'", arg => { var arguments = new SeparatedSyntaxList<ArgumentSyntax>(); arguments = arguments.Add(SyntaxFactory.Argument(SyntaxFactory.ThisExpression())); arguments = arguments.Add(node.ArgumentList.Arguments[0]); return Task.FromResult(document.WithSyntaxRoot( root.ReplaceNode((SyntaxNode) node, SyntaxFactory.InvocationExpression( SyntaxFactory.ParseExpression("object.ReferenceEquals"), SyntaxFactory.ArgumentList(arguments) ) .WithLeadingTrivia(node.GetLeadingTrivia()) .WithAdditionalAnnotations(Formatter.Annotation)) ) ); }), diagnostic); context.RegisterCodeFix(CodeActionFactory.Create(node.Span, diagnostic.Severity, "Remove 'base.'", arg => { return Task.FromResult(document.WithSyntaxRoot(root.ReplaceNode((SyntaxNode)node, node.WithExpression(SyntaxFactory.IdentifierName("Equals"))))); }), diagnostic); }
public static FieldDeclarationSyntax GenerateFieldDeclaration( IFieldSymbol field, CodeGenerationDestination destination, CodeGenerationOptions options) { var reusableSyntax = GetReuseableSyntaxNodeForSymbol<VariableDeclaratorSyntax>(field, options); if (reusableSyntax != null) { var variableDeclaration = reusableSyntax.Parent as VariableDeclarationSyntax; if (variableDeclaration != null) { var newVariableDeclaratorsList = new SeparatedSyntaxList<VariableDeclaratorSyntax>().Add(reusableSyntax); var newVariableDeclaration = variableDeclaration.WithVariables(newVariableDeclaratorsList); var fieldDecl = variableDeclaration.Parent as FieldDeclarationSyntax; if (fieldDecl != null) { return fieldDecl.WithDeclaration(newVariableDeclaration); } } } var initializerNode = CodeGenerationFieldInfo.GetInitializer(field) as ExpressionSyntax; var initializer = initializerNode != null ? SyntaxFactory.EqualsValueClause(initializerNode) : GenerateEqualsValue(field); var fieldDeclaration = SyntaxFactory.FieldDeclaration( AttributeGenerator.GenerateAttributeLists(field.GetAttributes(), options), GenerateModifiers(field, options), SyntaxFactory.VariableDeclaration( field.Type.GenerateTypeSyntax(), SyntaxFactory.SingletonSeparatedList( AddAnnotationsTo(field, SyntaxFactory.VariableDeclarator(field.Name.ToIdentifierToken(), null, initializer))))); return AddCleanupAnnotationsTo( ConditionallyAddDocumentationCommentTo(fieldDeclaration, field, options)); }
private TArgumentSyntax GetFormatArgument(SeparatedSyntaxList <TArgumentSyntax> arguments, ISyntaxFactsService syntaxFactsService) => arguments.FirstOrDefault(argument => string.Equals(GetArgumentName(argument, syntaxFactsService), StringFormatArguments.FormatArgumentName, StringComparison.OrdinalIgnoreCase)) ?? arguments[0];
public static TupleExpressionSyntaxWrapper TupleExpression(SeparatedSyntaxList <ArgumentSyntax> arguments = default) { return((TupleExpressionSyntaxWrapper)TupleExpressionAccessor1(arguments)); }
static ITypeSymbol CreateClass(MonoDevelop.Projects.Project project, Stetic.ActionGroupComponent group, string name, string namspace, string folder) { string fullName = namspace.Length > 0 ? namspace + "." + name : name; var type = SyntaxFactory.ClassDeclaration(name) .AddBaseListTypes(SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName("Gtk.ActionGroup"))); // Generate the constructor. It contains the call that builds the widget. var members = new SyntaxList <MemberDeclarationSyntax> (); var ctor = SyntaxFactory.ConstructorDeclaration( new SyntaxList <AttributeListSyntax> (), SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword)), SyntaxFactory.Identifier(name), SyntaxFactory.ParameterList(), SyntaxFactory.ConstructorInitializer(SyntaxKind.BaseKeyword, SyntaxFactory.ArgumentList(new SeparatedSyntaxList <ArgumentSyntax> { SyntaxFactory.Argument(SyntaxFactory.ParseExpression(fullName)) })), SyntaxFactory.Block( SyntaxFactory.ExpressionStatement( SyntaxFactory.InvocationExpression( SyntaxFactory.ParseExpression("Stetic.Gui.Build"), SyntaxFactory.ArgumentList( new SeparatedSyntaxList <ArgumentSyntax> { SyntaxFactory.Argument(SyntaxFactory.ThisExpression()), SyntaxFactory.Argument(SyntaxFactory.ParseExpression(fullName)) } ) ) ) ) ); type = type.AddMembers(ctor); // Add signal handlers foreach (Stetic.ActionComponent action in group.GetActions()) { foreach (Stetic.Signal signal in action.GetSignals()) { var parameters = new SeparatedSyntaxList <ParameterSyntax> (); foreach (var p in signal.SignalDescriptor.HandlerParameters) { parameters = parameters.Add(SyntaxFactory.Parameter(new SyntaxList <AttributeListSyntax> (), SyntaxFactory.TokenList(), SyntaxFactory.ParseTypeName(p.TypeName), SyntaxFactory.Identifier(p.Name), null)); } var met = SyntaxFactory.MethodDeclaration( new SyntaxList <AttributeListSyntax> (), SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)), SyntaxFactory.ParseTypeName(signal.SignalDescriptor.HandlerReturnTypeName), null, SyntaxFactory.Identifier(signal.Handler), null, SyntaxFactory.ParameterList(parameters), new SyntaxList <TypeParameterConstraintClauseSyntax> (), SyntaxFactory.Block(), null ); type = type.AddMembers(met); } } // Create the class return(CodeGenerationService.AddType((DotNetProject)project, folder, namspace, type)); }
public static void AnalyzeAnonyousMethodExpression(SyntaxNodeAnalysisContext context) { if (context.Node.SpanContainsDirectives()) { return; } var anonymousMethod = (AnonymousMethodExpressionSyntax)context.Node; InvocationExpressionSyntax invocationExpression = GetInvocationExpression(anonymousMethod.Body); if (invocationExpression == null) { return; } ExpressionSyntax expression = invocationExpression.Expression; if (!IsSimpleInvocation(expression)) { return; } SemanticModel semanticModel = context.SemanticModel; CancellationToken cancellationToken = context.CancellationToken; var methodSymbol = semanticModel.GetSymbol(invocationExpression, cancellationToken) as IMethodSymbol; if (methodSymbol == null) { return; } ImmutableArray <IParameterSymbol> parameterSymbols = methodSymbol.Parameters; ArgumentListSyntax argumentList = invocationExpression.ArgumentList; SeparatedSyntaxList <ArgumentSyntax> arguments = argumentList.Arguments; if (arguments.Count != parameterSymbols.Length) { return; } ParameterListSyntax parameterList = anonymousMethod.ParameterList; SeparatedSyntaxList <ParameterSyntax> parameters = parameterList.Parameters; bool isReduced = methodSymbol.MethodKind == MethodKind.ReducedExtension; if (parameters.Count != ((isReduced) ? arguments.Count + 1 : arguments.Count)) { return; } MemberAccessExpressionSyntax memberAccessExpression = (isReduced) ? (MemberAccessExpressionSyntax)expression : null; if (isReduced) { if (!CheckParameter( parameters[0], ((MemberAccessExpressionSyntax)expression).Expression, methodSymbol.ReducedFrom.Parameters[0])) { return; } parameters = parameters.RemoveAt(0); } if (!CheckParameters(parameters, arguments, parameterSymbols)) { return; } methodSymbol = (isReduced) ? methodSymbol.GetConstructedReducedFrom() : methodSymbol; if (!CheckInvokeMethod(anonymousMethod, methodSymbol, semanticModel, context.CancellationToken)) { return; } if (!CheckSpeculativeSymbol( anonymousMethod, (isReduced) ? memberAccessExpression.Name.WithoutTrivia() : expression, methodSymbol, semanticModel)) { return; } context.ReportDiagnostic(DiagnosticDescriptors.UseMethodGroupInsteadOfAnonymousFunction, anonymousMethod); FadeOut(context, null, parameterList, anonymousMethod.Block, argumentList, anonymousMethod.DelegateKeyword, memberAccessExpression); }
private void RegisterFixForMethodOverloads( CodeFixContext context, SeparatedSyntaxList <TArgumentSyntax> arguments, ImmutableArray <ArgumentInsertPositionData <TArgumentSyntax> > methodsAndArgumentsToAdd) { var codeFixData = PrepareCreationOfCodeActions(context.Document, arguments, methodsAndArgumentsToAdd); // To keep the list of offered fixes short we create one menu entry per overload only // as long as there are two or less overloads present. If there are more overloads we // create two menu entries. One entry for non-cascading fixes and one with cascading fixes. var fixes = codeFixData.Length <= 2 ? NestByOverload() : NestByCascading(); context.RegisterFixes(fixes, context.Diagnostics); return; ImmutableArray <CodeAction> NestByOverload() { var builder = ArrayBuilder <CodeAction> .GetInstance(codeFixData.Length); foreach (var data in codeFixData) { // We create the mandatory data.CreateChangedSolutionNonCascading fix first. var title = GetCodeFixTitle(FeaturesResources.Add_parameter_to_0, data.Method, includeParameters: true); CodeAction codeAction = new MyCodeAction( title: title, data.CreateChangedSolutionNonCascading); if (data.CreateChangedSolutionCascading != null) { // We have two fixes to offer. We nest the two fixes in an inlinable CodeAction // so the IDE is free to either show both at once or to create a sub-menu. var titleForNesting = GetCodeFixTitle(FeaturesResources.Add_parameter_to_0, data.Method, includeParameters: true); var titleCascading = GetCodeFixTitle(FeaturesResources.Add_parameter_to_0_and_overrides_implementations, data.Method, includeParameters: true); codeAction = new CodeAction.CodeActionWithNestedActions( title: titleForNesting, ImmutableArray.Create( codeAction, new MyCodeAction( title: titleCascading, data.CreateChangedSolutionCascading)), isInlinable: true); } // codeAction is now either a single fix or two fixes wrapped in a CodeActionWithNestedActions builder.Add(codeAction); } return(builder.ToImmutableAndFree()); } ImmutableArray <CodeAction> NestByCascading() { var builder = ArrayBuilder <CodeAction> .GetInstance(2); var nonCascadingActions = ImmutableArray.CreateRange <CodeFixData, CodeAction>(codeFixData, data => { var title = GetCodeFixTitle(FeaturesResources.Add_to_0, data.Method, includeParameters: true); return(new MyCodeAction(title: title, data.CreateChangedSolutionNonCascading)); }); var cascading = codeFixData.Where(data => data.CreateChangedSolutionCascading != null); var cascadingActions = ImmutableArray.CreateRange <CodeAction>(cascading.Select(data => { var title = GetCodeFixTitle(FeaturesResources.Add_to_0, data.Method, includeParameters: true); return(new MyCodeAction(title: title, data.CreateChangedSolutionCascading)); })); var aMethod = codeFixData.First().Method; // We need to term the MethodGroup and need an arbitrary IMethodSymbol to do so. var nestedNonCascadingTitle = GetCodeFixTitle(FeaturesResources.Add_parameter_to_0, aMethod, includeParameters: false); // Create a sub-menu entry with all the non-cascading CodeActions. // We make sure the IDE does not inline. Otherwise the context menu gets flooded with our fixes. builder.Add(new CodeAction.CodeActionWithNestedActions(nestedNonCascadingTitle, nonCascadingActions, isInlinable: false)); if (cascadingActions.Length > 0) { // if there are cascading CodeActions create a second sub-menu. var nestedCascadingTitle = GetCodeFixTitle(FeaturesResources.Add_parameter_to_0_and_overrides_implementations, aMethod, includeParameters: false); builder.Add(new CodeAction.CodeActionWithNestedActions(nestedCascadingTitle, cascadingActions, isInlinable: false)); } return(builder.ToImmutableAndFree()); } }
protected BoundCall MakeQueryInvocation(CSharpSyntaxNode node, BoundExpression receiver, string methodName, SeparatedSyntaxList <TypeSyntax> typeArgsSyntax, ImmutableArray <TypeSymbol> typeArgs, ImmutableArray <BoundExpression> args, DiagnosticBag diagnostics) { // clean up the receiver var ultimateReceiver = receiver; while (ultimateReceiver.Kind == BoundKind.QueryClause) { ultimateReceiver = ((BoundQueryClause)ultimateReceiver).Value; } if ((object)ultimateReceiver.Type == null) { if (ultimateReceiver.HasAnyErrors || node.HasErrors) { // report no additional errors } else if (ultimateReceiver.IsLiteralNull()) { diagnostics.Add(ErrorCode.ERR_NullNotValid, node.Location); } else if (ultimateReceiver.Kind == BoundKind.Lambda || ultimateReceiver.Kind == BoundKind.UnboundLambda) { // Could not find an implementation of the query pattern for source type '{0}'. '{1}' not found. diagnostics.Add(ErrorCode.ERR_QueryNoProvider, node.Location, MessageID.IDS_AnonMethod.Localize(), methodName); } else if (ultimateReceiver.Kind == BoundKind.MethodGroup) { var methodGroup = (BoundMethodGroup)ultimateReceiver; HashSet <DiagnosticInfo> useSiteDiagnostics = null; var resolution = this.ResolveMethodGroup(methodGroup, analyzedArguments: null, isMethodGroupConversion: false, useSiteDiagnostics: ref useSiteDiagnostics); diagnostics.Add(node, useSiteDiagnostics); diagnostics.AddRange(resolution.Diagnostics); if (resolution.HasAnyErrors) { receiver = this.BindMemberAccessBadResult(methodGroup); } else { Debug.Assert(!resolution.IsEmpty); diagnostics.Add(ErrorCode.ERR_QueryNoProvider, node.Location, MessageID.IDS_SK_METHOD.Localize(), methodName); } resolution.Free(); } receiver = new BoundBadExpression(receiver.Syntax, LookupResultKind.NotAValue, ImmutableArray <Symbol> .Empty, ImmutableArray.Create <BoundNode>(receiver), CreateErrorType()); } else if (receiver.Type.SpecialType == SpecialType.System_Void) { if (!receiver.HasAnyErrors && !node.HasErrors) { diagnostics.Add(ErrorCode.ERR_QueryNoProvider, node.Location, "void", methodName); } receiver = new BoundBadExpression(receiver.Syntax, LookupResultKind.NotAValue, ImmutableArray <Symbol> .Empty, ImmutableArray.Create <BoundNode>(receiver), CreateErrorType()); } return((BoundCall)MakeInvocationExpression( node, receiver, methodName, args, diagnostics, typeArgsSyntax, typeArgs, queryClause: node, // Queries are syntactical rewrites, so we allow fields and properties of delegate types to be invoked, // although no well-known non-generic query method is used atm. allowFieldsAndProperties: true)); }
public static bool IsLast <TNode>(this SeparatedSyntaxList <TNode> list, TNode node) where TNode : SyntaxNode { return(list.Any() && list.Last() == node); }
public static int IndexOfFirstFixableParameter( BaseArgumentListSyntax argumentList, SeparatedSyntaxList <ArgumentSyntax> arguments, SemanticModel semanticModel, CancellationToken cancellationToken) { int firstIndex = -1; for (int i = 0; i < arguments.Count; i++) { if (arguments[i].NameColon != null) { firstIndex = i; break; } } if (firstIndex != -1 && firstIndex != arguments.Count - 1) { ISymbol symbol = semanticModel.GetSymbol(argumentList.Parent, cancellationToken); if (symbol != null) { ImmutableArray <IParameterSymbol> parameters = symbol.GetParameters(); if (parameters.Length == arguments.Count) { for (int i = firstIndex; i < arguments.Count; i++) { ArgumentSyntax argument = arguments[i]; NameColonSyntax nameColon = argument.NameColon; if (nameColon == null) { break; } if (!string.Equals( nameColon.Name.Identifier.ValueText, parameters[i].Name, StringComparison.Ordinal)) { int fixableIndex = i; i++; while (i < arguments.Count) { if (arguments[i].NameColon == null) { break; } i++; } return(fixableIndex); } } } } } return(-1); }
public FunctionLikeDefineDirectiveParameterListSyntax(SyntaxToken openParenToken, SeparatedSyntaxList <SyntaxToken> parameters, SyntaxToken closeParenToken) : base(SyntaxKind.FunctionLikeDefineDirectiveParameterList) { RegisterChildNode(out OpenParenToken, openParenToken); RegisterChildNodes(out Parameters, parameters); RegisterChildNode(out CloseParenToken, closeParenToken); }
private static SeparatedSyntaxList <ArgumentSyntax> ConvertInitializers(SeparatedSyntaxList <AnonymousObjectMemberDeclaratorSyntax> initializers) => SyntaxFactory.SeparatedList(initializers.Select(ConvertInitializer), initializers.GetSeparators());
internal static IEnumerable <ArgumentSyntax> GetArgumentsOfKnownType(this SeparatedSyntaxList <ArgumentSyntax> syntaxList, KnownType knownType, SemanticModel semanticModel) => syntaxList .Where(argument => semanticModel.GetTypeInfo(argument.Expression).Type.Is(knownType));
protected abstract SyntaxNode?TryGetMatchingNamedArgument(SeparatedSyntaxList <SyntaxNode> arguments, string searchArgumentName);
private UnboundLambda AnalyzeAnonymousFunction( AnonymousFunctionExpressionSyntax syntax, DiagnosticBag diagnostics) { Debug.Assert(syntax != null); Debug.Assert(syntax.IsAnonymousFunction()); var names = default(ImmutableArray <string>); var refKinds = default(ImmutableArray <RefKind>); var types = default(ImmutableArray <TypeWithAnnotations>); var namesBuilder = ArrayBuilder <string> .GetInstance(); ImmutableArray <bool> discardsOpt = default; SeparatedSyntaxList <ParameterSyntax>?parameterSyntaxList = null; bool hasSignature; switch (syntax.Kind()) { default: case SyntaxKind.SimpleLambdaExpression: // x => ... hasSignature = true; var simple = (SimpleLambdaExpressionSyntax)syntax; namesBuilder.Add(simple.Parameter.Identifier.ValueText); break; case SyntaxKind.ParenthesizedLambdaExpression: // (T x, U y) => ... // (x, y) => ... hasSignature = true; var paren = (ParenthesizedLambdaExpressionSyntax)syntax; parameterSyntaxList = paren.ParameterList.Parameters; CheckParenthesizedLambdaParameters(parameterSyntaxList.Value, diagnostics); break; case SyntaxKind.AnonymousMethodExpression: // delegate (int x) { } // delegate { } var anon = (AnonymousMethodExpressionSyntax)syntax; hasSignature = anon.ParameterList != null; if (hasSignature) { parameterSyntaxList = anon.ParameterList !.Parameters; } break; } var isAsync = syntax.Modifiers.Any(SyntaxKind.AsyncKeyword); var isStatic = syntax.Modifiers.Any(SyntaxKind.StaticKeyword); if (parameterSyntaxList != null) { var hasExplicitlyTypedParameterList = true; var allValue = true; var typesBuilder = ArrayBuilder <TypeWithAnnotations> .GetInstance(); var refKindsBuilder = ArrayBuilder <RefKind> .GetInstance(); // In the batch compiler case we probably should have given a syntax error if the // user did something like (int x, y)=>x+y -- but in the IDE scenario we might be in // this case. If we are, then rather than try to make partial deductions from the // typed formal parameters, simply bail out and treat it as an untyped lambda. // // However, we still want to give errors on every bad type in the list, even if one // is missing. int underscoresCount = 0; foreach (var p in parameterSyntaxList.Value) { if (p.Identifier.IsUnderscoreToken()) { underscoresCount++; } foreach (var attributeList in p.AttributeLists) { Error(diagnostics, ErrorCode.ERR_AttributesNotAllowed, attributeList); } if (p.Default != null) { Error(diagnostics, ErrorCode.ERR_DefaultValueNotAllowed, p.Default.EqualsToken); } if (p.IsArgList) { Error(diagnostics, ErrorCode.ERR_IllegalVarArgs, p); continue; } var typeSyntax = p.Type; TypeWithAnnotations type = default; var refKind = RefKind.None; if (typeSyntax == null) { hasExplicitlyTypedParameterList = false; } else { type = BindType(typeSyntax, diagnostics); foreach (var modifier in p.Modifiers) { switch (modifier.Kind()) { case SyntaxKind.RefKeyword: refKind = RefKind.Ref; allValue = false; break; case SyntaxKind.OutKeyword: refKind = RefKind.Out; allValue = false; break; case SyntaxKind.InKeyword: refKind = RefKind.In; allValue = false; break; case SyntaxKind.ParamsKeyword: // This was a parse error in the native compiler; // it is a semantic analysis error in Roslyn. See comments to // changeset 1674 for details. Error(diagnostics, ErrorCode.ERR_IllegalParams, p); break; case SyntaxKind.ThisKeyword: Error(diagnostics, ErrorCode.ERR_ThisInBadContext, modifier); break; } } } namesBuilder.Add(p.Identifier.ValueText); typesBuilder.Add(type); refKindsBuilder.Add(refKind); } discardsOpt = computeDiscards(parameterSyntaxList.Value, underscoresCount); if (hasExplicitlyTypedParameterList) { types = typesBuilder.ToImmutable(); } if (!allValue) { refKinds = refKindsBuilder.ToImmutable(); } typesBuilder.Free(); refKindsBuilder.Free(); } if (hasSignature) { names = namesBuilder.ToImmutable(); } namesBuilder.Free(); return(new UnboundLambda(syntax, this, refKinds, types, names, discardsOpt, isAsync, isStatic));
internal static IEnumerable <ISymbol> GetSymbolsOfKnownType(this SeparatedSyntaxList <ArgumentSyntax> syntaxList, KnownType knownType, SemanticModel semanticModel) => syntaxList .GetArgumentsOfKnownType(knownType, semanticModel) .Select(argument => semanticModel.GetSymbolInfo(argument.Expression).Symbol);
internal static TNode SingleOrDefault <TNode>(this SeparatedSyntaxList <TNode> list, bool shouldthrow) where TNode : SyntaxNode { return((shouldthrow) ? list.SingleOrDefault() : ((list.Count == 1) ? list[0] : default(TNode))); }
private SeparatedSyntaxList <ArgumentSyntax> CreateArguments(SeparatedSyntaxList <AnonymousObjectMemberDeclaratorSyntax> initializers) => SyntaxFactory.SeparatedList <ArgumentSyntax>(CreateArguments(initializers.GetWithSeparators()));
public static SeparatedSyntaxList <TNode> ReplaceAt <TNode>(this SeparatedSyntaxList <TNode> list, int index, TNode newNode) where TNode : SyntaxNode { return(list.Replace(list[index], newNode)); }
internal override DependencyRegistration GetRegistration(IMethodSymbol method, SeparatedSyntaxList <ArgumentSyntax> arguments, SemanticModel semanticModel) { if (arguments.Count != 1) { return(null); } ObjectScope scope; if (!TryGetObjectScope(arguments[0], semanticModel, out scope)) { return(null); } return(DependencyRegistration.NonFactory( scope, method.TypeArguments[1], method.TypeArguments[1] )); }
private async Task <Solution> FixAsync( Document invocationDocument, IMethodSymbol method, TArgumentSyntax argument, SeparatedSyntaxList <TArgumentSyntax> argumentList, bool fixAllReferences, CancellationToken cancellationToken) { var solution = invocationDocument.Project.Solution; var(argumentType, refKind) = await GetArgumentTypeAndRefKindAsync(invocationDocument, argument, cancellationToken).ConfigureAwait(false); // The argumentNameSuggestion is the base for the parameter name. // For each method declaration the name is made unique to avoid name collisions. var(argumentNameSuggestion, isNamedArgument) = await GetNameSuggestionForArgumentAsync( invocationDocument, argument, cancellationToken).ConfigureAwait(false); var referencedSymbols = fixAllReferences ? await FindMethodDeclarationReferences(invocationDocument, method, cancellationToken).ConfigureAwait(false) : method.GetAllMethodSymbolsOfPartialParts(); var anySymbolReferencesNotInSource = referencedSymbols.Any(symbol => !symbol.IsFromSource()); var locationsInSource = referencedSymbols.Where(symbol => symbol.IsFromSource()); // Indexing Locations[0] is valid because IMethodSymbols have one location at most // and IsFromSource() tests if there is at least one location. var locationsByDocument = locationsInSource.ToLookup(declarationLocation => solution.GetDocument(declarationLocation.Locations[0].SourceTree)); foreach (var documentLookup in locationsByDocument) { var document = documentLookup.Key; var syntaxFacts = document.GetLanguageService <ISyntaxFactsService>(); var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var editor = new SyntaxEditor(syntaxRoot, solution.Workspace); var generator = editor.Generator; foreach (var methodDeclaration in documentLookup) { var methodNode = syntaxRoot.FindNode(methodDeclaration.Locations[0].SourceSpan); var existingParameters = generator.GetParameters(methodNode); var insertionIndex = isNamedArgument ? existingParameters.Count : argumentList.IndexOf(argument); // if the preceding parameter is optional, the new parameter must also be optional // see also BC30202 and CS1737 var parameterMustBeOptional = insertionIndex > 0 && syntaxFacts.GetDefaultOfParameter(existingParameters[insertionIndex - 1]) != null; var parameterSymbol = CreateParameterSymbol( methodDeclaration, argumentType, refKind, parameterMustBeOptional, argumentNameSuggestion); var argumentInitializer = parameterMustBeOptional ? generator.DefaultExpression(argumentType) : null; var parameterDeclaration = generator.ParameterDeclaration(parameterSymbol, argumentInitializer) .WithAdditionalAnnotations(Formatter.Annotation); if (anySymbolReferencesNotInSource && methodDeclaration == method) { parameterDeclaration = parameterDeclaration.WithAdditionalAnnotations( ConflictAnnotation.Create(FeaturesResources.Related_method_signatures_found_in_metadata_will_not_be_updated)); } if (method.MethodKind == MethodKind.ReducedExtension) { insertionIndex++; } AddParameter( syntaxFacts, editor, methodNode, argument, insertionIndex, parameterDeclaration, cancellationToken); } var newRoot = editor.GetChangedRoot(); solution = solution.WithDocumentSyntaxRoot(document.Id, newRoot); } return(solution); }
public static Task <Document> ToSingleLineAsync( Document document, InitializerExpressionSyntax initializer, bool removeTrailingComma = false, CancellationToken cancellationToken = default) { InitializerExpressionSyntax newInitializer = initializer .ReplaceWhitespace(ElasticSpace, TextSpan.FromBounds(initializer.SpanStart, initializer.Span.End)) .WithFormatterAnnotation(); newInitializer = newInitializer.WithOpenBraceToken(newInitializer.OpenBraceToken.WithoutLeadingTrivia().WithTrailingTrivia(Space)); newInitializer = newInitializer.WithCloseBraceToken(newInitializer.CloseBraceToken.WithoutLeadingTrivia()); SeparatedSyntaxList <ExpressionSyntax> expressions = newInitializer.Expressions; if (expressions.Any()) { ExpressionSyntax firstExpression = expressions[0]; newInitializer = newInitializer.WithExpressions(expressions.Replace(firstExpression, firstExpression.WithoutLeadingTrivia())); expressions = newInitializer.Expressions; SyntaxToken trailingComma = expressions.GetTrailingSeparator(); if (trailingComma.IsKind(SyntaxKind.CommaToken)) { if (removeTrailingComma) { expressions = expressions.ReplaceSeparator(trailingComma, MissingToken(SyntaxKind.CommaToken)); ExpressionSyntax lastExpression = expressions.Last(); expressions = expressions.Replace(lastExpression, lastExpression.WithTrailingTrivia(Space)); newInitializer = newInitializer.WithExpressions(expressions); } else { newInitializer = newInitializer.WithExpressions(expressions.ReplaceSeparator(trailingComma, trailingComma.WithTrailingTrivia(Space))); } } else { ExpressionSyntax lastExpression = expressions.Last(); newInitializer = newInitializer.WithExpressions(expressions.Replace(lastExpression, lastExpression.WithTrailingTrivia(Space))); } } SyntaxNode parent = initializer.Parent; SyntaxNode newParent; switch (parent.Kind()) { case SyntaxKind.ObjectCreationExpression: { var expression = (ObjectCreationExpressionSyntax)parent; expression = expression.WithInitializer(newInitializer); ArgumentListSyntax argumentList = expression.ArgumentList; if (argumentList != null) { newParent = expression.WithArgumentList(argumentList.WithTrailingTrivia(Space)); } else { newParent = expression.WithType(expression.Type.WithTrailingTrivia(Space)); } break; } case SyntaxKind.ArrayCreationExpression: { var expression = (ArrayCreationExpressionSyntax)parent; newParent = expression .WithInitializer(newInitializer) .WithType(expression.Type.WithTrailingTrivia(Space)); break; } case SyntaxKind.ImplicitArrayCreationExpression: { var expression = (ImplicitArrayCreationExpressionSyntax)parent; newParent = expression .WithInitializer(newInitializer) .WithCloseBracketToken(expression.CloseBracketToken.WithTrailingTrivia(Space)); break; } case SyntaxKind.EqualsValueClause: { var equalsValueClause = (EqualsValueClauseSyntax)parent; newParent = equalsValueClause .WithValue(newInitializer) .WithEqualsToken(equalsValueClause.EqualsToken.WithTrailingTrivia(Space)); break; } case SyntaxKind.SimpleAssignmentExpression: { var simpleAssignment = (AssignmentExpressionSyntax)parent; newParent = simpleAssignment .WithRight(newInitializer) .WithOperatorToken(simpleAssignment.OperatorToken.WithTrailingTrivia(Space)); break; } default: { Debug.Fail(parent.Kind().ToString()); return(document.ReplaceNodeAsync(initializer, newInitializer, cancellationToken)); } } return(document.ReplaceNodeAsync(parent, newParent, cancellationToken)); }
private async Task <Document> ReplaceStringWithLocalizerFormat(Document document, LiteralExpressionSyntax litDecl, CancellationToken cancellationToken) { try { //Get the details of the ID to use currentProject = ProjectsManager.projects[document.Project.Name]; newIDKey = currentProject.LocalizerSettings.NextTag; newValue = litDecl.ToString(); if (newValue.StartsWith("\"")) { newValue = newValue.Substring(1); } if (newValue.EndsWith("\"")) { newValue = newValue.Substring(0, newValue.Length - 1); } //Get the document var root = await document.GetSyntaxRootAsync(cancellationToken); CompilationUnitSyntax newroot = (CompilationUnitSyntax)root; SyntaxNode replacedNode; try { //Set up the call to Localizer.Format IdentifierNameSyntax localizer = SyntaxFactory.IdentifierName("Localizer"); IdentifierNameSyntax format = SyntaxFactory.IdentifierName("Format"); MemberAccessExpressionSyntax memberaccess = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, localizer, format); ArgumentSyntax arg = SyntaxFactory.Argument(SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(newIDKey))); SeparatedSyntaxList <ArgumentSyntax> argList = SyntaxFactory.SeparatedList(new[] { arg }); SyntaxAnnotation syntaxAnnotation = new SyntaxAnnotation("LocalizerFormat"); SyntaxNode writecall = SyntaxFactory.InvocationExpression(memberaccess, SyntaxFactory.ArgumentList(argList) ).WithAdditionalAnnotations(syntaxAnnotation).WithTriviaFrom(litDecl); newroot = newroot.ReplaceNode(litDecl, (SyntaxNode)writecall); //get the changed node back from teh updated document root replacedNode = newroot.GetAnnotatedNodes(syntaxAnnotation).Single(); } catch (Exception ex) { OutputManager.WriteErrorEx(ex, "Unable to compile the Localizer call. Refactor cancelled."); return(null); } try { //find the Trivial that marks the end of this line bool foundEOL = false; SyntaxNode objToCheck = replacedNode; SyntaxTrivia objEOL = SyntaxFactory.Comment(" "); //This look works upwards through the structure by parent to get bigger bits of the // syntax tree to find the first EOL after the replaced Node while (!foundEOL) { //Go up one level objToCheck = objToCheck.Parent; //If we found it get out if (FindEOLAfter(objToCheck, replacedNode.FullSpan.End, ref objEOL)) { foundEOL = true; } //If we just checked the whole document then stop looping if (objToCheck == root) { break; } } //If we found the EOL Trivia then insert the new comment before it if (foundEOL) { var tabs = SyntaxFactory.Whitespace("\t\t"); var comment = SyntaxFactory.Comment("// " + newIDKey + " = " + newValue); List <SyntaxTrivia> lineComment = new List <SyntaxTrivia>(); lineComment.Add(tabs); lineComment.Add(comment); newroot = newroot.InsertTriviaBefore(objEOL, lineComment); } } catch (Exception ex) { OutputManager.WriteErrorEx(ex, "Unable to add comment to end of line. Add it manually if you like."); } try { //Make sure the file has a usings so the short name works if (!newroot.Usings.Any(u => u.Name.GetText().ToString() == "KSP.Localization")) { newroot = newroot.AddUsings(SyntaxFactory.UsingDirective(SyntaxFactory.QualifiedName(SyntaxFactory.IdentifierName("KSP"), SyntaxFactory.IdentifierName("Localization")))); } } catch (Exception ex) { OutputManager.WriteErrorEx(ex, "Unable to add usings line to head of file. Add it manually."); } //Now convert it to the document to send it back try { var result = document.WithSyntaxRoot(newroot); return(result); } catch (Exception ex) { OutputManager.WriteErrorEx(ex, "Unable to rewrite the document. Refactor cancelled."); return(null); } } catch (Exception ex) { OutputManager.WriteErrorEx(ex, "General error refactoring the token. Refactor cancelled."); } return(null); }
public virtual SeparatedSyntaxList <TNode> VisitList <TNode>(SeparatedSyntaxList <TNode> list) where TNode : SyntaxNode { var count = list.Count; var sepCount = list.SeparatorCount; SeparatedSyntaxListBuilder <TNode> alternate = default(SeparatedSyntaxListBuilder <TNode>); int i = 0; for (; i < sepCount; i++) { var node = list[i]; var visitedNode = this.VisitListElement(node); var separator = list.GetSeparator(i); var visitedSeparator = this.VisitListSeparator(separator); if (alternate.IsNull) { if (node != visitedNode || separator != visitedSeparator) { alternate = new SeparatedSyntaxListBuilder <TNode>(count); alternate.AddRange(list, i); } } if (!alternate.IsNull) { if (visitedNode != null) { alternate.Add(visitedNode); if (visitedSeparator.RawKind == 0) { throw new InvalidOperationException(CSharpResources.SeparatorIsExpected); } alternate.AddSeparator(visitedSeparator); } else { if (visitedNode == null) { throw new InvalidOperationException(CSharpResources.ElementIsExpected); } } } } if (i < count) { var node = list[i]; var visitedNode = this.VisitListElement(node); if (alternate.IsNull) { if (node != visitedNode) { alternate = new SeparatedSyntaxListBuilder <TNode>(count); alternate.AddRange(list, i); } } if (!alternate.IsNull && visitedNode != null) { alternate.Add(visitedNode); } } if (!alternate.IsNull) { return(alternate.ToList()); } return(list); }
public static void AnalyzeSimpleLambdaExpression(SyntaxNodeAnalysisContext context) { if (context.Node.SpanContainsDirectives()) { return; } var lambda = (SimpleLambdaExpressionSyntax)context.Node; InvocationExpressionSyntax invocationExpression = GetInvocationExpression(lambda.Body); if (invocationExpression == null) { return; } ExpressionSyntax expression = invocationExpression.Expression; if (!IsSimpleInvocation(expression)) { return; } SemanticModel semanticModel = context.SemanticModel; CancellationToken cancellationToken = context.CancellationToken; var methodSymbol = semanticModel.GetSymbol(invocationExpression, cancellationToken) as IMethodSymbol; if (methodSymbol == null) { return; } bool isReduced = methodSymbol.MethodKind == MethodKind.ReducedExtension; ImmutableArray <IParameterSymbol> parameterSymbols = (isReduced) ? methodSymbol.ReducedFrom.Parameters : methodSymbol.Parameters; if (parameterSymbols.Length != 1) { return; } ArgumentListSyntax argumentList = invocationExpression.ArgumentList; SeparatedSyntaxList <ArgumentSyntax> arguments = argumentList.Arguments; if (arguments.Count != ((isReduced) ? 0 : 1)) { return; } ParameterSyntax parameter = lambda.Parameter; MemberAccessExpressionSyntax memberAccessExpression = (isReduced) ? (MemberAccessExpressionSyntax)expression : null; if (!CheckParameter( parameter, (isReduced) ? memberAccessExpression.Expression : arguments[0].Expression, parameterSymbols[0])) { return; } methodSymbol = (isReduced) ? methodSymbol.GetConstructedReducedFrom() : methodSymbol; if (!CheckInvokeMethod(lambda, methodSymbol, semanticModel, context.CancellationToken)) { return; } if (!CheckSpeculativeSymbol( lambda, (isReduced) ? memberAccessExpression.Name.WithoutTrivia() : expression, methodSymbol, semanticModel)) { return; } context.ReportDiagnostic(DiagnosticDescriptors.UseMethodGroupInsteadOfAnonymousFunction, lambda); FadeOut(context, parameter, null, lambda.Body as BlockSyntax, argumentList, lambda.ArrowToken, memberAccessExpression); }
/// <summary> /// Returns a list of variables, where some may be nested variables (BoundDeconstructionVariables). /// Checks that all the variables are assignable to. /// The caller is responsible for releasing the nested ArrayBuilders. /// </summary> private ArrayBuilder <DeconstructionVariable> BindDeconstructionAssignmentVariables(SeparatedSyntaxList <ArgumentSyntax> arguments, CSharpSyntaxNode syntax, DiagnosticBag diagnostics) { int numElements = arguments.Count; Debug.Assert(numElements >= 2); // this should not have parsed as a tuple. // bind the variables and check they can be assigned to var checkedVariablesBuilder = ArrayBuilder <DeconstructionVariable> .GetInstance(numElements); foreach (var argument in arguments) { if (argument.Expression.Kind() == SyntaxKind.TupleExpression) // nested tuple case { var nested = (TupleExpressionSyntax)argument.Expression; checkedVariablesBuilder.Add(new DeconstructionVariable(BindDeconstructionAssignmentVariables(nested.Arguments, nested, diagnostics), syntax)); } else { var boundVariable = BindExpression(argument.Expression, diagnostics, invoked: false, indexed: false); var checkedVariable = CheckValue(boundVariable, BindValueKind.Assignment, diagnostics); checkedVariablesBuilder.Add(new DeconstructionVariable(checkedVariable, argument)); } } return(checkedVariablesBuilder); }
public static TupleExpressionSyntaxWrapper TupleExpression(SyntaxToken openParenToken, SeparatedSyntaxList <ArgumentSyntax> arguments, SyntaxToken closeParenToken) { return((TupleExpressionSyntaxWrapper)TupleExpressionAccessor2(openParenToken, arguments, closeParenToken)); }
private static async Task <Document> DeclareExplicitValueAsync( Document document, EnumDeclarationSyntax enumDeclaration, INamedTypeSymbol enumSymbol, bool isFlags, bool useBitShift, ImmutableArray <ulong> values, SemanticModel semanticModel, CancellationToken cancellationToken) { List <ulong> reservedValues = values.ToList(); SeparatedSyntaxList <EnumMemberDeclarationSyntax> members = enumDeclaration.Members; SeparatedSyntaxList <EnumMemberDeclarationSyntax> newMembers = members; for (int i = 0; i < members.Count; i++) { if (members[i].EqualsValue == null) { IFieldSymbol fieldSymbol = semanticModel.GetDeclaredSymbol(members[i], cancellationToken); ulong?value = null; if (isFlags) { Optional <ulong> optional = FlagsUtility <ulong> .Instance.GetUniquePowerOfTwo(reservedValues); if (optional.HasValue && ConvertHelpers.CanConvert(optional.Value, enumSymbol.EnumUnderlyingType.SpecialType)) { value = optional.Value; } } else { value = SymbolUtility.GetEnumValueAsUInt64(fieldSymbol.ConstantValue, enumSymbol); } if (value != null) { reservedValues.Add(value.Value); ExpressionSyntax expression; if (useBitShift && value.Value > 1) { var power = (int)Math.Log(Convert.ToDouble(value.Value), 2); expression = LeftShiftExpression(NumericLiteralExpression(1), NumericLiteralExpression(power)); } else { expression = NumericLiteralExpression(value.Value, enumSymbol.EnumUnderlyingType.SpecialType); } EqualsValueClauseSyntax equalsValue = EqualsValueClause(expression); EnumMemberDeclarationSyntax newMember = members[i].WithEqualsValue(equalsValue); newMembers = newMembers.ReplaceAt(i, newMember); } } } EnumDeclarationSyntax newEnumDeclaration = enumDeclaration.WithMembers(newMembers); return(await document.ReplaceNodeAsync(enumDeclaration, newEnumDeclaration, cancellationToken).ConfigureAwait(false)); }
internal static TNode LastButOneOrDefault <TNode>(this SeparatedSyntaxList <TNode> list) where TNode : SyntaxNode { return((list.Count > 1) ? list.LastButOne() : default(TNode)); }
internal static TNode LastButOne <TNode>(this SeparatedSyntaxList <TNode> list) where TNode : SyntaxNode { return(list[list.Count - 2]); }
static ImmutableArray <bool> computeDiscards(SeparatedSyntaxList <ParameterSyntax> parameters, int underscoresCount) { if (underscoresCount <= 1) { return(default);
private static ImmutableArray <ParameterInfo> GetParameterInfos( InvocationExpressionSyntax invocation, IMethodSymbol methodSymbol) { bool isReduced = methodSymbol.MethodKind == MethodKind.ReducedExtension; if (isReduced) { methodSymbol = methodSymbol.GetConstructedReducedFrom(); } ImmutableArray <IParameterSymbol> parameters = methodSymbol.Parameters; if (isReduced) { parameters = parameters.RemoveAt(0); } List <ParameterInfo> parameterInfos = null; SeparatedSyntaxList <ArgumentSyntax> arguments = invocation.ArgumentList.Arguments; foreach (ArgumentSyntax argument in arguments) { IParameterSymbol parameterSymbol = DetermineParameterHelper.DetermineParameter(argument, arguments, parameters); if (parameterSymbol != null) { var parameterInfo = new ParameterInfo(parameterSymbol, argument.Expression); (parameterInfos ?? (parameterInfos = new List <ParameterInfo>())).Add(parameterInfo); } else { return(default(ImmutableArray <ParameterInfo>)); } } foreach (IParameterSymbol parameterSymbol in parameters) { if (parameterInfos == null || parameterInfos.FindIndex(f => { Debug.WriteLine(f.ParameterSymbol == parameterSymbol); Debug.WriteLine(f.ParameterSymbol.Equals(parameterSymbol)); Debug.WriteLine(f.ParameterSymbol.Name == parameterSymbol.Name); return(f.ParameterSymbol.Equals(parameterSymbol)); }) == -1) { if (parameterSymbol.HasExplicitDefaultValue) { var parameterInfo = new ParameterInfo(parameterSymbol, parameterSymbol.GetDefaultValueSyntax()); (parameterInfos ?? (parameterInfos = new List <ParameterInfo>())).Add(parameterInfo); } else { return(default(ImmutableArray <ParameterInfo>)); } } } if (isReduced) { var memberAccess = (MemberAccessExpressionSyntax)invocation.Expression; var parameterInfo = new ParameterInfo(methodSymbol.Parameters[0], memberAccess.Expression.TrimTrivia()); (parameterInfos ?? (parameterInfos = new List <ParameterInfo>())).Add(parameterInfo); } return((parameterInfos != null) ? parameterInfos.ToImmutableArray() : ImmutableArray <ParameterInfo> .Empty); }