public override void VisitConstructorDeclaration(ConstructorDeclarationSyntax node) { var symbol = model.GetDeclaredSymbol(node); this.declaredItems.Add(new DeclaredItemDocument { Name = symbol.Name, Location = this.model.SyntaxTree.GetLineSpan(node.Span, false).StartLinePosition.Line, Identifier = symbol.ToDisplayString(), Type = "Constructor" }); base.VisitConstructorDeclaration(node); }
public override SyntaxNode VisitConstructorDeclaration(ConstructorDeclarationSyntax node) { SyntaxTriviaList existingTrivia = node.GetLeadingTrivia(); // TODO: just existingTrivia.Any(SyntaxKind.DocumentationComment) should work here // but sometimes doc comments aren't picked up by Roslyn June 2012. if (!HasDocumentationComment(existingTrivia)) { MethodSymbol symbol = this.semanticModel.GetDeclaredSymbol(node); NamedTypeSymbol containingType = symbol.ContainingType; string containingTypeKind = symbol.ContainingType.TypeKind.ToString().ToLower(); string summary = string.Format( "/// <summary>\n" + "/// Initializes a new instance of the <see cref=\"{0}\"/> {1}.\n" + "/// </summary>\n", node.Identifier, containingTypeKind); var trivia = existingTrivia.Concat(Syntax.ParseLeadingTrivia(summary)); return node.WithLeadingTrivia(trivia); } return base.VisitConstructorDeclaration(node); }
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { if (!Settings.IsCodeFixEnabled(CodeFixIdentifiers.AddDocumentationComment) && !Settings.IsCodeFixEnabled(CodeFixIdentifiers.ChangeMethodReturnType) && !Settings.IsCodeFixEnabled(CodeFixIdentifiers.MemberTypeMustMatchOverriddenMemberType) && !Settings.IsCodeFixEnabled(CodeFixIdentifiers.AddPartialModifier) && !Settings.IsCodeFixEnabled(CodeFixIdentifiers.MakeContainingClassAbstract) && !Settings.IsCodeFixEnabled(CodeFixIdentifiers.RemoveParametersFromStaticConstructor) && !Settings.IsCodeFixEnabled(CodeFixIdentifiers.RemoveMemberDeclaration)) { return; } SyntaxNode root = await context.GetSyntaxRootAsync().ConfigureAwait(false); if (!TryFindFirstAncestorOrSelf(root, context.Span, out MemberDeclarationSyntax memberDeclaration)) { return; } foreach (Diagnostic diagnostic in context.Diagnostics) { switch (diagnostic.Id) { case CompilerDiagnosticIdentifiers.MissingXmlCommentForPubliclyVisibleTypeOrMember: { if (!Settings.IsCodeFixEnabled(CodeFixIdentifiers.AddDocumentationComment)) { break; } CodeAction codeAction = CodeAction.Create( "Add documentation comment", cancellationToken => AddDocumentationCommentRefactoring.RefactorAsync(context.Document, memberDeclaration, false, cancellationToken), GetEquivalenceKey(diagnostic)); context.RegisterCodeFix(codeAction, diagnostic); CodeAction codeAction2 = CodeAction.Create( "Add documentation comment (copy from base if available)", cancellationToken => AddDocumentationCommentRefactoring.RefactorAsync(context.Document, memberDeclaration, true, cancellationToken), GetEquivalenceKey(diagnostic, "CopyFromBaseIfAvailable")); context.RegisterCodeFix(codeAction2, diagnostic); break; } case CompilerDiagnosticIdentifiers.MethodReturnTypeMustMatchOverriddenMethodReturnType: { if (!Settings.IsCodeFixEnabled(CodeFixIdentifiers.ChangeMethodReturnType)) { break; } SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); var methodSymbol = (IMethodSymbol)semanticModel.GetDeclaredSymbol(memberDeclaration, context.CancellationToken); ITypeSymbol typeSymbol = methodSymbol.OverriddenMethod.ReturnType; if (typeSymbol?.IsErrorType() == false) { CodeAction codeAction = CodeAction.Create( $"Change return type to '{SymbolDisplay.GetMinimalString(typeSymbol, semanticModel, memberDeclaration.SpanStart)}'", cancellationToken => MemberTypeMustMatchOverriddenMemberTypeRefactoring.RefactorAsync(context.Document, memberDeclaration, typeSymbol, semanticModel, cancellationToken), GetEquivalenceKey(diagnostic)); context.RegisterCodeFix(codeAction, diagnostic); } break; } case CompilerDiagnosticIdentifiers.PartialMethodsMustHaveVoidReturnType: { if (!Settings.IsCodeFixEnabled(CodeFixIdentifiers.ChangeMethodReturnType)) { break; } SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); var methodDeclaration = (MethodDeclarationSyntax)memberDeclaration; MethodDeclarationSyntax otherPart = semanticModel.GetOtherPart(methodDeclaration, context.CancellationToken); if (otherPart == null) { break; } CodeAction codeAction = CodeAction.Create( "Change return type to 'void'", cancellationToken => { return(context.Document.Solution().ReplaceNodesAsync( new MethodDeclarationSyntax[] { methodDeclaration, otherPart }, (node, rewrittenNode) => node.WithReturnType(CSharpFactory.VoidType().WithTriviaFrom(node.ReturnType)), cancellationToken)); }, GetEquivalenceKey(diagnostic)); context.RegisterCodeFix(codeAction, diagnostic); break; } case CompilerDiagnosticIdentifiers.MemberTypeMustMatchOverriddenMemberType: { if (!Settings.IsCodeFixEnabled(CodeFixIdentifiers.MemberTypeMustMatchOverriddenMemberType)) { break; } SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); ITypeSymbol typeSymbol = null; switch (memberDeclaration.Kind()) { case SyntaxKind.PropertyDeclaration: case SyntaxKind.IndexerDeclaration: { var propertySymbol = (IPropertySymbol)semanticModel.GetDeclaredSymbol(memberDeclaration, context.CancellationToken); typeSymbol = propertySymbol.OverriddenProperty.Type; break; } case SyntaxKind.EventDeclaration: { var eventSymbol = (IEventSymbol)semanticModel.GetDeclaredSymbol(memberDeclaration, context.CancellationToken); typeSymbol = eventSymbol.OverriddenEvent.Type; break; } case SyntaxKind.EventFieldDeclaration: { VariableDeclaratorSyntax declarator = ((EventFieldDeclarationSyntax)memberDeclaration).Declaration.Variables.First(); var eventSymbol = (IEventSymbol)semanticModel.GetDeclaredSymbol(declarator, context.CancellationToken); typeSymbol = eventSymbol.OverriddenEvent.Type; break; } } if (typeSymbol?.IsErrorType() == false) { string title = $"Change type to '{SymbolDisplay.GetMinimalString(typeSymbol, semanticModel, memberDeclaration.SpanStart)}'"; CodeAction codeAction = CodeAction.Create( title, cancellationToken => MemberTypeMustMatchOverriddenMemberTypeRefactoring.RefactorAsync(context.Document, memberDeclaration, typeSymbol, semanticModel, cancellationToken), GetEquivalenceKey(diagnostic)); context.RegisterCodeFix(codeAction, diagnostic); } break; } case CompilerDiagnosticIdentifiers.MissingPartialModifier: case CompilerDiagnosticIdentifiers.PartialMethodMustBeDeclaredInPartialClassOrPartialStruct: { if (!Settings.IsCodeFixEnabled(CodeFixIdentifiers.AddPartialModifier)) { break; } SyntaxNode node = null; switch (memberDeclaration.Kind()) { case SyntaxKind.MethodDeclaration: { if (memberDeclaration.IsParentKind(SyntaxKind.ClassDeclaration, SyntaxKind.StructDeclaration)) { node = memberDeclaration.Parent; } break; } case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.InterfaceDeclaration: { node = memberDeclaration; break; } } Debug.Assert(node != null, memberDeclaration.ToString()); if (node == null) { break; } ModifiersCodeFixRegistrator.AddModifier(context, diagnostic, node, SyntaxKind.PartialKeyword); break; } case CompilerDiagnosticIdentifiers.MemberIsAbstractButItIsContainedInNonAbstractClass: { if (!Settings.IsCodeFixEnabled(CodeFixIdentifiers.MakeContainingClassAbstract)) { break; } if (!memberDeclaration.IsParentKind(SyntaxKind.ClassDeclaration)) { break; } ModifiersCodeFixRegistrator.AddModifier( context, diagnostic, memberDeclaration.Parent, SyntaxKind.AbstractKeyword, title: "Make containing class abstract"); break; } case CompilerDiagnosticIdentifiers.StaticConstructorMustBeParameterless: { if (!Settings.IsCodeFixEnabled(CodeFixIdentifiers.RemoveParametersFromStaticConstructor)) { break; } var constructorDeclaration = (ConstructorDeclarationSyntax)memberDeclaration; CodeAction codeAction = CodeAction.Create( "Remove parameters", cancellationToken => { ParameterListSyntax parameterList = constructorDeclaration.ParameterList; ParameterListSyntax newParameterList = parameterList .WithParameters(default(SeparatedSyntaxList <ParameterSyntax>)) .WithOpenParenToken(parameterList.OpenParenToken.WithoutTrailingTrivia()) .WithCloseParenToken(parameterList.CloseParenToken.WithoutLeadingTrivia()); ConstructorDeclarationSyntax newNode = constructorDeclaration.WithParameterList(newParameterList); return(context.Document.ReplaceNodeAsync(constructorDeclaration, newNode, cancellationToken)); }, GetEquivalenceKey(diagnostic)); context.RegisterCodeFix(codeAction, diagnostic); break; } case CompilerDiagnosticIdentifiers.ExplicitInterfaceDeclarationCanOnlyBeDeclaredInClassOrStruct: { if (!Settings.IsCodeFixEnabled(CodeFixIdentifiers.RemoveMemberDeclaration)) { break; } CodeFixRegistrator.RemoveMember(context, diagnostic, memberDeclaration); break; } } } }
public ConstructorNode(ConstructorDeclarationSyntax node) : base(node) { Node = node; DisplayText = node.Identifier.Text; }
private static bool IsEmptyConstructor(ConstructorDeclarationSyntax constructorDeclaration) => !constructorDeclaration.HasBodyOrExpressionBody() || (constructorDeclaration.Body != null && constructorDeclaration.Body.Statements.Count == 0);
private static bool IsConstructorParameterless(ConstructorDeclarationSyntax constructorDeclaration) { return(constructorDeclaration.ParameterList != null && !constructorDeclaration.ParameterList.Parameters.Any()); }
public static ConstructorDeclarationSyntax WithBodyStatements(this ConstructorDeclarationSyntax syntax, params StatementSyntax[] parameters) { return(syntax.WithBody(Block(parameters))); }
public static SyntaxNode RemoveModifierFromNode(SyntaxNode node, SyntaxKind modifier) { //there seem to be no base classes to support WithModifiers. //dynamic modifiersNode = node; //return modifiersNode.WithModifiers(SyntaxFactory.TokenList(modifiersNode.Modifiers.Where(m => !m.IsKind(SyntaxKind.PrivateKeyword)))); MethodDeclarationSyntax methodNode = node as MethodDeclarationSyntax; if (methodNode != null) { return(methodNode.WithModifiers(SyntaxFactory.TokenList(methodNode.Modifiers.Where(m => !m.IsKind(modifier)))) .WithLeadingTrivia(methodNode.GetLeadingTrivia())); } FieldDeclarationSyntax fieldNode = node as FieldDeclarationSyntax; if (fieldNode != null) { return(fieldNode.WithModifiers(SyntaxFactory.TokenList(fieldNode.Modifiers.Where(m => !m.IsKind(modifier)))) .WithLeadingTrivia(fieldNode.GetLeadingTrivia())); } PropertyDeclarationSyntax propertyNode = node as PropertyDeclarationSyntax; if (propertyNode != null) { return(propertyNode.WithModifiers(SyntaxFactory.TokenList(propertyNode.Modifiers.Where(m => !m.IsKind(modifier)))) .WithLeadingTrivia(propertyNode.GetLeadingTrivia())); } IndexerDeclarationSyntax indexerNode = node as IndexerDeclarationSyntax; if (indexerNode != null) { return(indexerNode.WithModifiers(SyntaxFactory.TokenList(indexerNode.Modifiers.Where(m => !m.IsKind(modifier)))) .WithLeadingTrivia(indexerNode.GetLeadingTrivia())); } EventDeclarationSyntax eventNode = node as EventDeclarationSyntax; if (eventNode != null) { return(eventNode.WithModifiers(SyntaxFactory.TokenList(eventNode.Modifiers.Where(m => !m.IsKind(modifier)))) .WithLeadingTrivia(eventNode.GetLeadingTrivia())); } ConstructorDeclarationSyntax ctrNode = node as ConstructorDeclarationSyntax; if (ctrNode != null) { return(ctrNode.WithModifiers(SyntaxFactory.TokenList(ctrNode.Modifiers.Where(m => !m.IsKind(modifier)))) .WithLeadingTrivia(ctrNode.GetLeadingTrivia())); } OperatorDeclarationSyntax opNode = node as OperatorDeclarationSyntax; if (opNode != null) { return(opNode.WithModifiers(SyntaxFactory.TokenList(opNode.Modifiers.Where(m => !m.IsKind(modifier)))) .WithLeadingTrivia(opNode.GetLeadingTrivia())); } ClassDeclarationSyntax classNode = node as ClassDeclarationSyntax; if (classNode != null) { return(classNode.WithModifiers(SyntaxFactory.TokenList(classNode.Modifiers.Where(m => !m.IsKind(modifier)))) .WithLeadingTrivia(classNode.GetLeadingTrivia())); } InterfaceDeclarationSyntax interfaceNode = node as InterfaceDeclarationSyntax; if (interfaceNode != null) { return(interfaceNode.WithModifiers(SyntaxFactory.TokenList(interfaceNode.Modifiers.Where(m => !m.IsKind(modifier)))) .WithLeadingTrivia(interfaceNode.GetLeadingTrivia())); } StructDeclarationSyntax structNode = node as StructDeclarationSyntax; if (structNode != null) { return(structNode.WithModifiers(SyntaxFactory.TokenList(structNode.Modifiers.Where(m => !m.IsKind(modifier)))) .WithLeadingTrivia(structNode.GetLeadingTrivia())); } var enumNode = node as EnumDeclarationSyntax; if (enumNode != null) { return(enumNode.WithModifiers(SyntaxFactory.TokenList(enumNode.Modifiers.Where(m => !m.IsKind(modifier)))) .WithLeadingTrivia(enumNode.GetLeadingTrivia())); } var delegateNode = node as DelegateDeclarationSyntax; if (delegateNode != null) { return(delegateNode.WithModifiers(SyntaxFactory.TokenList(delegateNode.Modifiers.Where(m => !m.IsKind(modifier)))) .WithLeadingTrivia(delegateNode.GetLeadingTrivia())); } return(node); }
public void AddFunction(ConstructorDeclarationSyntax node) { int nFunction = FunctionsByNumber.Count; Function f = new Function(this, nFunction, Model, Model.GetDeclaredSymbol(node)); Functions.Add(f.MethodSymbol, f); FunctionsByNumber.Add(f); }
public static ConstructorDeclarationSyntax WithParameters(this ConstructorDeclarationSyntax syntax, IEnumerable <ParameterSyntax> parameters) { return(syntax.WithParameterList(ParameterList(SeparatedList(parameters)))); }
public override void VisitConstructorDeclaration(ConstructorDeclarationSyntax node) { AddLocation(node.Identifier); base.VisitConstructorDeclaration(node); }
public void AddFunction(ConstructorDeclarationSyntax node, SemanticModel Model) { MethodSymbol ms = Model.GetDeclaredSymbol(node); AddFunction(ms, Model); }
private void CreateMethods() { // Generate Interface methods if (!string.IsNullOrEmpty(m_objectBuilder.Interface)) { var methodNodes = m_navigator.OfType <MyVisualSyntaxInterfaceMethodNode>(); foreach (var methodNode in methodNodes) { var methodSyntax = methodNode.GetMethodDeclaration(); ProcessNodes(new[] { methodNode }, ref methodSyntax); m_methodDeclarations.Add(methodSyntax); } } var events = m_navigator.OfType <MyVisualSyntaxEventNode>(); events.AddRange(m_navigator.OfType <MyVisualSyntaxKeyEventNode>()); // Generate Event methods // Take all events of same name and make a method out of theire bodies. while (events.Count > 0) { var firstEvent = events[0]; var eventsWithSameName = events.Where(@event => @event.ObjectBuilder.Name == firstEvent.ObjectBuilder.Name); var methodDeclaration = MySyntaxFactory.PublicMethodDeclaration( firstEvent.EventName, SyntaxKind.VoidKeyword, firstEvent.ObjectBuilder.OutputNames, firstEvent.ObjectBuilder.OuputTypes); ProcessNodes(eventsWithSameName, ref methodDeclaration); // Bind with VisualScriptingProxy in constructor. m_constructor = m_constructor.AddBodyStatements( MySyntaxFactory.DelegateAssignment( firstEvent.ObjectBuilder.Name, methodDeclaration.Identifier.ToString()) ); // unBind from visualScriptingProxy in dispose method m_disposeMethod = m_disposeMethod.AddBodyStatements( MySyntaxFactory.DelegateRemoval( firstEvent.ObjectBuilder.Name, methodDeclaration.Identifier.ToString()) ); m_methodDeclarations.Add(methodDeclaration); events.RemoveAll(@event => eventsWithSameName.Contains(@event)); } // There can be only one method from single input node. // Input nodes are of type Event. var inputs = m_navigator.OfType <MyVisualSyntaxInputNode>(); var outputs = m_navigator.OfType <MyVisualSyntaxOutputNode>(); if (inputs.Count > 0) { Debug.Assert(inputs.Count == 1); var input = inputs[0]; MethodDeclarationSyntax methodDeclaration = null; if (outputs.Count > 0) { List <string> outputParamNames = new List <string>(outputs[0].ObjectBuilder.Inputs.Count); List <string> outputParamTypes = new List <string>(outputs[0].ObjectBuilder.Inputs.Count); foreach (var outputData in outputs[0].ObjectBuilder.Inputs) { outputParamNames.Add(outputData.Name); outputParamTypes.Add(outputData.Type); } methodDeclaration = MySyntaxFactory.PublicMethodDeclaration("RunScript", SyntaxKind.BoolKeyword, input.ObjectBuilder.OutputNames, input.ObjectBuilder.OuputTypes, outputParamNames, outputParamTypes); } else { methodDeclaration = MySyntaxFactory.PublicMethodDeclaration("RunScript", SyntaxKind.BoolKeyword, input.ObjectBuilder.OutputNames, input.ObjectBuilder.OuputTypes); } ProcessNodes(new[] { input }, ref methodDeclaration, new[] { SyntaxFactory.ReturnStatement(SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression)) }); m_methodDeclarations.Add(methodDeclaration); } }
private async Task <Document> UpdateDataRowConstructor(Document document, TypeDeclarationSyntax typeDeclaration, ConstructorDeclarationSyntax constructorDeclaration, CancellationToken ct) { var unsetProperties = Helper.GetClassUnsetProperties(typeDeclaration, constructorDeclaration); SyntaxTriviaList leadingTrivia; SyntaxList <StatementSyntax> statements; if (constructorDeclaration.Body is null) { leadingTrivia = constructorDeclaration.GetLeadingTrivia(); } else { statements = constructorDeclaration.Body.Statements; leadingTrivia = statements.Any() ? statements.First().GetLeadingTrivia() : constructorDeclaration.GetLeadingTrivia(); } foreach (var property in unsetProperties) { var assigment = CreatePropertyAssigmentExpression(constructorDeclaration.ParameterList.Parameters[0], property); statements = statements.Add(SyntaxFactory.ExpressionStatement(assigment).WithLeadingTrivia(leadingTrivia)); } // Копируем параметры конструктора, заменяя только Body. var updatedConstructor = SyntaxFactory.ConstructorDeclaration(constructorDeclaration.AttributeLists, constructorDeclaration.Modifiers, constructorDeclaration.Identifier, constructorDeclaration.ParameterList, constructorDeclaration.Initializer, SyntaxFactory.Block(statements)); // Replace the old constructor declaration with the new local declaration. var oldRoot = await document.GetSyntaxRootAsync(ct); var newRoot = oldRoot.ReplaceNode(constructorDeclaration, updatedConstructor); // Return document with transformed tree. return(document.WithSyntaxRoot(newRoot)); }
/// <summary> /// /// </summary> /// <param name="node"></param> /// <param name="semanticModel"></param> /// <returns></returns> /// <remarks> /// Must be a type derived from <see cref="ConstructorDeclaration"/>. /// </remarks> protected virtual ConstructorDeclaration CreateHelper(ConstructorDeclarationSyntax node, SemanticModel semanticModel) { return(new ConstructorDeclaration(node, semanticModel)); }
public override void VisitConstructorDeclaration(ConstructorDeclarationSyntax node) { base.VisitConstructorDeclaration(node); Chunk.AddFunction(node, Model); }
private static int GetEndArgumentsLine(ConstructorDeclarationSyntax declarationSyntax) { var parametersCloseToken = declarationSyntax.ParameterList.CloseParenToken; return(parametersCloseToken.GetLocation().GetLineSpan().StartLinePosition.Line + 1); }
// Replace old ConstructorDeclarationSyntax with new one. public override SyntaxNode VisitConstructorDeclaration(ConstructorDeclarationSyntax node) { var updatedConstructorDeclaration = (ConstructorDeclarationSyntax)base.VisitConstructorDeclaration(node); // Get TypeSymbol corresponding to the containing ClassDeclarationSyntax for the // ConstructorDeclarationSyntax and check whether it is the same as the TypeSymbol // we are searching for. var classSymbol = (TypeSymbol)SemanticModel.GetDeclaredSymbol(node).ContainingSymbol; if (classSymbol.Equals(SearchSymbol)) { // Replace the identifier token containing the name of the class. SyntaxToken updatedIdentifierToken = Syntax.Identifier( updatedConstructorDeclaration.Identifier.LeadingTrivia, NewName, updatedConstructorDeclaration.Identifier.TrailingTrivia); updatedConstructorDeclaration = updatedConstructorDeclaration.WithIdentifier(updatedIdentifierToken); } return updatedConstructorDeclaration; }
public CodeActionEdit GetEdit(CancellationToken cancellationToken) { SyntaxNode root = (SyntaxNode)this.document.GetSyntaxRoot(cancellationToken); ISemanticModel model = this.document.GetSemanticModel(cancellationToken); TypeSyntax classTypeSyntax = this.expression.Type; // TODO: extract container info and propose solutions IDictionary <TypeSymbol, String> typeParametersMap = new Dictionary <TypeSymbol, String>(); SeparatedSyntaxList <ParameterSyntax> ctorParameters = Syntax.SeparatedList <ParameterSyntax>(); SeparatedSyntaxList <TypeParameterSyntax> typeParameters = Syntax.SeparatedList <TypeParameterSyntax>(); SyntaxList <StatementSyntax> ctorStatements = Syntax.List <StatementSyntax>(); SyntaxList <MemberDeclarationSyntax> classMembers = Syntax.List <MemberDeclarationSyntax>(); if (classTypeSyntax.Kind == SyntaxKind.IdentifierName) { } else if (classTypeSyntax.Kind == SyntaxKind.GenericName) { const string paramNames = "TUV"; int index = 0; GenericNameSyntax genericName = (GenericNameSyntax)classTypeSyntax; TypeArgumentListSyntax typeArgumentList = genericName.TypeArgumentList; foreach (TypeSyntax typeArgument in typeArgumentList.Arguments) { string typeParameterName = new string(paramNames[index % paramNames.Length], index / paramNames.Length + 1); TypeParameterSyntax typeParameter = Syntax.TypeParameter(typeParameterName); typeParametersMap.Add(model.GetTypeInfo(typeArgument, cancellationToken).Type as TypeSymbol, typeParameterName); typeParameters = typeParameters.Add(typeParameter); index += 1; } } else if (classTypeSyntax.Kind == SyntaxKind.QualifiedName) { } // Add comment SyntaxTrivia commentTrivia = Syntax.Comment("// TODO: Complete member initialization"); ctorStatements = ctorStatements.Add(Syntax.EmptyStatement().WithLeadingTrivia(commentTrivia)); int order = 0; ArgumentListSyntax argumentList = this.expression.ArgumentList; foreach (ArgumentSyntax argument in argumentList.Arguments) { // Generate new identifier SyntaxToken identifier = Syntax.Identifier(String.Format("param{0}", ++order)); // For named arguments use the associated name // Considers: // new foo(a: 2); -> foo(int a) { this.a = a; } if (argument.NameColon != null) { identifier = argument.NameColon.Identifier.Identifier; } // Determine argument type TypeSymbol typeSymbol = model.GetTypeInfo(argument.Expression, cancellationToken).Type as TypeSymbol; TypeSyntax typeSyntax = null; // Check if the type of parameter specified as template type // Considers: // new A<int>(1) -> class A<T> { A(>T< param) {} } if (typeParametersMap.ContainsKey(typeSymbol)) { typeSyntax = Syntax.ParseTypeName(typeParametersMap[typeSymbol]); } else { typeSyntax = Syntax.ParseTypeName(typeSymbol.ToDisplayString()); } // Create new parameter ParameterSyntax parameter = Syntax.Parameter(identifier) .WithType(typeSyntax); ctorParameters = ctorParameters.Add(parameter); // Create new field to store parameter value VariableDeclaratorSyntax variableDeclarator = Syntax.VariableDeclarator(identifier); VariableDeclarationSyntax variableDeclaration = Syntax.VariableDeclaration(typeSyntax) .WithVariables(Syntax.SeparatedList <VariableDeclaratorSyntax>(variableDeclarator)); FieldDeclarationSyntax fieldDeclaration = Syntax.FieldDeclaration(variableDeclaration) .WithModifiers(Syntax.TokenList(Syntax.Token(SyntaxKind.PrivateKeyword))) .WithTrailingTrivia(Syntax.EndOfLine("")); classMembers = classMembers.Add(fieldDeclaration); // Create ctor initializing statement: // Considers: // this.a = a; ExpressionStatementSyntax statement = Syntax.ExpressionStatement( Syntax.BinaryExpression(SyntaxKind.AssignExpression, Syntax.MemberAccessExpression(SyntaxKind.MemberAccessExpression, Syntax.ThisExpression(), Syntax.IdentifierName(identifier)), Syntax.IdentifierName(identifier) )); ctorStatements = ctorStatements.Add(statement); } ConstructorDeclarationSyntax ctorDeclaration = Syntax.ConstructorDeclaration(this.className) .WithModifiers(Syntax.TokenList(Syntax.Token(SyntaxKind.PublicKeyword))) .WithBody(Syntax.Block(ctorStatements)) .WithParameterList(Syntax.ParameterList(ctorParameters)); classMembers = classMembers.Add(ctorDeclaration); ClassDeclarationSyntax classDeclaration = Syntax.ClassDeclaration(this.className) .WithMembers(classMembers) .WithTrailingTrivia(Syntax.ElasticCarriageReturnLineFeed) .WithAdditionalAnnotations(CodeAnnotations.Formatting); if (typeParameters.Count > 0) { classDeclaration = classDeclaration.WithTypeParameterList(Syntax.TypeParameterList(typeParameters)); } CompilationUnitSyntax compilationUnit = this.expression.FirstAncestorOrSelf <CompilationUnitSyntax>(); CompilationUnitSyntax newCompilationUnit = compilationUnit.AddMembers(classDeclaration); SyntaxNode newRoot = root.ReplaceNode(compilationUnit, newCompilationUnit); return(new CodeActionEdit(document.UpdateSyntaxRoot(newRoot))); }
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { if (!Settings.IsEnabled(CodeFixIdentifiers.AddDocumentationComment) && !Settings.IsEnabled(CodeFixIdentifiers.ChangeMethodReturnType) && !Settings.IsEnabled(CodeFixIdentifiers.MemberTypeMustMatchOverriddenMemberType) && !Settings.IsEnabled(CodeFixIdentifiers.AddPartialModifier) && !Settings.IsEnabled(CodeFixIdentifiers.MakeContainingClassAbstract) && !Settings.IsEnabled(CodeFixIdentifiers.RemoveParametersFromStaticConstructor) && !Settings.IsEnabled(CodeFixIdentifiers.RemoveMemberDeclaration) && !Settings.IsEnabled(CodeFixIdentifiers.RenameDestructorToMatchClassName) && !Settings.IsEnabled(CodeFixIdentifiers.RenameTupleElement) && !Settings.IsEnabled(CodeFixIdentifiers.MarkDeclarationAsNonCLSCompliant)) { return; } SyntaxNode root = await context.GetSyntaxRootAsync().ConfigureAwait(false); if (!TryFindFirstAncestorOrSelf(root, context.Span, out MemberDeclarationSyntax memberDeclaration)) { return; } foreach (Diagnostic diagnostic in context.Diagnostics) { switch (diagnostic.Id) { case CompilerDiagnosticIdentifiers.MissingXmlCommentForPubliclyVisibleTypeOrMember: { if (!Settings.IsEnabled(CodeFixIdentifiers.AddDocumentationComment)) { break; } CodeAction codeAction = CodeAction.Create( "Add documentation comment", cancellationToken => AddDocumentationCommentRefactoring.RefactorAsync(context.Document, memberDeclaration, false, cancellationToken), GetEquivalenceKey(diagnostic)); context.RegisterCodeFix(codeAction, diagnostic); CodeAction codeAction2 = CodeAction.Create( "Add documentation comment (copy from base if available)", cancellationToken => AddDocumentationCommentRefactoring.RefactorAsync(context.Document, memberDeclaration, true, cancellationToken), GetEquivalenceKey(diagnostic, "CopyFromBaseIfAvailable")); context.RegisterCodeFix(codeAction2, diagnostic); break; } case CompilerDiagnosticIdentifiers.MethodReturnTypeMustMatchOverriddenMethodReturnType: { if (!Settings.IsEnabled(CodeFixIdentifiers.ChangeMethodReturnType)) { break; } SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); var methodSymbol = (IMethodSymbol)semanticModel.GetDeclaredSymbol(memberDeclaration, context.CancellationToken); ITypeSymbol typeSymbol = methodSymbol.OverriddenMethod.ReturnType; CodeFixRegistrator.ChangeTypeOrReturnType(context, diagnostic, memberDeclaration, typeSymbol, semanticModel); break; } case CompilerDiagnosticIdentifiers.PartialMethodsMustHaveVoidReturnType: { if (!Settings.IsEnabled(CodeFixIdentifiers.ChangeMethodReturnType)) { break; } SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); var methodDeclaration = (MethodDeclarationSyntax)memberDeclaration; MethodDeclarationSyntax otherPart = semanticModel.GetOtherPart(methodDeclaration, context.CancellationToken); if (otherPart == null) { break; } CodeAction codeAction = CodeAction.Create( "Change return type to 'void'", cancellationToken => { return(context.Document.Solution().ReplaceNodesAsync( new MethodDeclarationSyntax[] { methodDeclaration, otherPart }, (node, _) => node.WithReturnType(CSharpFactory.VoidType().WithTriviaFrom(node.ReturnType)), cancellationToken)); }, GetEquivalenceKey(diagnostic)); context.RegisterCodeFix(codeAction, diagnostic); break; } case CompilerDiagnosticIdentifiers.MemberTypeMustMatchOverriddenMemberType: { if (!Settings.IsEnabled(CodeFixIdentifiers.MemberTypeMustMatchOverriddenMemberType)) { break; } SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); ITypeSymbol typeSymbol = null; switch (memberDeclaration.Kind()) { case SyntaxKind.PropertyDeclaration: case SyntaxKind.IndexerDeclaration: { var propertySymbol = (IPropertySymbol)semanticModel.GetDeclaredSymbol(memberDeclaration, context.CancellationToken); typeSymbol = propertySymbol.OverriddenProperty.Type; break; } case SyntaxKind.EventDeclaration: { var eventSymbol = (IEventSymbol)semanticModel.GetDeclaredSymbol(memberDeclaration, context.CancellationToken); typeSymbol = eventSymbol.OverriddenEvent.Type; break; } case SyntaxKind.EventFieldDeclaration: { VariableDeclaratorSyntax declarator = ((EventFieldDeclarationSyntax)memberDeclaration).Declaration.Variables.First(); var eventSymbol = (IEventSymbol)semanticModel.GetDeclaredSymbol(declarator, context.CancellationToken); typeSymbol = eventSymbol.OverriddenEvent.Type; break; } } CodeFixRegistrator.ChangeTypeOrReturnType(context, diagnostic, memberDeclaration, typeSymbol, semanticModel); break; } case CompilerDiagnosticIdentifiers.MissingPartialModifier: case CompilerDiagnosticIdentifiers.PartialMethodMustBeDeclaredInPartialClassOrPartialStruct: { if (!Settings.IsEnabled(CodeFixIdentifiers.AddPartialModifier)) { break; } SyntaxNode node = null; switch (memberDeclaration.Kind()) { case SyntaxKind.MethodDeclaration: { if (memberDeclaration.IsParentKind(SyntaxKind.ClassDeclaration, SyntaxKind.StructDeclaration)) { node = memberDeclaration.Parent; } break; } case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.InterfaceDeclaration: { node = memberDeclaration; break; } } Debug.Assert(node != null, memberDeclaration.ToString()); if (node == null) { break; } ModifiersCodeFixRegistrator.AddModifier(context, diagnostic, node, SyntaxKind.PartialKeyword); break; } case CompilerDiagnosticIdentifiers.MemberIsAbstractButItIsContainedInNonAbstractClass: { if (!Settings.IsEnabled(CodeFixIdentifiers.MakeContainingClassAbstract)) { break; } if (!memberDeclaration.IsParentKind(SyntaxKind.ClassDeclaration)) { break; } ModifiersCodeFixRegistrator.AddModifier( context, diagnostic, memberDeclaration.Parent, SyntaxKind.AbstractKeyword, title: "Make containing class abstract"); break; } case CompilerDiagnosticIdentifiers.StaticConstructorMustBeParameterless: { if (!Settings.IsEnabled(CodeFixIdentifiers.RemoveParametersFromStaticConstructor)) { break; } var constructorDeclaration = (ConstructorDeclarationSyntax)memberDeclaration; CodeAction codeAction = CodeAction.Create( "Remove parameters", cancellationToken => { ParameterListSyntax parameterList = constructorDeclaration.ParameterList; ParameterListSyntax newParameterList = parameterList .WithParameters(default(SeparatedSyntaxList <ParameterSyntax>)) .WithOpenParenToken(parameterList.OpenParenToken.WithoutTrailingTrivia()) .WithCloseParenToken(parameterList.CloseParenToken.WithoutLeadingTrivia()); ConstructorDeclarationSyntax newNode = constructorDeclaration.WithParameterList(newParameterList); return(context.Document.ReplaceNodeAsync(constructorDeclaration, newNode, cancellationToken)); }, GetEquivalenceKey(diagnostic)); context.RegisterCodeFix(codeAction, diagnostic); break; } case CompilerDiagnosticIdentifiers.ExplicitInterfaceDeclarationCanOnlyBeDeclaredInClassOrStruct: case CompilerDiagnosticIdentifiers.InterfacesCannotContainFields: case CompilerDiagnosticIdentifiers.InterfacesCannotContainOperators: case CompilerDiagnosticIdentifiers.InterfacesCannotDeclareTypes: case CompilerDiagnosticIdentifiers.OnlyClassTypesCanContainDestructors: case CompilerDiagnosticIdentifiers.StructsCannotContainExplicitParameterlessConstructors: { if (!Settings.IsEnabled(CodeFixIdentifiers.RemoveMemberDeclaration)) { break; } CodeFixRegistrator.RemoveMemberDeclaration(context, diagnostic, memberDeclaration); break; } case CompilerDiagnosticIdentifiers.NameOfDestructorMustMatchNameOfClass: { if (!Settings.IsEnabled(CodeFixIdentifiers.RenameDestructorToMatchClassName)) { break; } if (!(memberDeclaration is DestructorDeclarationSyntax destructorDeclaration)) { break; } if (!(memberDeclaration.Parent is ClassDeclarationSyntax classDeclaration)) { break; } if (classDeclaration.Identifier.ValueText.Length == 0) { break; } CodeAction codeAction = CodeAction.Create( "Rename destructor to match class name", cancellationToken => { DestructorDeclarationSyntax newNode = destructorDeclaration.WithIdentifier(classDeclaration.Identifier.WithTriviaFrom(destructorDeclaration.Identifier)); return(context.Document.ReplaceNodeAsync(destructorDeclaration, newNode, cancellationToken)); }, GetEquivalenceKey(diagnostic)); context.RegisterCodeFix(codeAction, diagnostic); break; } case CompilerDiagnosticIdentifiers.CannotChangeTupleElementNameWhenOverridingInheritedMember: { if (!Settings.IsEnabled(CodeFixIdentifiers.RenameTupleElement)) { break; } SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); if (memberDeclaration is MethodDeclarationSyntax methodDeclaration) { IMethodSymbol methodSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration, context.CancellationToken); if (!(methodSymbol.ReturnType is INamedTypeSymbol tupleType)) { break; } if (!tupleType.IsTupleType) { break; } if (!(methodSymbol.OverriddenMethod?.ReturnType is INamedTypeSymbol baseTupleType)) { break; } if (!baseTupleType.IsTupleType) { break; } ImmutableArray <IFieldSymbol> elements = tupleType.TupleElements; ImmutableArray <IFieldSymbol> baseElements = baseTupleType.TupleElements; if (elements.Length != baseElements.Length) { break; } int i = 0; while (i < elements.Length) { if (elements[i].Name != baseElements[i].Name) { break; } i++; } if (i == elements.Length) { break; } TupleElementSyntax tupleElement = ((TupleTypeSyntax)methodDeclaration.ReturnType).Elements[i]; CodeAction codeAction = CodeAction.Create( $"Rename '{elements[i].Name}' to '{baseElements[i].Name}'", ct => RenameTupleElementAsync(context.Document, methodDeclaration, tupleElement, elements[i], baseElements[i].Name, semanticModel, ct), GetEquivalenceKey(diagnostic)); context.RegisterCodeFix(codeAction, diagnostic); } else if (memberDeclaration is PropertyDeclarationSyntax propertyDeclaration) { IPropertySymbol propertySymbol = semanticModel.GetDeclaredSymbol(propertyDeclaration, context.CancellationToken); if (!(propertySymbol.Type is INamedTypeSymbol tupleType)) { break; } if (!tupleType.IsTupleType) { break; } if (!(propertySymbol.OverriddenProperty?.Type is INamedTypeSymbol baseTupleType)) { break; } if (!baseTupleType.IsTupleType) { break; } ImmutableArray <IFieldSymbol> elements = tupleType.TupleElements; ImmutableArray <IFieldSymbol> baseElements = baseTupleType.TupleElements; if (elements.Length != baseElements.Length) { break; } int i = 0; while (i < elements.Length) { if (elements[i].Name != baseElements[i].Name) { break; } i++; } if (i == elements.Length) { break; } TupleElementSyntax tupleElement = ((TupleTypeSyntax)propertyDeclaration.Type).Elements[i]; CodeAction codeAction = CodeAction.Create( $"Rename '{elements[i].Name}' to '{baseElements[i].Name}'", ct => RenameTupleElementAsync(context.Document, propertyDeclaration, tupleElement, elements[i], baseElements[i].Name, semanticModel, ct), GetEquivalenceKey(diagnostic)); context.RegisterCodeFix(codeAction, diagnostic); } break; } case CompilerDiagnosticIdentifiers.MethodsWithVariableArgumentsAreNotCLSCompliant: case CompilerDiagnosticIdentifiers.ArgumentTypeIsNotCLSCompliant: case CompilerDiagnosticIdentifiers.ReturnTypeIsNotCLSCompliant: case CompilerDiagnosticIdentifiers.TypeOfVariableIsNotCLSCompliant: case CompilerDiagnosticIdentifiers.IdentifierDifferingOnlyInCaseIsNotCLSCompliant: case CompilerDiagnosticIdentifiers.OverloadedMethodDifferingOnlyInRefOrOutOrInArrayRankIsNotCLSCompliant: case CompilerDiagnosticIdentifiers.OverloadedMethodDifferingOnlyByUnnamedArrayTypesIsNotCLSCompliant: case CompilerDiagnosticIdentifiers.IdentifierIsNotCLSCompliant: case CompilerDiagnosticIdentifiers.BaseTypeIsNotCLSCompliant: case CompilerDiagnosticIdentifiers.ArraysAsAttributeArgumentsIsNotCLSCompliant: case CompilerDiagnosticIdentifiers.ConstraintTypeIsNotCLSCompliant: case CompilerDiagnosticIdentifiers.TypeIsNotCLSCompliantBecauseBaseInterfaceIsNotCLSCompliant: { if (!Settings.IsEnabled(CodeFixIdentifiers.MarkDeclarationAsNonCLSCompliant)) { break; } CodeAction codeAction = CodeAction.Create( $"Mark {CSharpFacts.GetTitle(memberDeclaration)} as non-CLS-compliant", ct => MarkDeclarationAsNonCLSCompliantAsync(context.Document, memberDeclaration, ct), GetEquivalenceKey(diagnostic)); context.RegisterCodeFix(codeAction, diagnostic); break; } } } }
public override void VisitConstructorDeclaration(ConstructorDeclarationSyntax node) { _members.Add(node); }
public static ConstructorDeclarationSyntax WithBodyStatements(this ConstructorDeclarationSyntax syntax, IEnumerable <StatementSyntax> parameters) { return(syntax.WithBody(Block(parameters))); }
public override SyntaxNode VisitConstructorDeclaration(ConstructorDeclarationSyntax node) { ConstructorDeclarationSyntax processedDeclaration = (ConstructorDeclarationSyntax)base.VisitConstructorDeclaration(node); // Make the constructor declaration private if it has other access modifier SyntaxTokenList modifiers = processedDeclaration.Modifiers; // Static constructors are different story if (modifiers.Any(SyntaxKind.StaticKeyword)) { return(processedDeclaration); } // If it is already declared as private, do nothing if (!modifiers.Any(SyntaxKind.PrivateKeyword)) { if (modifiers.Any(SyntaxKind.PublicKeyword) || modifiers.Any(SyntaxKind.ProtectedKeyword)) { // If there is already access modified, replace it with `private' keyword. // Considers: // public A() {} -> private A() {} // protected A() {} -> private A() {} SyntaxToken accessKeyword = processedDeclaration.GetFirstToken(t => t.Kind == SyntaxKind.PublicKeyword || t.Kind == SyntaxKind.ProtectedKeyword); // Copy leading and trailing trivia SyntaxToken privateKeyword = Syntax.Token(SyntaxKind.PrivateKeyword) .WithLeadingTrivia(accessKeyword.LeadingTrivia) .WithTrailingTrivia(accessKeyword.TrailingTrivia); // Replace the access modifier ConstructorDeclarationSyntax newDeclaration = processedDeclaration.ReplaceToken(accessKeyword, privateKeyword); return(newDeclaration); } else { // Otherwise, insert `private' at the beginning. // Considers: // A() {} -> private A() {} // Copy trivia from first token SyntaxToken firstToken = processedDeclaration.GetFirstToken(); // Copy leading and trailing trivia SyntaxToken privateKeyword = Syntax.Token(SyntaxKind.PrivateKeyword) .WithLeadingTrivia(firstToken.LeadingTrivia) .WithTrailingTrivia(firstToken.TrailingTrivia); // Remove the leading trivia from first token ConstructorDeclarationSyntax newDeclaration = processedDeclaration.ReplaceToken(firstToken, firstToken.WithLeadingTrivia(Syntax.Whitespace(" "))); // Insert the access modifier newDeclaration = newDeclaration .WithModifiers(newDeclaration.Modifiers.Insert(0, privateKeyword)); return(newDeclaration); } } return(processedDeclaration); }
public string Signature(bool forSorting) { string prefix = forSorting ? ClassPath + "." : ""; if (!forSorting && IsStatic) { prefix = "static "; } { MethodDeclarationSyntax method = Member as MethodDeclarationSyntax; if (method != null) { var signature = new System.Text.StringBuilder(); if (forSorting) { signature.Append($"{ClassPath}.{method.Identifier}("); } else { signature.Append($"{prefix}{method.ReturnType} {method.Identifier}("); } int parameterCount = method.ParameterList.Parameters.Count; for (int i = 0; i < parameterCount; i++) { if (i > 0) { signature.Append(", "); } var parameter = method.ParameterList.Parameters[i]; for (int j = 0; j < parameter.Modifiers.Count; j++) { signature.Append(parameter.Modifiers[j].Text); signature.Append(" "); } string paramType = parameter.Type.ToString(); int angleIndex = paramType.IndexOf('<'); if (angleIndex > 0) { string prefixType = paramType.Substring(0, angleIndex); int prefixIndex = prefixType.LastIndexOf('.'); if (prefixIndex > 0) { prefixType = prefixType.Substring(prefixIndex + 1); } string genericType = paramType.Substring(angleIndex + 1); int genericIndex = genericType.LastIndexOf('.'); if (genericIndex > 0) { genericType = genericType.Substring(genericIndex + 1); } paramType = prefixType + "<" + genericType; } else { int index = paramType.LastIndexOf('.'); if (index > 0) { paramType = paramType.Substring(index + 1); } } signature.Append(paramType); if (!forSorting) { signature.Append($" {parameter.Identifier}"); } } signature.Append(")"); return(signature.ToString()); } } { PropertyDeclarationSyntax property = Member as PropertyDeclarationSyntax; if (property != null) { var signature = new System.Text.StringBuilder(); if (forSorting) { signature.Append($"{ClassPath}.{property.Identifier}"); } else { string proptype = $"{property.Type}"; int index = proptype.LastIndexOf('.'); if (index > 0) { proptype = proptype.Substring(index + 1); } signature.Append($"{prefix}{proptype} {property.Identifier}"); } return(signature.ToString()); } } { EventDeclarationSyntax evt = Member as EventDeclarationSyntax; if (evt != null) { var signature = new System.Text.StringBuilder(); signature.Append($"{prefix}{evt.Identifier}"); return(signature.ToString()); } } { OperatorDeclarationSyntax op = Member as OperatorDeclarationSyntax; if (op != null) { var signature = new System.Text.StringBuilder(); signature.Append($"{prefix}{op.OperatorToken}"); return(signature.ToString()); } } { EventFieldDeclarationSyntax eventField = Member as EventFieldDeclarationSyntax; if (eventField != null) { var signature = new System.Text.StringBuilder(); string declaration = eventField.ToString(); int index = declaration.LastIndexOf(' '); declaration = declaration.Substring(index + 1, declaration.Length - 1 - (index + 1)); signature.Append($"{prefix}{declaration}"); return(signature.ToString()); } } { ConstructorDeclarationSyntax constructor = Member as ConstructorDeclarationSyntax; if (constructor != null) { var signature = new System.Text.StringBuilder(); if (forSorting) { signature.Append($"{ClassPath}("); } else { if (IsStatic) { signature.Append("static "); } var parent = new ParsedType(Member.Parent as BaseTypeDeclarationSyntax, null); signature.Append($"{parent.Name}("); } int parameterCount = constructor.ParameterList.Parameters.Count; for (int i = 0; i < parameterCount; i++) { if (i > 0) { signature.Append(", "); } var parameter = constructor.ParameterList.Parameters[i]; string paramType = parameter.Type.ToString(); int angleIndex = paramType.IndexOf('<'); if (angleIndex > 0) { string prefixType = paramType.Substring(0, angleIndex); int prefixIndex = prefixType.LastIndexOf('.'); if (prefixIndex > 0) { prefixType = prefixType.Substring(prefixIndex + 1); } string genericType = paramType.Substring(angleIndex + 1); int genericIndex = genericType.LastIndexOf('.'); if (genericIndex > 0) { genericType = genericType.Substring(genericIndex + 1); } paramType = prefixType + "<" + genericType; } else { int index = paramType.LastIndexOf('.'); if (index > 0) { paramType = paramType.Substring(index + 1); } } signature.Append(paramType); if (!forSorting) { signature.Append($" {parameter.Identifier}"); } } signature.Append(")"); return(signature.ToString()); } } { EnumMemberDeclarationSyntax enumMember = Member as EnumMemberDeclarationSyntax; if (enumMember != null) { var signature = enumMember.ToString(); var items = signature.Split(new char[] { '\n' }); signature = items[items.Length - 1]; return(signature); } } throw new NotImplementedException(); }
private static Func <CancellationToken, Task <Document> > GetCreateChangedDocument(CodeFixContext context, SyntaxNode node) { switch (node.Kind()) { case SyntaxKind.MethodDeclaration: { var methodDeclaration = (MethodDeclarationSyntax)node; SyntaxToken semicolonToken = methodDeclaration.SemicolonToken; if (semicolonToken.Kind() == SyntaxKind.None) { break; } ParameterListSyntax parameterList = methodDeclaration.ParameterList; if (parameterList == null) { break; } return(cancellationToken => { MethodDeclarationSyntax newNode = methodDeclaration .WithParameterList(parameterList.AppendToTrailingTrivia(semicolonToken.GetAllTrivia())) .WithSemicolonToken(default(SyntaxToken)) .WithBody(Block()) .WithFormatterAnnotation(); return context.Document.ReplaceNodeAsync(node, newNode, cancellationToken); }); } case SyntaxKind.ConstructorDeclaration: { var constructorDeclaration = (ConstructorDeclarationSyntax)node; SyntaxToken semicolonToken = constructorDeclaration.SemicolonToken; if (semicolonToken.Kind() == SyntaxKind.None) { break; } ParameterListSyntax parameterList = constructorDeclaration.ParameterList; if (parameterList == null) { break; } return(cancellationToken => { ConstructorDeclarationSyntax newNode = constructorDeclaration .WithParameterList(parameterList.AppendToTrailingTrivia(semicolonToken.GetAllTrivia())) .WithSemicolonToken(default(SyntaxToken)) .WithBody(Block()) .WithFormatterAnnotation(); return context.Document.ReplaceNodeAsync(node, newNode, cancellationToken); }); } case SyntaxKind.DestructorDeclaration: { var destructorDeclaration = (DestructorDeclarationSyntax)node; SyntaxToken semicolonToken = destructorDeclaration.SemicolonToken; if (semicolonToken.Kind() == SyntaxKind.None) { break; } ParameterListSyntax parameterList = destructorDeclaration.ParameterList; if (parameterList == null) { break; } return(cancellationToken => { DestructorDeclarationSyntax newNode = destructorDeclaration .WithParameterList(parameterList.AppendToTrailingTrivia(semicolonToken.GetAllTrivia())) .WithSemicolonToken(default(SyntaxToken)) .WithBody(Block()) .WithFormatterAnnotation(); return context.Document.ReplaceNodeAsync(node, newNode, cancellationToken); }); } case SyntaxKind.OperatorDeclaration: { var operatorDeclaration = (OperatorDeclarationSyntax)node; SyntaxToken semicolonToken = operatorDeclaration.SemicolonToken; if (semicolonToken.Kind() == SyntaxKind.None) { break; } ParameterListSyntax parameterList = operatorDeclaration.ParameterList; if (parameterList == null) { break; } return(cancellationToken => { OperatorDeclarationSyntax newNode = operatorDeclaration .WithParameterList(parameterList.AppendToTrailingTrivia(semicolonToken.GetAllTrivia())) .WithSemicolonToken(default(SyntaxToken)) .WithBody(Block()) .WithFormatterAnnotation(); return context.Document.ReplaceNodeAsync(node, newNode, cancellationToken); }); } case SyntaxKind.ConversionOperatorDeclaration: { var conversionOperatorDeclaration = (ConversionOperatorDeclarationSyntax)node; SyntaxToken semicolonToken = conversionOperatorDeclaration.SemicolonToken; if (semicolonToken.Kind() == SyntaxKind.None) { break; } ParameterListSyntax parameterList = conversionOperatorDeclaration.ParameterList; if (parameterList == null) { break; } return(cancellationToken => { ConversionOperatorDeclarationSyntax newNode = conversionOperatorDeclaration .WithParameterList(parameterList.AppendToTrailingTrivia(semicolonToken.GetAllTrivia())) .WithSemicolonToken(default(SyntaxToken)) .WithBody(Block()) .WithFormatterAnnotation(); return context.Document.ReplaceNodeAsync(node, newNode, cancellationToken); }); } case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: { var accessorDeclaration = (AccessorDeclarationSyntax)node; SyntaxToken semicolonToken = accessorDeclaration.SemicolonToken; if (semicolonToken.Kind() == SyntaxKind.None) { break; } return(cancellationToken => { AccessorDeclarationSyntax newNode = accessorDeclaration .WithSemicolonToken(default(SyntaxToken)) .WithBody(Block( Token(default(SyntaxTriviaList), SyntaxKind.OpenBraceToken, TriviaList(ElasticSpace)), default(SyntaxList <StatementSyntax>), Token(default(SyntaxTriviaList), SyntaxKind.CloseBraceToken, semicolonToken.LeadingAndTrailingTrivia()))); SyntaxToken keyword = newNode.Keyword; if (!keyword.HasTrailingTrivia) { newNode = newNode.WithKeyword(keyword.WithTrailingTrivia(ElasticSpace)); } return context.Document.ReplaceNodeAsync(node, newNode, cancellationToken); }); } case SyntaxKind.LocalFunctionStatement: { var localFunction = (LocalFunctionStatementSyntax)node; SyntaxToken semicolonToken = localFunction.SemicolonToken; if (semicolonToken.Kind() == SyntaxKind.None) { break; } ParameterListSyntax parameterList = localFunction.ParameterList; if (parameterList == null) { break; } return(cancellationToken => { LocalFunctionStatementSyntax newNode = localFunction .WithParameterList(parameterList.AppendToTrailingTrivia(semicolonToken.GetAllTrivia())) .WithSemicolonToken(default(SyntaxToken)) .WithBody(Block()) .WithFormatterAnnotation(); return context.Document.ReplaceNodeAsync(node, newNode, cancellationToken); }); } } Debug.Fail(node.Kind().ToString()); return(null); }
private async Task <Document> ReplacePublicWithProtectedAsync(Document document, ConstructorDeclarationSyntax ctor, CancellationToken cancellationToken) { var @public = ctor.Modifiers.First(m => m.IsKind(SyntaxKind.PublicKeyword)); var @protected = SyntaxFactory.Token(@public.LeadingTrivia, SyntaxKind.ProtectedKeyword, @public.TrailingTrivia); var newModifiers = ctor.Modifiers.Replace(@public, @protected); var newCtor = ctor.WithModifiers(newModifiers); var root = await document.GetSyntaxRootAsync(cancellationToken); var newRoot = root.ReplaceNode(ctor, newCtor); var newDocument = document.WithSyntaxRoot(newRoot); return(newDocument); }
private bool IsConstructorDocumentationGenerated(ConstructorDeclarationSyntax declaration) { return(new GeneratedConstructorCommentsChecker(declaration, _config, _metrics).IsGenerated()); }
public override void VisitConstructorDeclaration(ConstructorDeclarationSyntax node) { Visit(node.Initializer); VisitBodyOrExpressionBody(node.Body, node.ExpressionBody); //base.VisitConstructorDeclaration(node); }
public static void Write(string path) { StringBuilder js = new StringBuilder(); var keys = BindingClass.AllJavascriptClasses.Keys.ToList(); keys.Sort(); foreach (var key in keys) { var jsclass = GetJS(key); var rhcommon = RhinoCommonClass.Get(key); var doccomment = rhcommon.DocComment; js.AppendLine("/**"); if (doccomment == null) { js.AppendLine($" * {jsclass.ClassName}"); } else { string comment = doccomment.ToString(); comment = comment.Replace("///", ""); js.Append(comment); } if (!string.IsNullOrEmpty(jsclass.BaseClass)) { js.AppendLine($" * @extends {jsclass.BaseClass}"); } if (jsclass.Constructors.Count == 0) { js.AppendLine(" * @hideconstructor"); } js.AppendLine(" */"); js.AppendLine($"class {jsclass.ClassName} {{"); foreach (var constructor in jsclass.Constructors) { var c = rhcommon.GetConstructor(constructor); if (c == null) { continue; } ConstructorDeclarationSyntax constructorDecl = c.Item1; doccomment = c.Item2; if (constructorDecl != null) { List <string> paramNames = null; js.AppendLine(" /**"); if (doccomment != null) { string s = DocCommentToJsDoc(doccomment, null, constructorDecl.ParameterList, out paramNames); js.Append(s); } js.AppendLine(" */"); js.Append(" constructor("); if (paramNames != null) { string parameters = ""; foreach (var p in paramNames) { parameters += p + ","; } if (!string.IsNullOrWhiteSpace(parameters)) { parameters = parameters.Substring(0, parameters.Length - 1); js.Append(parameters); } } js.AppendLine("){}"); } } foreach (var(isStatic, method, args) in jsclass.Methods) { MethodDeclarationSyntax methodDecl = null; doccomment = null; for (int i = 0; i < rhcommon.Methods.Count; i++) { if (method.Equals(rhcommon.Methods[i].Item1.Identifier.ToString(), StringComparison.InvariantCultureIgnoreCase)) { methodDecl = rhcommon.Methods[i].Item1; doccomment = rhcommon.Methods[i].Item2; break; } } List <string> paramNames = new List <string>(); if (doccomment == null) { js.AppendLine(" /** ... */"); } else { js.AppendLine(" /**"); string s = DocCommentToJsDoc(doccomment, methodDecl, methodDecl.ParameterList, out paramNames); js.Append(s); js.AppendLine(" */"); } string parameters = ""; foreach (var p in paramNames) { parameters += p + ","; } if (!string.IsNullOrEmpty(parameters)) { parameters = parameters.Substring(0, parameters.Length - 1); } if (isStatic) { js.Append($" static {method}({parameters}) {{"); } else { js.Append($" {method}({parameters}) {{"); } js.AppendLine(" }"); } foreach (var prop in jsclass.Properties) { PropertyDeclarationSyntax propDecl = null; doccomment = null; for (int i = 0; i < rhcommon.Properties.Count; i++) { if (prop.Equals(rhcommon.Properties[i].Item1.Identifier.ToString(), StringComparison.InvariantCultureIgnoreCase)) { propDecl = rhcommon.Properties[i].Item1; doccomment = rhcommon.Properties[i].Item2; break; } } js.AppendLine(" /**"); if (doccomment != null) { string comment = DocCommentToJsDoc(doccomment, propDecl); js.Append(comment); } if (propDecl != null) { js.AppendLine($" * @type {{{ToJavascriptType(propDecl.Type.ToString())}}}"); } js.AppendLine(" */"); js.AppendLine($" get {prop}() {{ return null;}}"); } js.AppendLine("}"); } System.IO.File.WriteAllText(path, js.ToString()); }
private static bool IsSinglePublicConstructor(ConstructorDeclarationSyntax constructorDeclaration, SemanticModel semanticModel) { return(constructorDeclaration.Modifiers.Any(modifier => modifier.IsKind(SyntaxKind.PublicKeyword)) && IsInitializerEmptyOrRedundant(constructorDeclaration.Initializer) && TypeHasExactlyOneConstructor(constructorDeclaration, semanticModel)); }
private static void AppendMethodIdentifier(ConstructorDeclarationSyntax syntax, StringBuilder builder) { builder.Append(syntax.Identifier.ValueText); }
internal MethodMemberBuilder(NamedTypeSymbol container, Binder enclosing, ConstructorDeclarationSyntax syntax, DiagnosticBag diagnostics) : this(container, enclosing, (MemberDeclarationSyntax)syntax, diagnostics) { }
private static void _Assert_IsLastLink(ConstructorSyntaxLink link, ClassDeclarationSyntax classDeclarationSyntax, ConstructorDeclarationSyntax ctorSyntax) { Assert.AreEqual(link.CtorSyntax, ctorSyntax); Assert.AreEqual(link.OwingClassSyntax, classDeclarationSyntax); Assert.IsFalse(link.PathToNextCtorSyntax.Exists); Assert.IsFalse(link.NextLink.Exists); }
public void VisitConstructorDeclaration(ConstructorDeclarationSyntax node) { if (node == null) throw new ArgumentNullException("node"); node.Validate(); WriteLeadingTrivia(node); _writer.WriteIndent(); WriteAttributes( node, _writer.Configuration.LineBreaksAndWrapping.Other.PlaceMethodAttributeOnSameLine ); WriteMemberModifiers(node.Modifiers); _writer.WriteIdentifier(node.Identifier); node.ParameterList.Accept(this); if (node.Initializer != null) node.Initializer.Accept(this); node.Body.Accept(this); WriteTrailingTrivia(node); }
private static void _Assert_IsIntermadiateLink(ConstructorSyntaxLink link, ClassDeclarationSyntax classDeclarationSyntax, ConstructorDeclarationSyntax ctorDeclarationSyntax) { Assert.AreEqual(link.CtorSyntax, ctorDeclarationSyntax); Assert.AreEqual(link.OwingClassSyntax, classDeclarationSyntax); Assert.AreEqual(link.PathToNextCtorSyntax.Value, ctorDeclarationSyntax.DescendantNodes().OfType <ConstructorInitializerSyntax>().Single()); }
public override void VisitConstructorDeclaration(ConstructorDeclarationSyntax node) { base.VisitConstructorDeclaration(node); }
public static ConstructorDeclarationSyntax WithBlockBody(this ConstructorDeclarationSyntax ctor, params object[] code) => WithBody(code, null, ctor.WithBody);
public void Add(ConstructorDeclarationSyntax node) { Add(Chunk.Model.GetDeclaredSymbol(node)); /* FlatArrayBuilder fab = new FlatArrayBuilder(); MethodSymbol ms = Chunk.Model.GetDeclaredSymbol(node); fab.Add(FlatValue.Int32(ms.IsStatic ? (int)ClassMemberType.StaticMethod : (int)ClassMemberType.Method)); fab.Add(FlatValue.String(ms.GetFullyQualifiedName())); Function f; if (!Chunk.Functions.TryGetValue(ms, out f)) { throw new NotImplementedException("Method not found "+ms.ToString()); } fab.Add(FlatValue.Int32(f.NumFunction)); Members.Add(fab.GetFlatValue()); * */ }
public static ConstructorDeclarationSyntax WithBody(this ConstructorDeclarationSyntax ctor, params object[] code) => WithBody(code, x => ctor.WithExpressionBody(x).WithSemicolonToken(s_semicolonToken), ctor.WithBody);
public static ConstructorDeclarationSyntax AddModifiers(this ConstructorDeclarationSyntax syntax, params SyntaxKind[] modifier) { return(syntax.AddModifiers(modifier.Select(Token).ToArray())); }
public SyntaxNode ConstructorPrefixerDeclaration(ConstructorDeclarationSyntax node) { node = node.WithBody(node.Body.WithStatements(node.Body.Statements.Insert(0, Syntax.ExpressionStatement(Syntax.InvocationExpression(Syntax.IdentifierName(".prector")))))); return node; }