当前位置: 首页>>代码示例>>C#>>正文


C# SyntaxList.Add方法代码示例

本文整理汇总了C#中Microsoft.CodeAnalysis.CSharp.Syntax.SyntaxList.Add方法的典型用法代码示例。如果您正苦于以下问题:C# SyntaxList.Add方法的具体用法?C# SyntaxList.Add怎么用?C# SyntaxList.Add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Microsoft.CodeAnalysis.CSharp.Syntax.SyntaxList的用法示例。


在下文中一共展示了SyntaxList.Add方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: VisitClassDeclaration

        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.CSharpKind() == 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.CSharpKind())
                            {
                                case SyntaxKind.GetAccessorDeclaration:
                                    implementfield = true;
                                    newAccessors = newAccessors.Add(accessor.WithBody(SyntaxFactory.Block(SyntaxFactory.ReturnStatement(SyntaxFactory.IdentifierName("_" + prop.Identifier.ValueText)))));
                                    break;
                                case SyntaxKind.SetAccessorDeclaration:
                                    implementfield = true;
                                    newAccessors = newAccessors.Add(accessor.WithBody(SyntaxFactory.Block(SyntaxFactory.ExpressionStatement(SyntaxFactory.BinaryExpression(SyntaxKind.SimpleAssignmentExpression, SyntaxFactory.IdentifierName("_" + prop.Identifier.ValueText), SyntaxFactory.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(SyntaxFactory.VariableDeclarator("_" + prop.Identifier.ValueText));
                        newMembers = newMembers.Add(SyntaxFactory.FieldDeclaration(SyntaxFactory.VariableDeclaration(prop.Type, variables)).WithModifiers(prop.Modifiers));
                    }

                    newMembers = newMembers.Add(prop.WithAccessorList(prop.AccessorList.WithAccessors(newAccessors)));
                }
                else
                {
                    newMembers = newMembers.Add(member);
                }
            }
            return node.WithMembers(newMembers);
        }
开发者ID:LaxLacks,项目名称:ls2csc,代码行数:51,代码来源:AutoImplementedPropertyRewriter.cs

示例2: AttributeListList

 public static SyntaxList<AttributeListSyntax> AttributeListList(params AttributeSyntax[] attributes)
 {
     var list = new SyntaxList<AttributeListSyntax>();
     foreach (AttributeSyntax attributeSyntax in attributes)
     {
         list = list.Add(AttributeList(attributeSyntax));
     }
     return list;
 }
开发者ID:cdsalmons,项目名称:OrleansTemplates,代码行数:9,代码来源:AttributeUtils.cs

示例3: CreateSection

        private static SwitchSectionSyntax CreateSection(SwitchLabelSyntax label, StatementSyntax statement)
        {
            var labels = new SyntaxList<SwitchLabelSyntax>();
            labels = labels.Add(label);

            return SyntaxFactory.SwitchSection(
                labels, CreateSectionStatements(statement)
                );
        }
开发者ID:JeanLLopes,项目名称:code-cracker,代码行数:9,代码来源:ConvertToSwitchCodeFixProvider.cs

示例4: MockClass

        public static SyntaxNode MockClass(SyntaxTree tree, SemanticModel semanticModel, ClassDeclarationSyntax classNode)
        {
            SyntaxNode root = tree.GetRoot();
            Console.WriteLine("Class name: " + classNode.Identifier.Text);

            SyntaxList<MemberDeclarationSyntax> members = new SyntaxList<MemberDeclarationSyntax>();

            List<string> usedNames = new List<string>();

            foreach (var member in classNode.Members)
            {
                if (member is MethodDeclarationSyntax)
                {
                    var method = (MethodDeclarationSyntax)member;
                    Console.WriteLine("\tMethod name: " + method.Identifier.Text);

                    IMethodSymbol methodSemanticData = semanticModel.GetDeclaredSymbol(method) as IMethodSymbol;
                    members = members.Add(CreateMethodDelegate(method, methodSemanticData, usedNames));
                    members = members.Add(CreateMethodBody(method, methodSemanticData, usedNames));
                }
                else if (member is PropertyDeclarationSyntax)
                {
                    var property = (PropertyDeclarationSyntax)member;
                    Console.WriteLine("\tProperty name: " + property.Identifier.Text);

                    IPropertySymbol propertySemanticData = semanticModel.GetDeclaredSymbol(property) as IPropertySymbol;
                    members = members.Add(GenerateProperty(property, propertySemanticData, usedNames));
                }
                else
                {
                    members = members.Add(member);
                }
            }

            SyntaxToken classIdentifier = SF.IdentifierName(classNode.Identifier.Text + "Mock").GetFirstToken();
            var classDeclaration = SF.ClassDeclaration(classNode.AttributeLists, classNode.Modifiers, classIdentifier, classNode.TypeParameterList, classNode.BaseList, classNode.ConstraintClauses, members);

            return SF.NamespaceDeclaration(SF.IdentifierName("TestNamespace")).AddUsings(SF.UsingDirective(SF.IdentifierName("System"))).AddMembers(classDeclaration);
        }
开发者ID:jernejk,项目名称:Roslyn-simple-demos,代码行数:39,代码来源:Program.cs

示例5: AddDelimitedRecord

        protected async Task<Document> AddDelimitedRecord(CodeFixContext context, SyntaxNode root, Diagnostic diagnostic)
        {
            var diagnosticSpan = diagnostic.Location.SourceSpan;

            var node = root.FindNode(diagnosticSpan).Parent as TypeDeclarationSyntax;

            // Compute new uppercase name.
            //var typeofSyntax = (TypeOfExpressionSyntax)node.ArgumentList.Arguments[0].Expression;
            //var type = typeofSyntax.Type;
            //var originalEngine = node.Type;
            var attbAnte = node.AttributeLists;

            var attributes = new SyntaxList<AttributeListSyntax>();

            foreach (var attb in node.AttributeLists.ToArray())
            {
                attributes.Add(attb);
            }

            //attributes.AddRange(node.AttributeLists);
            attributes.Add(SyntaxFactory.AttributeList(SyntaxFactory.SeparatedList(
                new[]
                {
                    SyntaxFactory.Attribute(SyntaxFactory.ParseName("DelimitedRecord"),
                        SyntaxFactory.AttributeArgumentList())
                }
                )));
                
            
            //var newRoot = root.ReplaceNode(attbAnte, attributes);

                //SyntaxFactory.ObjectCreationExpression(SyntaxFactory.Token(SyntaxKind.NewKeyword),
                //    SyntaxFactory.ParseTypeName(originalEngine + "<" + type + ">"),
                //    SyntaxFactory.ArgumentList(SyntaxFactory.SeparatedList(node.ArgumentList.Arguments.Skip(1))), null));

            return context.Document.WithSyntaxRoot(newRoot);

        }
开发者ID:calebillman,项目名称:FileHelpers,代码行数:38,代码来源:ValidateRecordTypeCodeFixProvider.cs

示例6: BuildInitialize

            internal static SyntaxNode BuildInitialize(SyntaxGenerator generator, INamedTypeSymbol notImplementedException, SyntaxList<StatementSyntax> statements, string name)
            {
                var type = SyntaxFactory.ParseTypeName("AnalysisContext");
                var parameters = new[] { generator.ParameterDeclaration(name, type) };

                if (notImplementedException != null)
                {
                    statements = statements.Add(generator.ThrowStatement(generator.ObjectCreationExpression(notImplementedException)) as StatementSyntax);
                }

                var initializeDeclaration = generator.MethodDeclaration("Initialize", parameters: parameters, accessibility: Accessibility.Public, modifiers: DeclarationModifiers.Override, statements: statements);
                return initializeDeclaration;
            }
开发者ID:tmeschter,项目名称:roslyn-analyzers-1,代码行数:13,代码来源:CodeFixProvider.cs

示例7: SupportedRulesAsync

        private async Task<Document> SupportedRulesAsync(Document document, ClassDeclarationSyntax declaration, CancellationToken c)
        {
            List<string> ruleNames = new List<string>();
            var fieldMembers = declaration.Members.OfType<FieldDeclarationSyntax>();
            foreach (FieldDeclarationSyntax fieldSyntax in fieldMembers)
            {
                var fieldType = fieldSyntax.Declaration.Type;
                if (fieldType != null && fieldType.ToString() == "DiagnosticDescriptor")
                {
                    var ruleName = fieldSyntax.Declaration.Variables[0].Identifier.Text;
                    ruleNames.Add(ruleName);
                }
            }

            var propertyMembers = declaration.Members.OfType<PropertyDeclarationSyntax>();
            foreach (PropertyDeclarationSyntax propertySyntax in propertyMembers)
            {
                if (propertySyntax.Identifier.Text != "SupportedDiagnostics")
                {
                    continue;
                }

                AccessorDeclarationSyntax getAccessor = propertySyntax.AccessorList.Accessors.First();
                var returnStatement = getAccessor.Body.Statements.First() as ReturnStatementSyntax;
                InvocationExpressionSyntax invocationExpression = null;
                if (returnStatement == null)
                {
                    var declarationStatement = getAccessor.Body.Statements.First() as LocalDeclarationStatementSyntax;
                    if (declarationStatement == null)
                    {
                        return document;
                    }

                    invocationExpression = declarationStatement.Declaration.Variables[0].Initializer.Value as InvocationExpressionSyntax;
                }
                else
                {
                    invocationExpression = returnStatement.Expression as InvocationExpressionSyntax;
                }

                var oldArgumentList = invocationExpression.ArgumentList as ArgumentListSyntax;

                string argumentListString = "";
                foreach (string ruleName in ruleNames)
                {
                    if (ruleName == ruleNames.First())
                    {
                        argumentListString += ruleName;
                    }
                    else
                    {
                        argumentListString += ", " + ruleName;
                    }
                }

                var argumentListSyntax = SyntaxFactory.ParseArgumentList("(" + argumentListString + ")");
                SyntaxGenerator generator = SyntaxGenerator.GetGenerator(document);

                var args = argumentListSyntax.Arguments;
                var nodeArgs = new SyntaxList<SyntaxNode>();
                foreach (var arg in args)
                {
                    nodeArgs = nodeArgs.Add(arg as SyntaxNode);
                }

                if (invocationExpression.FirstAncestorOrSelf<ReturnStatementSyntax>() == null)
                {
                    return await ReplaceNode(invocationExpression.FirstAncestorOrSelf<LocalDeclarationStatementSyntax>(), generator.LocalDeclarationStatement(invocationExpression.FirstAncestorOrSelf<LocalDeclarationStatementSyntax>().Declaration.Variables[0].Identifier.Text, generator.InvocationExpression(generator.MemberAccessExpression(generator.IdentifierName("ImmutableArray"), "Create"), nodeArgs)).WithLeadingTrivia(SyntaxFactory.TriviaList(SyntaxFactory.ParseLeadingTrivia("// This array contains all the diagnostics that can be shown to the user").ElementAt(0), SyntaxFactory.EndOfLine("\r\n"))), document);
                }
                else
                {
                    return await ReplaceNode(invocationExpression.Parent, generator.ReturnStatement(generator.InvocationExpression(generator.MemberAccessExpression(generator.IdentifierName("ImmutableArray"), "Create"), nodeArgs)).WithLeadingTrivia(SyntaxFactory.TriviaList(SyntaxFactory.ParseLeadingTrivia("// This array contains all the diagnostics that can be shown to the user").ElementAt(0), SyntaxFactory.EndOfLine("\r\n"))), document);
                }
            }

           return document;
        }
开发者ID:tmeschter,项目名称:roslyn-analyzers-1,代码行数:77,代码来源:CodeFixProvider.cs

示例8: TooManyAccessorsAsync

        private async Task<Document> TooManyAccessorsAsync(Document document, PropertyDeclarationSyntax declaration, CancellationToken c)
        {
            SyntaxGenerator generator = SyntaxGenerator.GetGenerator(document);

            var allAccessors = declaration.AccessorList.Accessors.OfType<AccessorDeclarationSyntax>();
            bool foundGetAccessor = false;
            AccessorDeclarationSyntax accessorToKeep = null;
            var accessorList = declaration.AccessorList;

            foreach (AccessorDeclarationSyntax accessor in allAccessors)
            {
                var keyword = accessor.Keyword;
                if (keyword.IsKind(SyntaxKind.GetKeyword) && !foundGetAccessor)
                {
                    accessorToKeep = accessor;
                    foundGetAccessor = true;
                }
                else
                {
                    accessorList = accessorList.RemoveNode(accessor, 0);
                }
            }

            var block = SyntaxFactory.Block(new StatementSyntax[0]);
            if (accessorToKeep == null)
            {
                accessorToKeep = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, block);
            }
            
            SyntaxList<SyntaxNode> accessorsToAdd = new SyntaxList<SyntaxNode>();
            accessorsToAdd = accessorsToAdd.Add(accessorToKeep);
            var newPropertyDeclaration = declaration.WithAccessorList(null);
            newPropertyDeclaration = generator.AddAccessors(newPropertyDeclaration, accessorsToAdd) as PropertyDeclarationSyntax;

            return await ReplaceNode(declaration, newPropertyDeclaration, document);
        }
开发者ID:tmeschter,项目名称:roslyn-analyzers-1,代码行数:36,代码来源:CodeFixProvider.cs

示例9: MultipleStatementsAsync

        private async Task<Document> MultipleStatementsAsync(Document document, MethodDeclarationSyntax declaration, CancellationToken c)
        {
            SyntaxList<StatementSyntax> statements = new SyntaxList<StatementSyntax>();
            SyntaxList<StatementSyntax> initializeStatements = declaration.Body.Statements;

            var newBlock = declaration.Body;

            foreach (ExpressionStatementSyntax statement in initializeStatements)
            {
                var expression = statement.Expression as InvocationExpressionSyntax;
                var expressionStart = expression.Expression as MemberAccessExpressionSyntax;
                if (expressionStart == null || expressionStart.Name == null ||
                    expressionStart.Name.ToString() != "RegisterSyntaxNodeAction")
                {
                    continue;
                }

                if (expression.ArgumentList == null || expression.ArgumentList.Arguments.Count() != 2)
                {
                    continue;
                }

                var argumentMethod = expression.ArgumentList.Arguments[0].Expression as IdentifierNameSyntax;
                var argumentKind = expression.ArgumentList.Arguments[1].Expression as MemberAccessExpressionSyntax;
                var preArgumentKind = argumentKind.Expression as IdentifierNameSyntax;
                if (argumentMethod.Identifier == null || argumentKind.Name == null || preArgumentKind.Identifier == null || argumentKind.Name.Identifier.Text != "IfStatement" ||
                    preArgumentKind.Identifier.ValueText != "SyntaxKind")
                {
                    continue;
                }

                statements = statements.Add(statement);
            }

            SyntaxList<StatementSyntax> statementsToAdd = new SyntaxList<StatementSyntax>();
            statementsToAdd = statementsToAdd.Add(statements[0]);

            newBlock = newBlock.WithStatements(statementsToAdd);
            var newDeclaration = declaration.WithBody(newBlock);

            return await ReplaceNode(declaration, newDeclaration, document);
        }
开发者ID:tmeschter,项目名称:roslyn-analyzers-1,代码行数:42,代码来源:CodeFixProvider.cs

示例10: VisitClassDeclaration

        //public SemanticModel Model { get; private set; }
        public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
        {
            node = (ClassDeclarationSyntax)base.VisitClassDeclaration(node);
            MethodDeclarationSyntax prector = SyntaxFactory.MethodDeclaration(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), ".prector");
            MethodDeclarationSyntax precctor = SyntaxFactory.MethodDeclaration(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), ".precctor");
            precctor = precctor.AddModifiers(SyntaxFactory.Token(SyntaxKind.StaticKeyword));

            List<StatementSyntax> Initializers = new List<StatementSyntax>();
            List<StatementSyntax> StaticInitializers = new List<StatementSyntax>();
            foreach (MemberDeclarationSyntax member in node.Members)
            {
                if (member.CSharpKind() == SyntaxKind.FieldDeclaration)
                {
                    FieldDeclarationSyntax fds = (FieldDeclarationSyntax)member;

                    foreach (VariableDeclaratorSyntax vds in fds.Declaration.Variables)
                    {
                        if (vds.Initializer != null)
                        {
                            if (fds.Modifiers.ToString().Contains("static"))
                            {
                                StaticInitializers.Add(SyntaxFactory.ExpressionStatement(SyntaxFactory.BinaryExpression(SyntaxKind.SimpleAssignmentExpression, SyntaxFactory.IdentifierName(vds.Identifier), vds.Initializer.Value)));
                            }
                            else
                            {
                                Initializers.Add(SyntaxFactory.ExpressionStatement(SyntaxFactory.BinaryExpression(SyntaxKind.SimpleAssignmentExpression, SyntaxFactory.IdentifierName(vds.Identifier), vds.Initializer.Value)));
                            }
                        }
                    }
                }
            }

            if (Initializers.Count == 0 && StaticInitializers.Count == 0)
                return node;
            SyntaxList<MemberDeclarationSyntax> newMembers = new SyntaxList<MemberDeclarationSyntax>();

            if (Initializers.Count > 0)
            {
                int constructors = node.Members.Count((m) => (m is ConstructorDeclarationSyntax && !((ConstructorDeclarationSyntax)m).Modifiers.ToString().Contains("static")));

                prector = prector.AddBodyStatements(Initializers.ToArray());
                node = node.AddMembers(prector);

                if (constructors == 0)
                {
                    ConstructorDeclarationSyntax ctor = SyntaxFactory.ConstructorDeclaration(node.Identifier);
                    ctor = ctor.AddBodyStatements(SyntaxFactory.ExpressionStatement(SyntaxFactory.InvocationExpression(SyntaxFactory.IdentifierName(".prector"))));
                    ctor = ctor.AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword));

                    newMembers = newMembers.Add(ctor);
                }
               // else
                {

                    foreach (MemberDeclarationSyntax member in node.Members)
                    {
                        if (member.CSharpKind() == SyntaxKind.ConstructorDeclaration && !((ConstructorDeclarationSyntax)member).Modifiers.ToString().Contains("static"))
                        {
                            newMembers = newMembers.Add((MemberDeclarationSyntax)ConstructorPrefixerDeclaration((ConstructorDeclarationSyntax)member));
                        }
                        else
                        {
                            newMembers = newMembers.Add(member);
                        }
                    }
                }
            }
            if (StaticInitializers.Count > 0)
            {
                int constructors = node.Members.Count((m) => (m is ConstructorDeclarationSyntax && ((ConstructorDeclarationSyntax)m).Modifiers.ToString().Contains("static")));

                precctor = precctor.AddBodyStatements(StaticInitializers.ToArray());
                node = node.AddMembers(precctor);

                if (constructors == 0)
                {
                    ConstructorDeclarationSyntax ctor = SyntaxFactory.ConstructorDeclaration(node.Identifier);
                    ctor = ctor.AddModifiers(SyntaxFactory.Token(SyntaxKind.StaticKeyword));
                    ctor = ctor.AddBodyStatements(SyntaxFactory.ExpressionStatement(SyntaxFactory.InvocationExpression(SyntaxFactory.IdentifierName(".precctor"))));
                    ctor = ctor.AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword));

                    newMembers = newMembers.Add(ctor);
                }
                //else
                {

                    foreach (MemberDeclarationSyntax member in node.Members)
                    {
                        if (member.CSharpKind() == SyntaxKind.ConstructorDeclaration && ((ConstructorDeclarationSyntax)member).Modifiers.ToString().Contains("static"))
                        {
                            newMembers = newMembers.Add((MemberDeclarationSyntax)StaticConstructorPrefixerDeclaration((ConstructorDeclarationSyntax)member));
                        }
                        else
                        {
                            newMembers = newMembers.Add(member);
                        }
                    }
                }
            }
//.........这里部分代码省略.........
开发者ID:LaxLacks,项目名称:ls2csc,代码行数:101,代码来源:FieldInitializerRewriter.cs

示例11: VisitBlock

            public override SyntaxNode VisitBlock(BlockSyntax node)
            {
                BlockSyntax block = (BlockSyntax)base.VisitBlock(node);
                SyntaxList<StatementSyntax> curList = new SyntaxList<StatementSyntax>();
                Dictionary<string, SyntaxNode> replacements = new Dictionary<string, SyntaxNode>();

                int numbering = 1;
                foreach (var stmt in block.Statements)
                {
                    SyntaxList<StatementSyntax> preList = new SyntaxList<StatementSyntax>();
                    var stm = stmt.ReplaceNodes(nodes: stmt.DescendantNodes().Reverse(), computeReplacementNode: (original, origWithReplacedDesc) =>
                    {
                        Console.WriteLine(origWithReplacedDesc.GetType() + ": " + origWithReplacedDesc);

                        if (origWithReplacedDesc.IsKind(SyntaxKind.InvocationExpression)
                            || origWithReplacedDesc.IsKind(SyntaxKind.ObjectCreationExpression))
                        {
                            return SimplifyMethodAndConstructorInvocation(ref numbering, ref preList, original, origWithReplacedDesc);
                        }
                        return origWithReplacedDesc;
                    });
                    curList = curList.AddRange(preList);
                    curList = curList.Add(stm);
                }
                return block.WithStatements(curList);
            }
开发者ID:TubaKayaDev,项目名称:Call-Graph-Builder-DotNet,代码行数:26,代码来源:MethodSimpifier.cs

示例12: CreateDiagnostic

            internal static SyntaxNode CreateDiagnostic(SyntaxGenerator generator, string locationName, string ruleName)
            {
                var identifier = generator.IdentifierName("Diagnostic");
                var expression = generator.MemberAccessExpression(identifier, "Create");

                SyntaxList<SyntaxNode> arguments = new SyntaxList<SyntaxNode>();

                var ruleExpression = generator.IdentifierName(ruleName);
                var ruleArg = generator.Argument(ruleExpression);

                var locationExpression = generator.IdentifierName(locationName);
                var locationArg = generator.Argument(locationExpression);

                arguments = arguments.Add(ruleArg);
                arguments = arguments.Add(locationArg);

                string name = "diagnostic";
                var initializer = generator.InvocationExpression(expression, arguments);
                SyntaxNode localDeclaration = generator.LocalDeclarationStatement(name, initializer);

                return localDeclaration;
            }
开发者ID:tmeschter,项目名称:roslyn-analyzers-1,代码行数:22,代码来源:CodeFixProvider.cs

示例13: CreateAnalysisMethod

            internal static SyntaxNode CreateAnalysisMethod(SyntaxGenerator generator, string methodName, SemanticModel semanticModel)
            {
                var type = SyntaxFactory.ParseTypeName("SyntaxNodeAnalysisContext");
                var parameters = new[] { generator.ParameterDeclaration("context", type) };
                SyntaxList<SyntaxNode> statements = new SyntaxList<SyntaxNode>();
                INamedTypeSymbol notImplementedException = semanticModel.Compilation.GetTypeByMetadataName("System.NotImplementedException");
                statements = statements.Add(generator.ThrowStatement(generator.ObjectCreationExpression(notImplementedException)));

                SyntaxNode newMethodDeclaration = generator.MethodDeclaration(methodName, parameters: parameters, accessibility: Accessibility.Private, statements: statements);
                return newMethodDeclaration.WithLeadingTrivia(SyntaxFactory.ParseLeadingTrivia("// This method, which is the method that is registered within Initialize, performs the analysis of the Syntax Tree when an IfStatementSyntax Node is found. If the analysis finds an error, a diagnostic is reported").ElementAt(0), SyntaxFactory.CarriageReturnLineFeed, SyntaxFactory.ParseLeadingTrivia("// In this tutorial, this method will walk through the Syntax Tree seen in IfSyntaxTree.jpg and determine if the if-statement being analyzed has the correct spacing").ElementAt(0), SyntaxFactory.CarriageReturnLineFeed);
            }
开发者ID:tmeschter,项目名称:roslyn-analyzers-1,代码行数:11,代码来源:CodeFixProvider.cs

示例14: CreateRuleList

            protected internal static SyntaxList<SyntaxNode> CreateRuleList(Document document, List<string> ruleNames)
            {
              
                string argumentListString = "";
                foreach (string ruleName in ruleNames)
                {
                    if (ruleName == ruleNames.First())
                    {
                        argumentListString += ruleName;
                    }
                    else
                    {
                        argumentListString += ", " + ruleName;
                    }
                }

                ArgumentListSyntax argumentListSyntax = SyntaxFactory.ParseArgumentList("(" + argumentListString + ")");
                SyntaxGenerator generator = SyntaxGenerator.GetGenerator(document);

                SeparatedSyntaxList<ArgumentSyntax> args = argumentListSyntax.Arguments;
                var nodeArgs = new SyntaxList<SyntaxNode>();
                foreach (ArgumentSyntax arg in args)
                {
                    nodeArgs = nodeArgs.Add(arg as SyntaxNode);
                }

                return nodeArgs;
            }
开发者ID:maggiemsft,项目名称:roslyn-analyzers,代码行数:28,代码来源:CodeFixProvider.cs

示例15: ComputeRefactoringsAsync

        public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
        {
            var document = context.Document;
            if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
                return;
            var span = context.Span;
            if (!span.IsEmpty)
                return;
            var cancellationToken = context.CancellationToken;
            if (cancellationToken.IsCancellationRequested)
                return;
            var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
            if (model.IsFromGeneratedCode(cancellationToken))
                return;
            var root = await model.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);

            var token = root.FindToken(span.Start);
            if (!token.IsKind(SyntaxKind.SwitchKeyword))
                return;

            var switchStatement = token.Parent as SwitchStatementSyntax;
            if (switchStatement == null)
                return;

            var result = model.GetSymbolInfo(switchStatement.Expression);
            if (result.Symbol == null)
                return;
            var resultType = result.Symbol.GetReturnType();
            if (resultType.TypeKind != TypeKind.Enum)
                return;

            if (switchStatement.Sections.Count == 0)
            {
                SyntaxList<SwitchSectionSyntax> sections = new SyntaxList<SwitchSectionSyntax>();
                foreach (var field in resultType.GetMembers().OfType<IFieldSymbol>())
                {
                    if (!field.IsConst)
                        continue;
                    sections = sections.Add(GetSectionFromSymbol(model, field, span).WithStatements(SyntaxFactory.SingletonList<StatementSyntax>(SyntaxFactory.BreakStatement())));
                }
                sections = sections.Add(SyntaxFactory.SwitchSection()
                    .WithLabels(SyntaxFactory.SingletonList<SwitchLabelSyntax>(SyntaxFactory.DefaultSwitchLabel()))
                    .WithStatements(SyntaxFactory.SingletonList<StatementSyntax>(
                        SyntaxFactory.ThrowStatement(
                        SyntaxFactory.ObjectCreationExpression(
                            SyntaxFactory.IdentifierName("ArgumentOutOfRangeException")).WithArgumentList(SyntaxFactory.ArgumentList())))));
                var newRoot = root.ReplaceNode((SyntaxNode)switchStatement, switchStatement.WithSections(sections).WithAdditionalAnnotations(Formatter.Annotation));
                context.RegisterRefactoring(
                    CodeActionFactory.Create(span, DiagnosticSeverity.Info, GettextCatalog.GetString("Generate switch labels"), document.WithSyntaxRoot(newRoot))
                );
            }
            else
            {
                List<IFieldSymbol> fields = new List<IFieldSymbol>();
                foreach (var field in resultType.GetMembers())
                {
                    var fieldSymbol = field as IFieldSymbol;
                    if (fieldSymbol == null || !fieldSymbol.IsConst)
                        continue;
                    if (!IsHandled(model, switchStatement, fieldSymbol))
                        fields.Add(fieldSymbol);
                }
                if (fields.Count == 0)
                    return;
                var newSections = new SyntaxList<SwitchSectionSyntax>().AddRange(
                    fields.Select(f => GetSectionFromSymbol(model, f, span).WithStatements(SyntaxFactory.SingletonList<StatementSyntax>(SyntaxFactory.BreakStatement()))));

                //default section - if it exists, remove it, add in our new sections, and replace it
                var defaultSection = switchStatement.Sections.FirstOrDefault(s => s.Labels.Any(l => l is DefaultSwitchLabelSyntax));

                if (defaultSection == null)
                    newSections = switchStatement.Sections.AddRange(newSections);
                else
                    newSections = switchStatement.Sections.Remove(defaultSection).AddRange(newSections).Add(defaultSection);

                var newRoot = root.ReplaceNode((SyntaxNode)switchStatement, switchStatement.WithSections(newSections).WithAdditionalAnnotations(Formatter.Annotation));
                context.RegisterRefactoring(CodeActionFactory.Create(span, DiagnosticSeverity.Info, "Create missing switch labels", document.WithSyntaxRoot(newRoot)));
            }
        }
开发者ID:alecor191,项目名称:RefactoringEssentials,代码行数:79,代码来源:GenerateSwitchLabelsCodeRefactoringProvider.cs


注:本文中的Microsoft.CodeAnalysis.CSharp.Syntax.SyntaxList.Add方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。