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);
        }
예제 #2
0
 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;
 }
        private static SwitchSectionSyntax CreateSection(SwitchLabelSyntax label, StatementSyntax statement)
        {
            var labels = new SyntaxList<SwitchLabelSyntax>();
            labels = labels.Add(label);

            return SyntaxFactory.SwitchSection(
                labels, CreateSectionStatements(statement)
                );
        }
예제 #4
0
        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);
        }
        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);

        }
            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;
            }
        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;
        }
        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);
        }
        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);
        }
예제 #10
0
        //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);
                        }
                    }
                }
            }

            return node.WithMembers(newMembers);
        }
            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);
            }
            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;
            }
            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);
            }
예제 #14
0
            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;
            }
        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)));
            }
        }
예제 #16
0
            // creates the trivia kind check
            protected internal static SyntaxNode TriviaKindCheckHelper(SyntaxGenerator generator, IfStatementSyntax ifStatement, SyntaxList<SyntaxNode> ifBlockStatements)
            {
                var ifBlock = ifStatement.Statement as BlockSyntax;
                string variableName = GetTrailingTriviaName(ifBlock);
                SyntaxNode identifierName = generator.IdentifierName(variableName);


                var arguments = new SyntaxList<SyntaxNode>();

                SyntaxNode whitespaceTrivia = generator.MemberAccessExpression(generator.IdentifierName("SyntaxKind"), "WhitespaceTrivia");
                arguments = arguments.Add(whitespaceTrivia);
                SyntaxNode trailingTriviaKind = generator.InvocationExpression(generator.MemberAccessExpression(identifierName, "IsKind"), arguments);

                SyntaxNode newIfStatement = generator.IfStatement(trailingTriviaKind, ifBlockStatements);

                return newIfStatement;
            }
예제 #17
0
        // gets ride of multiple statement inside Initialize, keeping one correct statement
        private async Task<Document> MultipleStatementsAsync(Document document, MethodDeclarationSyntax declaration, CancellationToken c)
        {
            SyntaxList<StatementSyntax> statements = new SyntaxList<StatementSyntax>();
            SyntaxList<StatementSyntax> initializeStatements = declaration.Body.Statements;

            foreach (ExpressionStatementSyntax statement in initializeStatements)
            {
                bool correctRegister = CodeFixHelper.IsCorrectRegister(statement);

                if (correctRegister)
                {
                    statements = statements.Add(statement);
                    break;
                }
            }

            BlockSyntax newBlock = declaration.Body;
            newBlock = newBlock.WithStatements(statements);
            MethodDeclarationSyntax newDeclaration = declaration.WithBody(newBlock);

            return await ReplaceNode(declaration, newDeclaration, document);
        }
예제 #18
0
        static CompilationUnitSyntax DumpEvents(CompilationUnitSyntax root)
        {
            Dictionary<SyntaxNode, SyntaxNode> changes = new Dictionary<SyntaxNode, SyntaxNode>();

            var classes = root.DescendantNodes().OfType<ClassDeclarationSyntax>();
            foreach (var @class in classes)
            {
                var events = @class.Members.OfType<EventDeclarationSyntax>();
                foreach (var @event in events)
                {
                    AccessorDeclarationSyntax add, remove;
                    BlockSyntax newBody = SyntaxFactory.Block(SyntaxFactory.ParseStatement("throw new NotImplementedException();"));
                    AccessorDeclarationSyntax adder = SyntaxFactory.AccessorDeclaration(SyntaxKind.AddAccessorDeclaration,newBody);
                    AccessorDeclarationSyntax remover = SyntaxFactory.AccessorDeclaration(SyntaxKind.RemoveAccessorDeclaration, newBody);
                    SyntaxList<AccessorDeclarationSyntax> syntaxes = new SyntaxList<AccessorDeclarationSyntax>();
                    syntaxes = syntaxes.Add(adder);
                    syntaxes = syntaxes.Add(remover);
                    AccessorListSyntax accessors = SyntaxFactory.AccessorList(syntaxes);
                    
                    EventDeclarationSyntax modifiedEvent = @event.WithAccessorList(accessors);
                    changes.Add(@event, modifiedEvent);
                }

            }

            root = root.ReplaceNodes(changes.Keys, (n1, n2) => changes[n1]);
            return root;
        }
            //creates the diagnostic location statement
            internal static SyntaxNode CreateLocation(SyntaxGenerator generator, string ifStatementIdentifier, string spanIdentifier)
            {
                string name = "diagnosticLocation";
                SyntaxNode memberIdentifier = generator.IdentifierName("Location");
                SyntaxNode memberName = generator.IdentifierName("Create");
                SyntaxNode expression = generator.MemberAccessExpression(memberIdentifier, memberName);

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

                var treeIdentifier = generator.IdentifierName(ifStatementIdentifier);
                var treeArgExpression = generator.MemberAccessExpression(treeIdentifier, "SyntaxTree");
                var treeArg = generator.Argument(treeArgExpression);

                var spanArgIdentifier = generator.IdentifierName(spanIdentifier);
                var spanArg = generator.Argument(spanArgIdentifier);

                arguments = arguments.Add(treeArg);
                arguments = arguments.Add(spanArg);

                SyntaxNode initializer = generator.InvocationExpression(expression, arguments);
                SyntaxNode localDeclaration = generator.LocalDeclarationStatement(name, initializer);

                return localDeclaration;
            }
        private async Task<Document> AddSuppDiagAsync(Document document, ClassDeclarationSyntax declaration, CancellationToken c)
        {
            SyntaxList<MemberDeclarationSyntax> members = declaration.Members;
            MethodDeclarationSyntax insertPoint = null;

            foreach (MemberDeclarationSyntax member in members)
            {
                insertPoint = member as MethodDeclarationSyntax;
                if (insertPoint == null || insertPoint.Identifier.Text != "Initialize")
                {
                    continue;
                }
                else
                {
                    break;
                }
            }

            SyntaxNode insertPointNode = insertPoint as SyntaxNode;

            SyntaxGenerator generator = SyntaxGenerator.GetGenerator(document);
            var semanticModel = await document.GetSemanticModelAsync();

            INamedTypeSymbol notImplementedException = semanticModel.Compilation.GetTypeByMetadataName("System.NotImplementedException");
            PropertyDeclarationSyntax propertyDeclaration = CodeFixNodeCreator.CreateSupportedDiagnostics(generator, notImplementedException);

            var newNodes = new SyntaxList<SyntaxNode>();
            newNodes = newNodes.Add(propertyDeclaration);

            var root = await document.GetSyntaxRootAsync();
            if (insertPoint != null)
            {
                var newRoot = root.InsertNodesBefore(insertPointNode, newNodes);
                var newDocument = document.WithSyntaxRoot(newRoot);
                return newDocument;
            }
            else
            {
                var newRoot = root.ReplaceNode(declaration, declaration.AddMembers(propertyDeclaration));
                var newDocument = document.WithSyntaxRoot(newRoot);
                return newDocument;
            }
        }
            //creates the diagnostic span statement
            internal static SyntaxNode CreateSpan(SyntaxGenerator generator, string startIdentifier, string endIdentifier)
            {
                string name = "diagnosticSpan";
                SyntaxNode memberIdentifier = generator.IdentifierName("TextSpan");
                SyntaxNode memberName = generator.IdentifierName("FromBounds");
                SyntaxNode expression = generator.MemberAccessExpression(memberIdentifier, memberName);

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

                var startSpanIdentifier = generator.IdentifierName(startIdentifier);
                var endSpanIdentifier = generator.IdentifierName(endIdentifier);

                arguments = arguments.Add(startSpanIdentifier);
                arguments = arguments.Add(endSpanIdentifier);

                SyntaxNode initializer = generator.InvocationExpression(expression, arguments);
                SyntaxNode localDeclaration = generator.LocalDeclarationStatement(name, initializer);

                return localDeclaration;
            }
        Document PerformAction(Document document, SemanticModel model, SyntaxNode root, PropertyDeclarationSyntax propertyDeclaration, bool needsSetter)
        {
            AccessorDeclarationSyntax accessor = null;
            PropertyDeclarationSyntax newProp = null;
            if (needsSetter)
            {
                accessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration);

                var getter = propertyDeclaration.AccessorList.Accessors.FirstOrDefault(m => m.IsKind(SyntaxKind.GetAccessorDeclaration));
                if (getter == null)
                {
                    //get;
                    accessor = accessor.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken));
                }
                else
                {
                    var getField = ReplacePropertyWithBackingFieldWithAutoPropertyCodeRefactoringProvider.ScanGetter(model, getter);
                    if (getField == null && getter.Body == null)
                    {
                        //get;
                        accessor = accessor.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)).WithTrailingTrivia(getter.GetTrailingTrivia());
                    }
                    else if (getField == null || getField.IsReadOnly)
                    {
                        //readonly or no field can be found
                        accessor = accessor.WithBody(GetNotImplementedBlock());
                    }
                    else
                    {
                        //now we add a 'field = value'.
                        accessor = accessor.WithBody(SyntaxFactory.Block(
                            SyntaxFactory.ExpressionStatement(
                                SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, SyntaxFactory.IdentifierName(getField.Name), SyntaxFactory.IdentifierName("value")))));
                    }
                }
                newProp = propertyDeclaration.WithAccessorList(propertyDeclaration.AccessorList.AddAccessors(accessor));
            }
            else
            {
                accessor = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration);

                var setter = propertyDeclaration.AccessorList.Accessors.FirstOrDefault(m => m.IsKind(SyntaxKind.SetAccessorDeclaration));
                var accessorDeclList = new SyntaxList<AccessorDeclarationSyntax>();
                if (setter == null)
                {
                    //set;
                    accessor = accessor.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken));
                }
                else
                {
                    var setField = ReplacePropertyWithBackingFieldWithAutoPropertyCodeRefactoringProvider.ScanSetter(model, setter);
                    if (setField == null && setter.Body == null)
                    {
                        //set;
                        accessor = accessor.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)).WithTrailingTrivia(setter.GetTrailingTrivia());
                    }
                    else if (setField == null)
                    {
                        //no field can be found
                        accessor = accessor.WithBody(GetNotImplementedBlock());
                    }
                    else
                    {
                        //now we add a 'return field;'.
                        accessor = accessor.WithBody(SyntaxFactory.Block(
                            SyntaxFactory.ReturnStatement(SyntaxFactory.IdentifierName(setField.Name))));
                    }
                    accessorDeclList = accessorDeclList.Add(propertyDeclaration.AccessorList.Accessors.First(m => m.IsKind(SyntaxKind.SetAccessorDeclaration)));
                }
                accessorDeclList = accessorDeclList.Insert(0, accessor);
                var accessorList = SyntaxFactory.AccessorList(accessorDeclList);
                newProp = propertyDeclaration.WithAccessorList(accessorList);
            }
            var newRoot = root.ReplaceNode((SyntaxNode)propertyDeclaration, newProp).WithAdditionalAnnotations(Formatter.Annotation);
            return document.WithSyntaxRoot(newRoot);
        }
            internal static PropertyDeclarationSyntax CreateSupportedDiagnostics(SyntaxGenerator generator, INamedTypeSymbol notImplementedException)
            {
                var type = SyntaxFactory.ParseTypeName("ImmutableArray<DiagnosticDescriptor>");
                var modifiers = DeclarationModifiers.Override;

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

                SyntaxNode throwStatement = generator.ThrowStatement(generator.ObjectCreationExpression(notImplementedException));
                getAccessorStatements = getAccessorStatements.Add(throwStatement);

                var propertyDeclaration = generator.PropertyDeclaration("SupportedDiagnostics", type, accessibility: Accessibility.Public, modifiers: modifiers, getAccessorStatements: getAccessorStatements) as PropertyDeclarationSyntax;
                propertyDeclaration = propertyDeclaration.RemoveNode(propertyDeclaration.AccessorList.Accessors[1], 0);

                return propertyDeclaration;
            }
        private static SyntaxList<StatementSyntax> CreateSectionStatements(StatementSyntax source)
        {
            var result = new SyntaxList<StatementSyntax>();

            if (source is BlockSyntax)
            {
                var block = source as BlockSyntax;
                result = result.AddRange(block.Statements);
            }
            else
            {
                result = result.Add(source);
            }

            var lastStatement = result.LastOrDefault();
            if (!(lastStatement is ReturnStatementSyntax || lastStatement is ThrowStatementSyntax))
            {
                result = result.Add(SyntaxFactory.BreakStatement());
            }

            return result;
        }
        private async Task<Document> AddRuleAsync(Document document, ClassDeclarationSyntax declaration, CancellationToken c)
        {
            SyntaxGenerator generator = SyntaxGenerator.GetGenerator(document);

            SyntaxList<MemberDeclarationSyntax> members = declaration.Members;
            PropertyDeclarationSyntax insertPoint = null;

            foreach (MemberDeclarationSyntax member in members)
            {
                insertPoint = member as PropertyDeclarationSyntax;
                if (insertPoint == null || insertPoint.Identifier.Text != "SupportedDiagnostics")
                {
                    insertPoint = null;
                    continue;
                }
                else
                {
                    break;
                }
            }

            SyntaxNode insertPointNode = insertPoint as SyntaxNode;

            FieldDeclarationSyntax fieldDeclaration = CodeFixNodeCreator.CreateEmptyRule(generator);

            var newNode = new SyntaxList<SyntaxNode>();
            newNode = newNode.Add(fieldDeclaration.WithLeadingTrivia(SyntaxFactory.TriviaList(SyntaxFactory.Whitespace("        "), SyntaxFactory.ParseLeadingTrivia("// If the analyzer finds an issue, it will report the DiagnosticDescriptor rule").ElementAt(0), SyntaxFactory.EndOfLine("\r\n"), SyntaxFactory.Whitespace("        "))));

            var root = await document.GetSyntaxRootAsync();
            if (insertPointNode != null)
            {
                var newRoot = root.InsertNodesBefore(insertPointNode, newNode);
                var newDocument = document.WithSyntaxRoot(newRoot);
                return newDocument;
            }
            else
            {
                var newRoot = root.ReplaceNode(declaration, declaration.AddMembers(fieldDeclaration.WithLeadingTrivia(SyntaxFactory.TriviaList(SyntaxFactory.ParseLeadingTrivia("// If the analyzer finds an issue, it will report the DiagnosticDescriptor rule").ElementAt(0), SyntaxFactory.EndOfLine("\r\n")))));
                var newDocument = document.WithSyntaxRoot(newRoot);
                return newDocument;
            }
        }
        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 property = root.FindNode(span) as PropertyDeclarationSyntax;
            if (property == null || !property.Identifier.Span.Contains(span))
                return;

            if (property.AccessorList.Accessors.Any(b => !IsEmptyOrNotImplemented(b.Body))) //ignore properties with >=1 accessor body
                return;
            context.RegisterRefactoring(
                CodeActionFactory.Create(
                    property.Identifier.Span,
                    DiagnosticSeverity.Info,
                    GettextCatalog.GetString("To property with backing field"),
                    t2 =>
                    {
                        string name = GetNameProposal(property.Identifier.ValueText, model, root);

                        //create our backing store
                        var backingStore = SyntaxFactory.FieldDeclaration(
                            SyntaxFactory.VariableDeclaration(
                                property.Type,
                                SyntaxFactory.SingletonSeparatedList<VariableDeclaratorSyntax>(SyntaxFactory.VariableDeclarator(name)))
                        ).WithModifiers(!property.Modifiers.Any(m => m.IsKind(SyntaxKind.StaticKeyword)) ?
                                        SyntaxFactory.TokenList() :
                                        SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.StaticKeyword)))
                        .WithAdditionalAnnotations(Formatter.Annotation);

                        //create our new property
                        var fieldExpression = name == "value" ?
                            (ExpressionSyntax)SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ThisExpression(), SyntaxFactory.IdentifierName("value")) :
                            SyntaxFactory.IdentifierName(name);

                        var newPropAnno = new SyntaxAnnotation();
                        var syntaxList = new SyntaxList<AccessorDeclarationSyntax>();
                        var hasSetter = property.AccessorList.Accessors.Any(acc => acc.IsKind(SyntaxKind.SetAccessorDeclaration));
                        var hasGetter = property.AccessorList.Accessors.Any(acc => acc.IsKind (SyntaxKind.GetAccessorDeclaration));

                        if (hasGetter)
                        {
                            var getBody = SyntaxFactory.Block(SyntaxFactory.ReturnStatement(fieldExpression));
                            var getter = SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, getBody);
							getter = getter.WithModifiers (property.AccessorList.Accessors.First (acc => acc.IsKind (SyntaxKind.GetAccessorDeclaration)).Modifiers);
                            syntaxList = syntaxList.Add(getter);
                            if (!hasSetter)
                                backingStore = backingStore.WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword)));
                        }

                        if (hasSetter)
                        {
                            var setBody = SyntaxFactory.Block(SyntaxFactory.ExpressionStatement(
                                SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, fieldExpression,
                                                                   SyntaxFactory.IdentifierName("value"))));
                            var setter = SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration, setBody);
							setter = setter.WithModifiers (property.AccessorList.Accessors.First (acc => acc.IsKind (SyntaxKind.SetAccessorDeclaration)).Modifiers);
                            syntaxList = syntaxList.Add(setter);
                        }
                        var newProperty = property.WithAccessorList(SyntaxFactory.AccessorList(syntaxList))
                            .WithAdditionalAnnotations(newPropAnno, Formatter.Annotation);

                        var newRoot = root.ReplaceNode((SyntaxNode)property, newProperty);
                        return Task.FromResult(document.WithSyntaxRoot(newRoot.InsertNodesBefore(newRoot.GetAnnotatedNodes(newPropAnno).First(), new List<SyntaxNode>() {
                            backingStore
                        })));
                    })
            );
        }
            private static SyntaxNode SimplifyMethodAndConstructorInvocation(ref int numbering, ref SyntaxList<StatementSyntax> preList, SyntaxNode original, SyntaxNode origWithReplacedDesc)
            {
                SeparatedSyntaxList<ArgumentSyntax> slst = new SeparatedSyntaxList<ArgumentSyntax>();
                SeparatedSyntaxList<ArgumentSyntax> myArgs;
                InvocationExpressionSyntax ies = null;
                ObjectCreationExpressionSyntax oces = null;
                // es necesario manejarlos por separado, porque pese a que ambos tienen como propiedad Arguments
                // de tipo SeparatedSyntaxList<ArgumentSyntax>, no estan en la misma linea de jerarquia
                // de clases... entonces:
                if (origWithReplacedDesc.IsKind(SyntaxKind.InvocationExpression))
                {
                    ies = (InvocationExpressionSyntax)origWithReplacedDesc;
                    myArgs = ies.ArgumentList.Arguments;
                }
                else
                {
                    oces = (ObjectCreationExpressionSyntax)origWithReplacedDesc;
                    myArgs = oces.ArgumentList.Arguments;
                }
                foreach (var arg in myArgs)
                {
                    if (!(arg.Expression is LiteralExpressionSyntax || arg.Expression is IdentifierNameSyntax))
                    {
                        numbering++;
                        preList = preList.Add(SyntaxFactory.ParseStatement("var __a" + numbering + " = " + arg + ";"));
                        slst = slst.Add((SyntaxFactory.Argument(SyntaxFactory.ParseExpression("__a" + numbering))));
                    }
                }

                if (slst.Count() > 0)
                {
                    var argumentList = SyntaxFactory.ArgumentList(slst);
                    if (origWithReplacedDesc.IsKind(SyntaxKind.InvocationExpression))
                    {
                        return ies.WithArgumentList(argumentList);
                    }
                    else
                    {
                        return oces.WithArgumentList(argumentList);
                    }
                }
                else return original;
            }
        private SyntaxNode AddLambdaThis(SyntaxNode node)
        {
            //SyntaxTreeHelper.PrintTree(node);
            if (!node.GetAnnotations("haslambdas").Any())
            {
                return node;
            }

            /*if (!node.DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Any())
            {
                return node;    
            }*/

            var stmt = CreateLambdaThis();
            var stmtlist = new SyntaxList<StatementSyntax>();
            stmtlist = stmtlist.Add(stmt);
            stmtlist = stmtlist.AddRange(node.ChildNodes().OfType<StatementSyntax>());
            node = SyntaxFactory.Block(stmtlist);


            return node;
        }
예제 #29
0
 private SyntaxList<StatementSyntax> AddAdditionnalDeclaration(MethodDeclarationSyntax m, SyntaxList<StatementSyntax> bodyStatements)
 {
     SyntaxList<StatementSyntax> result = bodyStatements;
     //add result var in order to trace it
     if (IsFunction(m))
     {
         var localDeclarationstm = SyntaxFactory.LocalDeclarationStatement(
             SyntaxFactory.VariableDeclaration(m.ReturnType)
             .WithVariables(new SeparatedSyntaxList<VariableDeclaratorSyntax>().Add(SyntaxFactory.VariableDeclarator(RESULTMARKER)))
             );
         result = bodyStatements.Add(localDeclarationstm);
     }
     //Add at start of void/function 'WeaverReport.Logger.BeginReport(fullname of void/function)'
     var stm = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(MethodFullName(m)));
     result = result.Add(ReportStatement("BeginReport",SyntaxFactory.Argument(stm)));
     var parameters = m.ParameterList.Parameters;
     var arg = ParametersToArg(parameters, x => !x.Modifiers.Any<SyntaxToken>(y => SyntaxKind.OutKeyword == y.Kind()));
     if (arg != null)
         result = result.Add(ReportStatement("PushArgs", SyntaxFactory.Argument(arg)));
     return result;
 }
예제 #30
0
        private void DoTestAddInsertRemoveReplaceOnEmptyList(SyntaxList<SyntaxNode> list)
        {
            Assert.Equal(0, list.Count);

            SyntaxNode nodeD = SyntaxFactory.ParseExpression("D ");
            SyntaxNode nodeE = SyntaxFactory.ParseExpression("E ");

            var newList = list.Add(nodeD);
            Assert.Equal(1, newList.Count);
            Assert.Equal("D ", newList.ToFullString());

            newList = list.AddRange(new[] { nodeD, nodeE });
            Assert.Equal(2, newList.Count);
            Assert.Equal("D E ", newList.ToFullString());

            newList = list.Insert(0, nodeD);
            Assert.Equal(1, newList.Count);
            Assert.Equal("D ", newList.ToFullString());

            newList = list.InsertRange(0, new[] { nodeD, nodeE });
            Assert.Equal(2, newList.Count);
            Assert.Equal("D E ", newList.ToFullString());

            newList = list.Remove(nodeD);
            Assert.Equal(0, newList.Count);

            Assert.Equal(-1, list.IndexOf(nodeD));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.RemoveAt(0));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(1, nodeD));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.Insert(-1, nodeD));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(1, new[] { nodeD }));
            Assert.Throws<ArgumentOutOfRangeException>(() => list.InsertRange(-1, new[] { nodeD }));
            Assert.Throws<ArgumentException>(() => list.Replace(nodeD, nodeE));
            Assert.Throws<ArgumentException>(() => list.ReplaceRange(nodeD, new[] { nodeE }));
            Assert.Throws<ArgumentNullException>(() => list.Add(null));
            Assert.Throws<ArgumentNullException>(() => list.AddRange((IEnumerable<SyntaxNode>)null));
            Assert.Throws<ArgumentNullException>(() => list.Insert(0, null));
            Assert.Throws<ArgumentNullException>(() => list.InsertRange(0, (IEnumerable<SyntaxNode>)null));
        }