示例#1
0
        public override void VisitMethodDeclaration(MethodDeclarationSyntax node)
        {
            var leadingTrivia = node.HasLeadingTrivia
                ? node.GetLeadingTrivia()
                : default(SyntaxTriviaList);

            // multiline comment on method
            AddMultiLineDocumentationComment(leadingTrivia);

            if (node.ShouldBeHidden(leadingTrivia))
            {
                return;
            }

            // allow derived types to determine if this method should be json serialized
            if (SerializeMethodDeclarationToJson(node))
            {
                return;
            }

            var memberName = node.Identifier.Text;

            foreach (var blockNode in node.ChildNodes().OfType <BlockSyntax>())
            {
                AddBlockChildNodes(blockNode, memberName);
            }

            foreach (var syntax in node.ChildNodes().Where(c => c.IsKind(SyntaxKind.ArrowExpressionClause)))
            {
                var syntaxNode = syntax.ChildNodes().First();
                Blocks.Add(new CSharpBlock(syntaxNode, ClassDepth, memberName));
            }
        }
        protected IEnumerable <CodeAction> GetActions(Document document, SyntaxNode root, MethodDeclarationSyntax node)
        {
            var nullableType = node.ChildNodes().OfType <NullableTypeSyntax>().FirstOrDefault();

            var objectType = node.ChildNodes().OfType <IdentifierNameSyntax>().FirstOrDefault();

            return(GetActions(document, root, node, nullableType, objectType));
        }
示例#3
0
        public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node)
        {
            ArrowExpressionClauseSyntax arrowExpressionClause = null;
            SyntaxNode nodeBeforeArrowExpression = null;

            foreach (SyntaxNode childNode in node.ChildNodes())
            {
                if (childNode.Kind() == SyntaxKind.ArrowExpressionClause)
                {
                    arrowExpressionClause = childNode as ArrowExpressionClauseSyntax;
                    break;
                }
                nodeBeforeArrowExpression = childNode;
            }

            if (arrowExpressionClause == null || nodeBeforeArrowExpression == null)
            {
                return(base.VisitMethodDeclaration(node));
            }

            if (!ShouldFormat(arrowExpressionClause, nodeBeforeArrowExpression))
            {
                return(base.VisitMethodDeclaration(node));
            }

            SyntaxNode newNode = FormatMethodNode(node, nodeBeforeArrowExpression, arrowExpressionClause);

            return(base.VisitMethodDeclaration(newNode as MethodDeclarationSyntax));
        }
示例#4
0
        public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node)
        {
            var typ = node.ChildNodes().OfType <PredefinedTypeSyntax>().FirstOrDefault();

            var    parametr  = node.ChildNodes().OfType <ParameterListSyntax>().FirstOrDefault();
            string parametry = "";

            foreach (ParameterSyntax p in parametr.ChildNodes())
            {
                parametry = parametry + p + " ";
            }


            if (parametry == "")
            {
                parametry = "Brak parametrów";
            }

            return(base.VisitMethodDeclaration(node).WithLeadingTrivia(SyntaxFactory.Comment("\n//Typ zwracany przez metodę: " + typ + "\n" + "//Parametry metody:  " + parametry + "\n")));
        }
示例#5
0
        public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node)
        {
            if (!node.ChildNodes().OfType <PredefinedTypeSyntax>().FirstOrDefault().ToString().Equals("void"))
            {
                var wynikMetody = node.ChildNodes().OfType <BlockSyntax>().FirstOrDefault()
                                  .ChildNodes().OfType <ReturnStatementSyntax>().FirstOrDefault();
                //Console.WriteLine(wynikMetody.ToString());
                var poReturnie = wynikMetody.ChildNodes().OfType <LiteralExpressionSyntax>().FirstOrDefault();
                poRet = poReturnie;
                //Console.WriteLine(poReturnie.ToString());

                if (poReturnie != null)
                {
                    lista.Add(node.Identifier.ToString(), poReturnie);
                    //  Console.WriteLine(lista[node.Identifier]);
                }
            }

            return(base.VisitMethodDeclaration(node));
        }
示例#6
0
        /// <summary>
        /// This method calculates the bounds of the method background adornment.
        /// </summary>
        /// <param name="methodDeclarationSyntaxNode">The syntax node that represents the method declaration that has too many lines of code.</param>
        /// <param name="snapshotSpan">The span of text that is associated with the background adornment.</param>
        /// <returns>Returns the calculated bounds of the method adornment.</returns>
        private Rect CalculateBounds(MethodDeclarationSyntax methodDeclarationSyntaxNode, SnapshotSpan snapshotSpan)
        {
            if (methodDeclarationSyntaxNode == null)
            {
                throw new ArgumentNullException(nameof(methodDeclarationSyntaxNode));
            }

            if (snapshotSpan == null)
            {
                throw new ArgumentNullException(nameof(snapshotSpan));
            }

            var nodes = new List <SyntaxNode>(methodDeclarationSyntaxNode.ChildNodes());

            nodes.Add(methodDeclarationSyntaxNode);

            var nodesFirstCharacterPositions    = nodes.Select(node => node.Span.Start);
            var coordinatesOfCharacterPositions = new List <double>();

            foreach (var position in nodesFirstCharacterPositions)
            {
                var point = CalculateScreenCoordinatesForCharacterPosition(position);
                coordinatesOfCharacterPositions.Add(point.x);
            }

            // [RS] In the case we cannot find the screen coordinates for a character position, we simply skip and return empty bounds.
            if (coordinatesOfCharacterPositions == null || coordinatesOfCharacterPositions.Count == 0)
            {
                return(Rect.Empty);
            }

            var viewOffset = VisualTreeHelper.GetOffset(_view.VisualElement);

            var left = coordinatesOfCharacterPositions
                       .Select(coordinate => coordinate)
                       .Min() - viewOffset.X;

            var geometry = _view.TextViewLines.GetMarkerGeometry(snapshotSpan, true, new Thickness(0));

            if (geometry == null)
            {
                return(Rect.Empty);
            }

            var top    = geometry.Bounds.Top;
            var width  = geometry.Bounds.Right - geometry.Bounds.Left; // - viewOffset.X;
            var height = geometry.Bounds.Bottom - geometry.Bounds.Top;

            return(new Rect(left, top, width, height));
        }
示例#7
0
        private static bool ReturnsEnumerable(MethodDeclarationSyntax method)
        {
            foreach (var unknown in method.ChildNodes())
            {
                switch (unknown)
                {
                case GenericNameSyntax g when g.GetName() == nameof(IEnumerable):
                case IdentifierNameSyntax i when i.GetName() == nameof(IEnumerable):
                    return(true);
                }
            }

            return(false);
        }
        private static string DetermineName(MethodDeclarationSyntax node)
        {
            var name = DetermineRawName(node);

            var typeParameters = node.ChildNodes().OfType <TypeParameterListSyntax>().FirstOrDefault();

            if (typeParameters == null)
            {
                return(name);
            }

            var parameterList = typeParameters.ToString();

            return(name + parameterList);
        }
示例#9
0
        private void ParseMethodDeclaration(MethodDeclarationSyntax methodDeclarationSyntax)
        {
            _output.HandleLeadingTrivia(methodDeclarationSyntax);

            string methodDeclaration = methodDeclarationSyntax.ReturnType.ToString() + " " + methodDeclarationSyntax.Identifier;

            _output.Add(methodDeclaration);

            ParseParameterListSyntax(methodDeclarationSyntax.ParameterList);

            BlockSyntax blockSyntax = methodDeclarationSyntax.ChildNodes().Skip(2).First() as BlockSyntax;

            HandleStatementSyntax(blockSyntax);

            _output.HandleTrailingTrivia(methodDeclarationSyntax);
        }
示例#10
0
        static String SplitMethod(MethodDeclarationSyntax mds)
        {
            //List<SyntaxNode> original = new List<SyntaxNode>();
            //List<SyntaxNode> newNodes = new List<SyntaxNode>();
            String program = "";
            String variableDeclarations = "";

            //DescendantNodes
            foreach (StatementSyntax blockstatement in mds.ChildNodes().OfType <StatementSyntax>())
            {
                List <Object> results = ReadBlock(blockstatement);
                program += results[0];
                variableDeclarations += results[1];
            }
            program = variableDeclarations + strings["start-switch"] + program;
            return(RemoveWhiteSpaces(program));
        }
        public void GetMethodParameters(MethodDeclarationSyntax methodDeclaration, SemanticModel semanticModel, ControllerActionModel controllerActionModel, Compilation compilation)
        {
            var list                = methodDeclaration.AttributeLists.SelectMany(a => a.Attributes).ToList();
            var parameters          = new List <ControllerActionParameter>();
            var parameterListSyntax = methodDeclaration.ChildNodes().OfType <ParameterListSyntax>().FirstOrDefault();

            foreach (var parameterSyntax in parameterListSyntax.Parameters)
            {
                var symbol = semanticModel.GetDeclaredSymbol(parameterSyntax);
                if (symbol == null)
                {
                    continue;
                }
                var type = symbol.Type as INamedTypeSymbol;
                if (type == null)
                {
                    continue;
                }

                var controllerParameter = new ControllerActionParameter
                {
                    ParameterName          = parameterSyntax.Identifier.ValueText,
                    Required               = !symbol.HasExplicitDefaultValue,
                    ParameterTypeName      = type.ToString(),
                    ParameterTypeNamespace = type.ContainingNamespace.ToString()
                };
                if (type.ContainingNamespace.IsGlobalNamespace)
                {
                    //var location = type.Locations.FirstOrDefault();
                    //var tree = location?.SourceTree;

                    //var root = tree.GetCompilationUnitRoot();
                    //var model = compilation.GetSemanticModel(tree);
                    //var ns = GetNamespace(root);

                    //controllerParameter.ParameterTypeNamespace = GetNamespace(root);
                }
                parameters.Add(controllerParameter);
                //var blockMethodParameter = BlockFactory.ParameterProvider.BlockMethodParameterFromMethodDeclaration(parameterSyntax, semanticModel, blockMethod);
                //if (blockMethodParameter != null)
                //{
                //    blockMethod.Parameters.Add(blockMethodParameter);
                //}
            }
            controllerActionModel.Parameters = parameters;
        }
示例#12
0
        public override void VisitMethodDeclaration(MethodDeclarationSyntax node)
        {
            var returnType  = node.ChildNodes().FirstOrDefault(x => !(x is AttributeListSyntax)).ToString();
            var isSubMethod = node.ChildNodes().FirstOrDefault(x => !(x is AttributeListSyntax)).ChildTokens().Any(x => x.Kind() == SyntaxKind.VoidKeyword);
            var isPartial   = node.ChildTokens().Any(x => x.Kind() == SyntaxKind.PartialKeyword);
            var defineName  = node.ChildTokens().FirstOrDefault(x => x.Kind() == SyntaxKind.IdentifierToken).ToString();

            // ジェネリック型を定義している場合
            if (node.ChildNodes().OfType <TypeParameterListSyntax>().Any())
            {
                var listNode     = node.ChildNodes().OfType <TypeParameterListSyntax>().FirstOrDefault();
                var genericTypes = listNode
                                   .ChildNodes()
                                   .OfType <TypeParameterSyntax>()
                                   .Select(x => x.ChildTokens().FirstOrDefault(y => y.Kind() == SyntaxKind.IdentifierToken).ToString());

                defineName = $"{defineName}<{string.Join(", ", genericTypes)}>";
            }

            var methodArguments = new List <MethodArgument>();

            if (node.ChildNodes().OfType <ParameterListSyntax>().FirstOrDefault().ChildNodes().Any())
            {
                var listNode = node.ChildNodes().OfType <ParameterListSyntax>().FirstOrDefault();
                methodArguments = GetMethodArguments(listNode);
            }

            var startLength     = node.Span.Start;
            var endLength       = node.Span.End;
            var parentNamespace = GetNamespace(DefineKinds.Method, startLength, endLength);

            // EventHandler、Method(Sub, Function)
            var isEventHandler = false;

            if (isSubMethod)
            {
                if (methodArguments.Count == 2)
                {
                    if (methodArguments[0].DefineType == "object" && methodArguments[1].DefineType.EndsWith("EventArgs"))
                    {
                        isEventHandler = true;
                    }
                }
            }

            var isWinAPI = node.AttributeLists.Any(x => x.ToString().Contains("DllImport"));
            var kinds    = DefineKinds.Method;

            if (isEventHandler)
            {
                kinds = DefineKinds.EventHandler;
            }

            // EventHandler っぽいけど、Windows API の場合は、こちらを優先する
            if (isWinAPI)
            {
                kinds = DefineKinds.WindowsAPI;
            }

            UserDefinitions.Add(new UserDefinition
            {
                DefineKinds     = kinds,
                IsPartial       = isPartial,
                Namespace       = parentNamespace,
                DefineName      = defineName,
                DefineFullName  = $"{parentNamespace}.{defineName}",
                MethodArguments = methodArguments,
                ReturnType      = RemoveNamespace(returnType),
                SourceFile      = SourceFile,
                StartLength     = startLength,
                EndLength       = endLength,
            });

            base.VisitMethodDeclaration(node);
        }
        private async Task <Solution> SwagifyEndpoint(Document doc, MethodDeclarationSyntax method,
                                                      CancellationToken cancellationToken)
        {
            SyntaxNode root = await doc.GetSyntaxRootAsync(cancellationToken);

            BlockSyntax methodBlock = method.ChildNodes().First(m => m is BlockSyntax) as BlockSyntax;

            /* Get SwaggerResponse attributes:
             * att.Attributes[0] is always the name of the attribute
             * (I think, it could be something like assembly:) TODO */
            List <AttributeListSyntax> swaggerResponses    = new List <AttributeListSyntax>();
            List <AttributeListSyntax> remainingAttributes = new List <AttributeListSyntax>();

            foreach (AttributeListSyntax att in method.AttributeLists)
            {
                if (att.GetName() == AttributeName)
                {
                    swaggerResponses.Add(att);
                }
                else
                {
                    remainingAttributes.Add(att);
                }
            }

            /* TODO: check BlockSyntaxes for returns */
            List <ReturnStatementSyntax> returnStatements = methodBlock.ChildNodes().OfType <ReturnStatementSyntax>().ToList();

            Dictionary <HttpStatusCode, AttributeMetadata> responses = GetAttributeSummaries(swaggerResponses);
            /* Clone dictionary for working, keep returnTypes for the original */
            Dictionary <HttpStatusCode, AttributeMetadata> responsesUpdated =
                responses.ToDictionary(a => a.Key, b => new AttributeMetadata(b.Value.StatusCode, b.Value.Description, b.Value.TypeName));

            for (int index = 0; index < returnStatements.Count; index++)
            {
                ReturnStatementSyntax returnStatement = returnStatements[index];
                HttpStatusCode        statusCode      = GetReturnCode(returnStatement);

                /* Get the type and update it. If the types are the same,
                 * nothing will change. */
                string type = GetReturnTypeName(returnStatement);
                if (responsesUpdated.ContainsKey(statusCode))
                {
                    responsesUpdated[statusCode].TypeName = type;
                }
                else
                {
                    responsesUpdated[statusCode] =
                        new AttributeMetadata(statusCode, DescriptionPlaceholder, type);
                }
            }
            /* Check if a change is required */

            if (!IsRefactorRequired(responses, responsesUpdated))
            {
                /* No change required */
                return(null);
            }

            /* Commit refactoring */
            SyntaxList <AttributeListSyntax> newAttributes = DoRefactor(responsesUpdated, method);

            Solution swagSolution = doc.WithSyntaxRoot(root.ReplaceNode(
                                                           method, method.WithAttributeLists(newAttributes))).Project.Solution;

            return(swagSolution);
        }
 private SyntaxNode GetMethodRoot(MethodDeclarationSyntax method)
 {
     return(method.ChildNodes().First().Parent);
 }