Example #1
0
        private static Location GetDiagnosticLocation(SyntaxNode node)
        {
            if (node.HasLeadingTrivia)
            {
                return(node.GetLeadingTrivia()[0].GetLocation());
            }

            var firstToken = node.ChildTokens().FirstOrDefault();

            if (firstToken != default(SyntaxToken))
            {
                return(node.ChildTokens().First().GetLocation());
            }

            return(Location.None);
        }
        private static bool FindMatchingBrace(int position, int direction, SyntaxNode parent, SyntaxKind syntaxKind, out TextSpan right)
        {
            var tokens         = parent.ChildTokens().Where(t => t.Kind == syntaxKind);
            var relevantTokens = direction < 0
                                     ? from t in tokens
                                 where t.Span.End <= position
                                 select t
                                     : from t in tokens
                                 where position < t.Span.Start
                                 select t;

            right = new TextSpan();
            var found = false;

            foreach (var token in relevantTokens)
            {
                if (!found)
                {
                    right = token.Span;
                    found = true;
                }
                else
                {
                    return(false);
                }
            }

            return(found);
        }
Example #3
0
        // TODO: Exception e is allowed
        private bool IsNumberSeriesViolation(SyntaxNode declaration)
        {
            const string numberSeriesRegex = "^[a-zA-Z][0-9]{1,3}$";
            var          identifier        = declaration.ChildTokens().First(t => t.RawKind == IdentifierToken);

            return(Regex.IsMatch(identifier.Value.ToString(), numberSeriesRegex));
        }
        private XmlNodeSyntax GetTextNodeFromCommentTextNode(SyntaxNode textNode)
        {
            var tokens = new List <SyntaxToken>();

            foreach (var token in textNode.ChildTokens())
            {
                switch (token.Kind())
                {
                case SyntaxKind.XmlTextLiteralNewLineToken:
                    tokens.Add(Token.CreateXmlTextNewLine());
                    break;

                case SyntaxKind.XmlTextLiteralToken:
                    var text      = token.ValueText.ToString();
                    var delimiter = noSpace;
                    if (tokens.Count() != 0 && tokens.Last().IsKind(SyntaxKind.XmlTextLiteralNewLineToken))
                    {
                        delimiter = _documentationCommentDelimiter;
                    }
                    tokens.Add(Token.CreateXmlTextLiteral(text, delimiter));
                    break;

                default:
                    break;
                }
            }
            return(Node.CreateXmlText(_documentationCommentDelimiter, tokens.ToArray()));
        }
Example #5
0
        private AstWriter Write(SyntaxNode node)
        {
            this.WriteStartElement()
            .Write(" ");
            switch (this.settings.Format)
            {
            case AstFormat.Light:
                this.Write(node.Kind().ToString());
                break;

            case AstFormat.Json:
                this.WriteProperty("Kind", node.Kind().ToString());
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            this.indentation.Push();

            if (this.settings.Trivia.HasFlag(AstTrivia.Node))
            {
                _ = this.WriteTrivia("LeadingTrivia", node.GetLeadingTrivia())
                    .WriteTrivia("TrailingTrivia", node.GetTrailingTrivia());
            }

            this.WriteChildTokens(node.ChildTokens().ToList())
            .WriteChildNodes(node.ChildNodes().ToList())
            .Write(" ")
            .WriteEndElement();
            this.indentation.Pop();
            return(this);
        }
        public static string NameFrom(this SyntaxNode node)
        {
            var qualifiedNameNode = node.ChildNodes()
                                    .OfType <QualifiedNameSyntax>()
                                    .SingleOrDefault();
            var identifierNameNodes = node.ChildNodes()
                                      .OfType <IdentifierNameSyntax>()
                                      .ToList();
            var name = "";

            if (qualifiedNameNode != null)
            {
                name = name + qualifiedNameNode.ToString();
            }
            foreach (var identifierNameNode in identifierNameNodes)
            {
                var identifierName = identifierNameNode.ToString();
                if (!(string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(identifierName)))
                {
                    name += ".";
                }
                name = name += identifierName;
            }
            if (!string.IsNullOrWhiteSpace(name))
            {
                return(name);
            }
            var nameToken = node.ChildTokens()
                            .Where(x => x.Kind() == SyntaxKind.IdentifierToken)
                            .SingleOrDefault();

            return(nameToken.ValueText);
        }
        private static void AnalyzeBlock(CodeBlockEndAnalysisContext context)
        {
            SyntaxNode node = context.CodeBlock;

            //If the node isn't a Method Declaration - exit
            if (node.Kind() != SyntaxKind.MethodDeclaration)
            {
                return;
            }

            var block = node.ChildNodes().OfType <BlockSyntax>().FirstOrDefault();

            if (block == null)
            {
                return;
            }

            //If there are less than 10 statements - exit
            if (block.Statements.Count <= 10)
            {
                return;
            }

            //Get the identifier name
            var methodName = node.ChildTokens().FirstOrDefault(k => k.Kind() == SyntaxKind.IdentifierToken).Text;

            var diagnostic = Diagnostic.Create(Rule, block.GetLocation(), methodName);

            context.ReportDiagnostic(diagnostic);
        }
    private static bool HasConstOrEquivalent(SyntaxNode node)
    {
        bool hasStatic   = false;
        bool hasReadOnly = false;

        foreach (var tok in node.ChildTokens())
        {
            switch (tok.Kind())
            {
            case SyntaxKind.ReadOnlyKeyword:
                hasReadOnly = true;
                if (hasStatic)
                {
                    return(true);
                }
                break;

            case SyntaxKind.StaticKeyword:
                hasStatic = true;
                if (hasReadOnly)
                {
                    return(true);
                }
                break;

            case SyntaxKind.ConstKeyword:
                return(true);
            }
        }
        return(false);
    }
        private static string CreateName(CodeRefactoringContext context, SyntaxNode root, SyntaxNode blockSyntax, string typeName)
        {
            string name = typeName + "Const";

            name = NameGenerator.GenerateUniqueName(name, root.ChildTokens().Where(t => t.IsKind(SyntaxKind.IdentifierToken)).Select(t => t.ToString()).ToSet(), StringComparer.Ordinal);
            var newConstName = NameProposalService.GetNameProposal(name, SyntaxKind.MethodDeclaration, Accessibility.Private, true, context.Document, blockSyntax.SpanStart);

            return(newConstName);
        }
 public static bool IsStatic(this SyntaxNode @this)
 {
     if (@this == null)
     {
         throw new ArgumentNullException(nameof(@this));
     }
     return(@this.ChildTokens()
            .Any(t => t.IsKind(SyntaxKind.StaticKeyword)));
 }
Example #11
0
        private static int SwapMembers(this IWpfTextView textView, SyntaxNode member1, SyntaxNode member2, MovePosition position, MoveDirection direction, IOleCommandTarget commandTarget, IEditorOperations editorOperations)
        {
            if (member1 == null || member2 == null)
            {
                return(-1);
            }
            int    caretIndent  = textView.Caret.Position.BufferPosition.Position - member1.FullSpan.Start;
            int    movePosition = 0;
            string moveText     = member1.GetText().ToString();

            //Find the position to Move the Current method (i.e. member1)
            if (position == MovePosition.Top)
            {
                movePosition = member2.FullSpan.Start;
            }
            else if (position == MovePosition.Bottom)
            {
                movePosition = member2.FullSpan.End;
            }
            else if (position == MovePosition.MiddlefromBottom)
            {
                movePosition = member2.ChildTokens().FirstOrDefault(t => t.IsKind(SyntaxKind.CloseBraceToken)).SpanStart - 1;
            }
            else if (position == MovePosition.MiddlefromTop)
            {
                movePosition = member2.ChildTokens().FirstOrDefault(t => t.IsKind(SyntaxKind.OpenBraceToken)).SpanStart + 1;
            }

            var editor = textView.TextSnapshot.TextBuffer.CreateEdit();

            editor.Delete(member1.FullSpan.Start, member1.FullSpan.Length);
            editor.Insert(movePosition, moveText);
            editor.Apply();

            int newCaretPosition = direction == MoveDirection.Up ? (movePosition + caretIndent) : (movePosition + caretIndent - moveText.Length);

            textView.Caret.MoveTo(new SnapshotPoint(textView.TextSnapshot, newCaretPosition));
            textView.Selection.Select(new SnapshotSpan(textView.TextSnapshot, (direction == MoveDirection.Up) ? movePosition : movePosition - moveText.Length, moveText.Length), false);
            FormatDocument(commandTarget);
            textView.Selection.Clear();

            return(newCaretPosition);
        }
        public static void ReportProblems(CompilationAnalysisContext context, SyntaxNode methodDeclaration)
        {
            var staticKeyword = methodDeclaration.ChildTokens().Where(x => x.IsKind(SyntaxKind.StaticKeyword)).FirstOrDefault();

            if (staticKeyword == null || staticKeyword.IsKind(SyntaxKind.None))
            {
                if (IsInEntityClass(methodDeclaration))
                {
                    var methodName = methodDeclaration.ChildTokens().Where(x => x.IsKind(SyntaxKind.IdentifierToken)).FirstOrDefault();

                    if (methodName != null)
                    {
                        var diagnostic = Diagnostic.Create(Rule, methodName.GetLocation(), methodName);

                        context.ReportDiagnostic(diagnostic);
                    }
                }
            }
        }
Example #13
0
        private void InitializeOOTypeMember(IOOTypeMember itemAsOO, SyntaxNode syntaxNode, IDom parent, SemanticModel model)
        {
            if (itemAsOO == null)
            {
                return;
            }
            var itemAsDom = itemAsOO as IRoslynHasSymbol;

            //itemAsOO.IsAbstract = itemAsDom.Symbol.IsAbstract;
            itemAsOO.IsAbstract = syntaxNode.ChildTokens().Any(x => x.Kind() == SyntaxKind.AbstractKeyword);
            itemAsOO.IsVirtual  = itemAsDom.Symbol.IsVirtual;
            itemAsOO.IsOverride = itemAsDom.Symbol.IsOverride;
            itemAsOO.IsSealed   = itemAsDom.Symbol.IsSealed;
            var itemAsCanBeNew = itemAsOO as ICanBeNew;

            if (itemAsCanBeNew != null)
            {
                // See note on IsNew on interface before changing
                itemAsCanBeNew.IsNew = syntaxNode.ChildTokens().Any(x => x.Kind() == SyntaxKind.NewKeyword);
            }
        }
Example #14
0
        private static async Task <Document> MakeConstantLeft(Document document, SyntaxNode node, CancellationToken cancellationToken)
        {
            // Sometimes the equal node is the child of the node passed in
            if (!BTAnalyzer.IsEqualFamilyExpression(node.Kind()))
            {
                node = node.ChildNodes().FirstOrDefault();
            }

            // Get child nodes
            if (null == node)
            {
                return(null);
            }

            // Get child node
            SyntaxNode[] childNodes = node.ChildNodes().ToArray();
            if (2 != childNodes.Count())
            {
                return(null);
            }

            // Replace the old local declaration with the new local declaration
            var oldRoot = await document.GetSyntaxRootAsync(cancellationToken);

            SyntaxNode newNode0 = childNodes[0].ReplaceToken(childNodes[0].GetFirstToken(), SyntaxFactory.ParseToken(childNodes[0].GetFirstToken().ToString().Trim()));
            SyntaxNode newNode1 = childNodes[1].ReplaceToken(childNodes[1].GetFirstToken(), SyntaxFactory.ParseToken(childNodes[1].GetFirstToken().ToString() + " "));

            SyntaxNode newRoot = null;
            SyntaxNode newNode = null;

            try
            {
                newNode = node.ReplaceNodes(childNodes, (original, _) => original == childNodes[0] ? newNode1 : newNode0);
                SyntaxToken token = newNode.ChildTokens().FirstOrDefault();
                if (null == token)
                {
                    return(null);
                }

                if (BTCodeFixProvider.GreaterDictionary.ContainsKey(token.Kind()))
                {
                    newNode = newNode.ReplaceToken(token, SyntaxFactory.ParseToken(SyntaxFactory.Token(BTCodeFixProvider.GreaterDictionary[token.Kind()]).ToString() + " "));
                }

                newRoot = oldRoot.ReplaceNode(node, newNode);
            }
            catch (Exception e)
            {
            }

            // Return document with transformed tree
            return(document.WithSyntaxRoot(newRoot));
        }
Example #15
0
        // A syntax tree has SyntaxNodes, SyntaxTokens and SyntaxTrivia, for more detail please refer to link below:
        // https://docs.microsoft.com/en-us/dotnet/csharp/roslyn-sdk/get-started/syntax-analysis
        // This function's purpose is to remove all trivia from the syntax tree, so it needs to iterate through all
        // existing SyntaxNodes and SyntaxTokens and to replace each of them without trivia.
        public static SyntaxNode RemoveAllTrivia(this SyntaxNode node)
        {
            if (node != null)
            {
                node = node.WithoutTrivia();

                var childNodes = node.ChildNodes();
                node = node.ReplaceNodes(childNodes, (oldNode, _) => oldNode.RemoveAllTrivia());

                var childTokens = node.ChildTokens();
                node = node.ReplaceTokens(childTokens, (oldToken, _) => oldToken.WithoutTrivia());
            }
            return(node);
        }
Example #16
0
        private bool IsSingleCharViolation(SyntaxNode declaration)
        {
            var identifier = declaration.ChildTokens().First(t => t.RawKind == IdentifierToken);

            if (IsInLoop(declaration))
            {
                return(false);
            }
            if (IsInLamda(declaration))
            {
                return(false);
            }
            return(identifier.Value.ToString().Length == 1);
        }
Example #17
0
 public static SyntaxNode Token2Child(this SyntaxNode node, string token)
 {
     if (node.ChildTokens().Any(t => t.ToString() == token))
     {
         return(node);
     }
     if (node.ChildNodes().Any(c => Token2Child(c, token) != null))
     {
         return(node.ChildNodes().First(c => Token2Child(c, token) != null));
     }
     else
     {
         return(null);
     }
 }
Example #18
0
 public static bool HasParentToken(this SyntaxNode node, string token)
 {
     if (node.ChildTokens().Any(t => t.ToString() == token))
     {
         return(true);
     }
     if (node.Parent != null)
     {
         return(HasParentToken(node.Parent, token));
     }
     else
     {
         return(false);
     }
 }
Example #19
0
 public static bool HasChildToken(this SyntaxNode node, string token)
 {
     if (node.ChildTokens().Any(t => t.ToString() == token))
     {
         return(true);
     }
     if (node.ChildNodes().Any(c => HasChildToken(c, token)))
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
Example #20
0
 public static SyntaxNode Token2Parent(this SyntaxNode node, string token)
 {
     if (node.ChildTokens().Any(t => t.ToString() == token))
     {
         return(node);
     }
     if (node.Parent != null && Token2Parent(node.Parent, token) != null)
     {
         return(Token2Parent(node.Parent, token));
     }
     else
     {
         return(null);
     }
 }
Example #21
0
        protected void HandleTrailingTrivia(SyntaxNode syntaxNode, SemanticModel model, IDom parent)
        {
            var trailingTrivia = syntaxNode.ChildTokens().Last().LeadingTrivia;
            var trailing       = CreateFromWorker.GetDetail(syntaxNode, trailingTrivia,
                                                            parent, model, OutputContext);
            var container = parent as IRDomContainer;

            if (trailing.Any() && container != null)
            {
                foreach (var newTrailing in trailing)
                {
                    container.AddOrMoveMember(newTrailing);
                }
            }
        }
Example #22
0
        private void TraverseIfCondition(SyntaxNodeAnalysisContext context, SyntaxNode node, ref int found)
        {
            foreach (var child in node.ChildTokens())
            {
                if (child.ValueText == "&&" || child.ValueText == "||")
                {
                    found++;
                }
            }

            foreach (var child in node.ChildNodes())
            {
                TraverseIfCondition(context, child, ref found);
            }
        }
        private static bool TryGetFunctionNameInStringLiteral(SyntaxNode node, out string functionName)
        {
            if (node != null && node.IsKind(SyntaxKind.StringLiteralExpression))
            {
                var stringLiteralToken = node.ChildTokens().Where(x => x.IsKind(SyntaxKind.StringLiteralToken)).FirstOrDefault();
                if (stringLiteralToken != null)
                {
                    functionName = stringLiteralToken.ValueText;
                    return(true);
                }
            }

            functionName = null;
            return(false);
        }
Example #24
0
            public override void Visit(SyntaxNode node)
            {
                var ns    = node.Language == "C#" ? kindNs : node.Language;
                var kind  = new Kind(node.Kind().ToString(), ns, true);
                var aNode = new AstNode("unknown", kind);
                var span  = node.GetLocation().GetLineSpan();

                aNode.key = keyMan.GetKey();

                aNode.SetProperty("filename", this.filename);
                aNode.SetProperty("start_column", span.StartLinePosition.Character);
                aNode.SetProperty("start_line", span.StartLinePosition.Line);
                aNode.SetProperty("start_offset", node.Span.Start);
                aNode.SetProperty("end_column", span.EndLinePosition.Character);
                aNode.SetProperty("end_line", span.EndLinePosition.Line);
                aNode.SetProperty("end_offset", node.Span.End);

                if (stack.Count == 0)
                {
                    aNode.parentKey = parentKey;
                }
                else
                {
                    var parentNode = stack.Peek();
                    aNode.olderSiblings = parentNode.childKeys.ToArray();
                    parentNode.childKeys.Add(aNode.key);
                    aNode.parentKey = parentNode.key;
                }

                foreach (var tok in node.ChildTokens())
                {
                    var kindStr = tok.Kind().ToString();
                    var value   = tok.Value;
                    aNode.SetProperty(kindStr, value);
                }

                PrintNode(aNode);
                stack.Push(aNode);

                // Visit children
                base.Visit(node);

                if (stack.Count > 1)
                {
                    stack.Pop();
                }
            }
Example #25
0
        public override void DefaultVisit(SyntaxNode node)
        {
            var nodes  = node.ChildNodes();
            var enumer = nodes.GetEnumerator();

            while (enumer.MoveNext())
            {
                this.Visit(enumer.Current);
            }
            var tokens  = node.ChildTokens();
            var enumer2 = tokens.GetEnumerator();

            while (enumer2.MoveNext())
            {
                this.VisitToken(enumer2.Current);
            }
        }
Example #26
0
        private List <string> GetTokenNamesWithKind(SyntaxNode node)
        {
            var names = new List <string> {
                $"NODE {node.Kind()}"
            };

            foreach (var token in node.ChildTokens())
            {
                names.Add($"{token.ValueText} {token.Kind()}");
            }

            foreach (var childNode in node.ChildNodes())
            {
                names.AddRange(GetTokenNamesWithKind(childNode));
            }

            return(names);
        }
        private static IEnumerable <Token> ProcessNodeChildren(SyntaxNode node)
        {
            foreach (var token in node.ChildTokens())
            {
                yield return(ConvertToken(token));
            }

            foreach (var childNode in node.ChildNodes())
            {
                var nodeString = childNode.ToString();
                var kind       = childNode.Kind();

                foreach (var childToken in ProcessNodeChildren(childNode))
                {
                    yield return(childToken);
                }
            }
        }
            private bool IsPublic(SyntaxNode statement)
            {
                var isPublic = statement.ChildTokens().AnyOfKind(SyntaxKind.PublicKeyword);

                // statement is a declaration statement - method, class, etc. its Parent is
                // declaration block, its Parent is another block.
                var parentInterfaceBlock = statement.Parent?.Parent;

                // Interface members are public even though they don't have modifiers
                if (!isPublic &&
                    parentInterfaceBlock != null &&
                    parentInterfaceBlock.IsKind(SyntaxKind.InterfaceBlock))
                {
                    isPublic = IsPublic(((InterfaceBlockSyntax)parentInterfaceBlock).InterfaceStatement);
                }

                return(isPublic);
            }
        /// <summary>
        /// Finds the member identifier using the specified node
        /// </summary>
        /// <param name="node">The node</param>
        /// <returns>The descendant identifier</returns>
        public static string FindMemberIdentifier(SyntaxNode node)
        {
            var directNodeIdentifier = node
                                       .ChildTokens()
                                       .FirstOrDefault(t => t.Kind() == SyntaxKind.IdentifierToken)
                                       .Text;

            if (!string.IsNullOrWhiteSpace(directNodeIdentifier))
            {
                return(directNodeIdentifier);
            }

            var descendantIdentifier = node
                                       .DescendantTokens()
                                       .LastOrDefault(t => t.Kind() == SyntaxKind.IdentifierToken)
                                       .Text;

            return(descendantIdentifier);
        }
Example #30
0
        private static void GetContInDeep(SyntaxNode node, SyntaxKind syntaxKind)
        {
            node.ChildNodes().All(t =>
            {
                GetContInDeep(t, syntaxKind);
                return(true);
            });

            node.ChildTokens().All(t =>
            {
                var count = t
                            .GetAllTrivia()
                            .Count(t2 => t2.IsKind(SyntaxKind.EndOfLineTrivia));

                totalCount += count;

                return(true);
            });
        }