Exemplo n.º 1
0
 private static int GetDepth(SyntaxNodeOrToken syntax, int depth = 0)
 {
     if (syntax.IsNode)
     {
         return(syntax.ChildNodesAndTokens().Count == 0 ? depth : syntax.ChildNodesAndTokens().Max(x => GetDepth(x, depth + 1)));
     }
     return((syntax.AsToken().HasLeadingTrivia || syntax.AsToken().HasTrailingTrivia) ? depth + 1 : depth);
 }
Exemplo n.º 2
0
        private static bool IsTypeName(
            SyntaxNodeOrToken nodeOrToken,
            SemanticModel semanticModel,
            CancellationToken cancellationToken)
        {
            // Syntactically, everything works out. We're in a pretty good spot to show 'when' now.
            // But let's not do it just yet... Consider these cases:
            // case SyntaxNode |
            // case SyntaxNode w|
            // If what we have here is known to be a type, we don't want to clutter the variable name suggestion list
            // with 'when' since we know that the resulting code would be semantically invalid.

            bool isVar;
            ImmutableArray <ISymbol> symbols;

            if (nodeOrToken.IsNode)
            {
                var node       = nodeOrToken.AsNode();
                var expression = node as ExpressionSyntax
                                 ?? (node as ConstantPatternSyntax)?.Expression;

                if (!(expression is TypeSyntax typeSyntax))
                {
                    return(false);
                }

                // We don't pass in the semantic model - let IsPotentialTypeName handle the cases where it's clear
                // from the syntax, but other than that, we need to do our own logic here.
                if (typeSyntax.IsPotentialTypeName(semanticModelOpt: null, cancellationToken))
                {
                    return(true);
                }

                isVar   = typeSyntax.IsVar;
                symbols = semanticModel.LookupName(typeSyntax, namespacesAndTypesOnly: false, cancellationToken);
            }
            else
            {
                // In a var pattern, the 'var' keyword is not wrapped in a type syntax, so we might just have a naked token.
                var token = nodeOrToken.AsToken();

                isVar   = token.Text == SyntaxFacts.GetText(SyntaxKind.VarKeyword);
                symbols = semanticModel.LookupSymbols(nodeOrToken.AsToken().SpanStart, null, token.Text);
            }

            if (symbols.Length == 0)
            {
                // For all unknown identifiers except var, we return false (therefore 'when' will be offered),
                // because the user could later create a type with this name OR a constant. We give them both options.
                // But with var, when there is no type or constant with this name, we instead make the reasonable
                // assumption that the user didn't just type 'var' to then create a constant named 'var', but really
                // is about to declare a variable. Therefore we don't want to interfere with the declaration.
                // However note that if such a constant already exists, we do the right thing and do offer 'when'.
                return(isVar);
            }

            return(symbols.All(symbol => symbol is IAliasSymbol || symbol is ITypeSymbol));
        }
Exemplo n.º 3
0
            private bool CanReuse(SyntaxNodeOrToken nodeOrToken)
            {
                // Zero width nodes and tokens always indicate that the parser had to do
                // something tricky, so don't reuse them.
                // NOTE: this is slightly different from IsMissing because of omitted type arguments
                // and array size expressions.
                if (nodeOrToken.FullWidth == 0)
                {
                    return(false);
                }

                // As of 2013/03/14, the compiler never attempts to incrementally parse a tree containing
                // annotations.  Our goal in instituting this restriction is to prevent API clients from
                // taking a depedency on the survival of annotations.
                if (nodeOrToken.ContainsAnnotations)
                {
                    return(false);
                }

                // We can't reuse a node or token if it intersects a changed text range.
                if (this.IntersectsNextChange(nodeOrToken))
                {
                    return(false);
                }

                // don't reuse nodes or tokens with skipped text or diagnostics attached to them
                if (nodeOrToken.ContainsDiagnostics ||
                    (nodeOrToken.IsToken && ((CSharpSyntaxNode)nodeOrToken.AsToken().Node).ContainsSkippedText && nodeOrToken.Parent.ContainsDiagnostics))
                {
                    return(false);
                }

                // fabricated tokens did not come from the lexer (likely from parser)
                if (IsFabricatedToken(nodeOrToken.CSharpKind()))
                {
                    return(false);
                }

                // don't reuse nodes that are incomplete. this helps cases were an incomplete node
                // completes differently after a change with far look-ahead.
                //
                // NOTE(cyrusn): It is very unfortunate that we even need this check given that we
                // have already checked for ContainsDiagnostics above.  However, there is a case where we
                // can have a node with a missing token *and* there are no diagnostics.
                // Specifically, this happens in the REPL when you have the last statement without a
                // trailing semicolon.  We treat this as an ExpressionStatement with a missing
                // semicolon, but we do not report errors.  It would be preferable to fix that so
                // that the semicolon can be optional rather than abusing the system.
                if ((nodeOrToken.IsToken && nodeOrToken.AsToken().IsMissing) ||
                    (nodeOrToken.IsNode && IsIncomplete((CSharp.CSharpSyntaxNode)nodeOrToken.AsNode())))
                {
                    return(false);
                }


                return(true);
            }
Exemplo n.º 4
0
        internal static async Task <Document> AddAccessModifierAsync(
            Document document,
            SyntaxNode declaration,
            CancellationToken cancellationToken)
        {
            SyntaxNode oldRoot = await document.GetSyntaxRootAsync(cancellationToken);

            SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken);

            SyntaxKind  modifierKind  = GetModifierKind(declaration, semanticModel, cancellationToken);
            SyntaxToken modifierToken = SyntaxFactory.Token(modifierKind).WithTrailingSpace();

            SyntaxTokenList modifiers = declaration.GetDeclarationModifiers();

            SyntaxNode newDeclaration = declaration;

            if (modifiers.Count > 0)
            {
                modifiers = modifiers
                            .Replace(modifiers[0], modifiers[0].WithoutLeadingTrivia())
                            .Insert(0, modifierToken.WithLeadingTrivia(modifiers[0].LeadingTrivia));
            }
            else
            {
                SyntaxNodeOrToken nodeOrToken = GetNodeOrToken(declaration);

                if ((nodeOrToken.IsNode && nodeOrToken.AsNode() == null) ||
                    (nodeOrToken.IsToken && nodeOrToken.AsToken().IsKind(SyntaxKind.None)))
                {
                    Debug.Assert(false, "");
                    return(document);
                }

                modifiers = SyntaxFactory.TokenList(modifierToken.WithLeadingTrivia(nodeOrToken.GetLeadingTrivia()));

                if (nodeOrToken.IsNode)
                {
                    newDeclaration = declaration.ReplaceNode(
                        nodeOrToken.AsNode(),
                        nodeOrToken.AsNode().WithoutLeadingTrivia());
                }
                else
                {
                    newDeclaration = declaration.ReplaceToken(
                        nodeOrToken.AsToken(),
                        nodeOrToken.AsToken().WithoutLeadingTrivia());
                }
            }

            newDeclaration = GetNewDeclaration(newDeclaration, modifiers);

            SyntaxNode newRoot = oldRoot.ReplaceNode(declaration, newDeclaration);

            return(document.WithSyntaxRoot(newRoot));
        }
    private static bool IsWellKnownConstant(SyntaxNodeOrToken node)
    {
        if (!node.IsToken)
        {
            return(false);
        }
        string text = node.AsToken().Text;

        if (text == null)
        {
            return(false);
        }
        // note: this is naïve. we also should add 0d, 0f, 0m, etc.
        if (text == "1" || text == "-1" || text == "0")
        {
            return(true);
        }
        // ok for '\0' or '\r', etc.
        if (text.Length == 4 && text.StartsWith("'\\") && text.EndsWith("'"))
        {
            return(true);
        }
        if (text == "' '")
        {
            return(true);
        }
        if (text == "")
        {
            return(true);
        }
        return(false);
    }
Exemplo n.º 6
0
        private void append(TreeViewItem _rootItem, SyntaxNode _node)
        {
            if (__treeView.Items.Count == 0)
            {
                __treeView.Items.Add(_rootItem);
            }

            ChildSyntaxList _children = _node.ChildNodesAndTokens();

            ChildSyntaxList.Enumerator _enumerator = _children.GetEnumerator();
            while (_enumerator.MoveNext())
            {
                SyntaxNodeOrToken _syntaxElement = _enumerator.Current;
                if (_syntaxElement.IsNode)
                {
                    SyntaxNode   _childNode     = _syntaxElement.AsNode();
                    TreeViewItem _childNodeItem = syntaxNodeItem(_childNode);
                    _rootItem.Items.Add(_childNodeItem);
                    append(_childNodeItem, _childNode);
                }
                else
                if (_syntaxElement.IsToken)
                {
                    SyntaxToken _token = _syntaxElement.AsToken();
                    _rootItem.Items.Add(syntaxTokenItem(_token));
                }
            }
        }
Exemplo n.º 7
0
        public static void Dump(this SyntaxNodeOrToken nodeOrToken, TextWriter writer = null, int depth = 0)
        {
            const string indentString = "  ";

            if (nodeOrToken.IsMissing)
            {
                return;
            }

            writer = writer ?? Console.Out;

            for (int i = 0; i < depth; i++)
            {
                writer.Write(indentString);
            }

            if (nodeOrToken.IsNode)
            {
                var node = nodeOrToken.AsNode();
                writer.WriteLine("{0}: {1}", node.GetType().Name, node);
                foreach (var child in node.ChildNodesAndTokens())
                {
                    Dump(child, writer, depth + 1);
                }
            }
            else
            {
                var token = nodeOrToken.AsToken();
                writer.WriteLine("{0}: {1}", token.Kind(), token);
            }
        }
Exemplo n.º 8
0
        internal static double ComputeDistance(SyntaxNodeOrToken oldNodeOrToken, SyntaxNodeOrToken newNodeOrToken)
        {
            Debug.Assert(newNodeOrToken.IsToken == oldNodeOrToken.IsToken);

            double distance;

            if (oldNodeOrToken.IsToken)
            {
                var leftToken  = oldNodeOrToken.AsToken();
                var rightToken = newNodeOrToken.AsToken();

                distance = ComputeDistance(leftToken, rightToken);
                Debug.Assert(!SyntaxFactory.AreEquivalent(leftToken, rightToken) || distance == ExactMatchDist);
            }
            else
            {
                var leftNode  = oldNodeOrToken.AsNode();
                var rightNode = newNodeOrToken.AsNode();

                distance = ComputeDistance(leftNode, rightNode);
                Debug.Assert(!SyntaxFactory.AreEquivalent(leftNode, rightNode) || distance == ExactMatchDist);
            }

            return(distance);
        }
Exemplo n.º 9
0
    /// <summary>
    /// Recursive method that "quotes" a SyntaxNode, SyntaxToken, SyntaxTrivia or other objects.
    /// </summary>
    /// <returns>A description of Roslyn API calls necessary to recreate the input object.</returns>
    private ApiCall Quote(object treeElement, string name = null)
    {
        if (treeElement is SyntaxTrivia)
        {
            return(QuoteTrivia((SyntaxTrivia)treeElement));
        }

        if (treeElement is SyntaxToken)
        {
            return(QuoteToken((SyntaxToken)treeElement, name));
        }

        if (treeElement is SyntaxNodeOrToken)
        {
            SyntaxNodeOrToken syntaxNodeOrToken = (SyntaxNodeOrToken)treeElement;
            if (syntaxNodeOrToken.IsNode)
            {
                return(QuoteNode(syntaxNodeOrToken.AsNode(), name));
            }
            else
            {
                return(QuoteToken(syntaxNodeOrToken.AsToken(), name));
            }
        }

        return(QuoteNode((SyntaxNode)treeElement, name));
    }
Exemplo n.º 10
0
        public override Match Run(SyntaxNodeOrToken nodeOrToken)
        {
            if (nodeOrToken.Kind() != _kind)
                return Match.NoMatch;

            return nodeOrToken.AsToken().ValueText == _text ? Match.Success : Match.NoMatch;
        }
        public static SyntaxNodeOrToken WithoutLeadingTrivia(this SyntaxNodeOrToken nodeOrToken)
        {
            if (nodeOrToken.IsNode)
            {
                return(nodeOrToken.AsNode().WithoutLeadingTrivia());
            }

            return(nodeOrToken.AsToken().WithoutLeadingTrivia());
        }
Exemplo n.º 12
0
        public TRoot Replace <TRoot>(TRoot root, SyntaxNodeOrToken oldNodeOrToken, SyntaxNodeOrToken newNodeOrToken) where TRoot : SyntaxNode
        {
            if (oldNodeOrToken.IsToken)
            {
                return(root.ReplaceToken(oldNodeOrToken.AsToken(), newNodeOrToken.AsToken()));
            }

            return(root.ReplaceNode(oldNodeOrToken.AsNode(), newNodeOrToken.AsNode()));
        }
        public static SyntaxToken GetToken(this SyntaxNodeOrToken nodeOrToken)
        {
            if (!nodeOrToken.IsToken)
            {
                throw new ArgumentException("expected token", nameof(nodeOrToken));
            }

            return(nodeOrToken.AsToken());
        }
Exemplo n.º 14
0
        public static Edit UpdateBetween(
            SyntaxNodeOrToken left, SyntaxTriviaList leftTrailingTrivia,
            SyntaxTriviaList rightLeadingTrivia, SyntaxNodeOrToken right)
        {
            var leftLastToken   = left.IsToken ? left.AsToken() : left.AsNode().GetLastToken();
            var rightFirstToken = right.IsToken ? right.AsToken() : right.AsNode().GetFirstToken();

            return(new Edit(leftLastToken, leftTrailingTrivia, rightFirstToken, rightLeadingTrivia));
        }
    public static SyntaxToken WithSourceMappingFrom(this SyntaxToken converted, SyntaxNodeOrToken fromToken)
    {
        var origLinespan = fromToken.SyntaxTree.GetLineSpan(fromToken.Span);

        if (fromToken.IsToken)
        {
            converted = fromToken.AsToken().CopyAnnotationsTo(converted);
        }
        return(converted.WithSourceStartLineAnnotation(origLinespan).WithSourceEndLineAnnotation(origLinespan));
    }
Exemplo n.º 16
0
 public SourceLabelSymbol(
     MethodSymbol containingMethod,
     SyntaxNodeOrToken identifierNodeOrToken,
     ConstantValue switchCaseLabelConstant = null)
     : base(identifierNodeOrToken.IsToken ? identifierNodeOrToken.AsToken().ValueText : identifierNodeOrToken.ToString())
 {
     this.containingMethod        = containingMethod;
     this.identifierNodeOrToken   = identifierNodeOrToken;
     this.switchCaseLabelConstant = switchCaseLabelConstant;
 }
Exemplo n.º 17
0
        private void ClassifyNodeOrToken(SyntaxNodeOrToken nodeOrToken)
        {
            if (nodeOrToken.IsToken)
            {
                ClassifyToken(nodeOrToken.AsToken());
                return;
            }

            ClassifyNode(nodeOrToken.AsNode());
        }
 public SourceLabelSymbol(
     MethodSymbol containingMethod,
     SyntaxNodeOrToken identifierNodeOrToken,
     ConstantValue switchCaseLabelConstant = null)
     : base(identifierNodeOrToken.IsToken ? identifierNodeOrToken.AsToken().ValueText : identifierNodeOrToken.ToString())
 {
     this.containingMethod = containingMethod;
     this.identifierNodeOrToken = identifierNodeOrToken;
     this.switchCaseLabelConstant = switchCaseLabelConstant;
 }
Exemplo n.º 19
0
        internal Roslyn.Compilers.CSharp.SyntaxToken FindTokenInternal(int position)
        {
            SyntaxNodeOrToken syntaxNodeOrToken = (SyntaxNodeOrToken)this;

            while (syntaxNodeOrToken.AsNode() != null)
            {
                syntaxNodeOrToken = Roslyn.Compilers.CSharp.SyntaxNode.GetChildThatContainsPosition(syntaxNodeOrToken.ChildNodesAndTokens(), position);
            }
            return(syntaxNodeOrToken.AsToken());
        }
Exemplo n.º 20
0
        private void ClassifyNodeOrToken(SyntaxNodeOrToken nodeOrToken)
        {
            if (nodeOrToken.IsToken)
            {
                ClassifyToken(nodeOrToken.AsToken());
                return;
            }

            ClassifyNode(nodeOrToken.AsNode());
        }
        // Helpers for populating the treeview.

        private void AddNodeOrToken(TreeViewItem parentItem, SyntaxNodeOrToken nodeOrToken)
        {
            if (nodeOrToken.IsNode)
            {
                AddNode(parentItem, nodeOrToken.AsNode());
            }
            else
            {
                AddToken(parentItem, nodeOrToken.AsToken());
            }
        }
Exemplo n.º 22
0
 public virtual string ExtractMetadataName(SyntaxNodeOrToken nodeOrToken)
 {
     if (nodeOrToken.IsToken)
     {
         return(nodeOrToken.AsToken().ValueText);
     }
     else
     {
         return(nodeOrToken.AsNode().ToString());
     }
 }
Exemplo n.º 23
0
 public virtual object ExtractValue(SyntaxNodeOrToken nodeOrToken)
 {
     if (nodeOrToken.IsToken)
     {
         return(nodeOrToken.AsToken().Value);
     }
     else
     {
         return(ExtractValue(nodeOrToken.AsNode().ToString()));
     }
 }
Exemplo n.º 24
0
        private void TestAnnotation(SyntaxAnnotation annotation, SyntaxNode root, SyntaxNodeOrToken oldNodeOrToken)
        {
            // Test for existence of exactly one annotation
            if (oldNodeOrToken.IsToken)
            {
                TestAnnotation(annotation, root, oldNodeOrToken.AsToken());
                return;
            }

            TestAnnotation(annotation, root, oldNodeOrToken.AsNode());
        }
Exemplo n.º 25
0
 private void ClassifyNodeOrToken(SyntaxNodeOrToken nodeOrToken)
 {
     var node = nodeOrToken.AsNode();
     if (node != null)
     {
         ClassifyNode(node);
     }
     else
     {
         ClassifyToken(nodeOrToken.AsToken());
     }
 }
 public static Result IsTokenwiseEquivalent(SyntaxNodeOrToken nodeOrTokenA, SyntaxNodeOrToken nodeOrTokenB)
 {
     if (nodeOrTokenA.IsNode && nodeOrTokenB.IsNode)
     {
         return(IsTokenwiseEquivalent(nodeOrTokenA.AsNode(), nodeOrTokenB.AsNode()));
     }
     if (nodeOrTokenA.IsToken && nodeOrTokenB.IsToken)
     {
         return(IsTokenwiseEquivalent(nodeOrTokenA.AsToken(), nodeOrTokenB.AsToken()));
     }
     return(Result.NotEquivalent);
 }
Exemplo n.º 27
0
        private void ClassifyNodeOrToken(SyntaxNodeOrToken nodeOrToken)
        {
            Debug.Assert(nodeOrToken.IsNode || nodeOrToken.IsToken);

            if (nodeOrToken.IsToken)
            {
                ClassifyToken(nodeOrToken.AsToken());
                return;
            }

            ClassifyNode(nodeOrToken.AsNode() !);
        }
Exemplo n.º 28
0
        private Item(SyntaxNodeOrToken x)
        {
            this.SyntaxNodeOrToken = x;
            this.ChildList         = x.ChildNodesAndTokens();
            this.Language          = IsVB(x.Language) ? TargetLanguage.VB : TargetLanguage.CS;
            if (this.SyntaxNodeOrToken.IsToken)
            {
                Value = this.Token = x.AsToken();
                Text  = this.Token.Text;

                if (this.Language == TargetLanguage.VB)
                {
                    foreach (var k in kindsVB)
                    {
                        if (this.Token.IsKind(k))
                        {
                            this.Kind = k;
                            break;
                        }
                    }
                }
                else
                {
                    foreach (var k in kindsCS)
                    {
                        if (this.Token.IsKind(k))
                        {
                            this.Kind = k;
                            break;
                        }
                    }
                }
                this.ItemType = ItemType.Token;
            }
            else
            {
                Value = this.Node = x.AsNode();

                if (this.Node is VB.VisualBasicSyntaxNode)
                {
                    var node = (VB.VisualBasicSyntaxNode) this.Node;
                    this.Kind = node.Kind();
                    this.Text = this.Kind.ToString();
                }
                else
                {
                    this.Text = ((CS.CSharpSyntaxNode)Node).Kind().ToString();
                    //Text = this.Node.ToString();
                }
                this.ItemType = ItemType.Node;
            }
        }
Exemplo n.º 29
0
        internal static DirectiveStack ApplyDirectives(this SyntaxNodeOrToken nodeOrToken, DirectiveStack stack)
        {
            if (nodeOrToken.IsToken)
            {
                return(nodeOrToken.AsToken().ApplyDirectives(stack));
            }

            if (nodeOrToken.IsNode)
            {
                return(nodeOrToken.AsNode().ApplyDirectives(stack));
            }

            return(stack);
        }
Exemplo n.º 30
0
        public static void CheckParents(
            SyntaxNodeOrToken nodeOrToken,
            SyntaxTree expectedSyntaxTree
            )
        {
            Assert.Equal(expectedSyntaxTree, nodeOrToken.SyntaxTree);

            var span = nodeOrToken.Span;

            if (nodeOrToken.IsToken)
            {
                var token = nodeOrToken.AsToken();
                foreach (var trivia in token.LeadingTrivia)
                {
                    var tspan       = trivia.Span;
                    var parentToken = trivia.Token;
                    Assert.Equal(parentToken, token);
                    if (trivia.HasStructure)
                    {
                        var parentTrivia = trivia.GetStructure().Parent;
                        Assert.Null(parentTrivia);
                        CheckParents((CSharpSyntaxNode)trivia.GetStructure(), expectedSyntaxTree);
                    }
                }

                foreach (var trivia in token.TrailingTrivia)
                {
                    var tspan       = trivia.Span;
                    var parentToken = trivia.Token;
                    Assert.Equal(parentToken, token);
                    if (trivia.HasStructure)
                    {
                        var parentTrivia = trivia.GetStructure().Parent;
                        Assert.Null(parentTrivia);
                        CheckParents(trivia.GetStructure(), expectedSyntaxTree);
                    }
                }
            }
            else
            {
                var node = nodeOrToken.AsNode();
                foreach (var child in node.ChildNodesAndTokens())
                {
                    var parent = child.Parent;
                    Assert.Equal(node, parent);
                    CheckParents(child, expectedSyntaxTree);
                }
            }
        }
Exemplo n.º 31
0
 public static SyntaxTrivia GetEndOfLine(SyntaxNodeOrToken nodeOrToken)
 {
     if (nodeOrToken.IsNode)
     {
         return(GetEndOfLine(nodeOrToken.AsNode()));
     }
     else if (nodeOrToken.IsToken)
     {
         return(GetEndOfLine(nodeOrToken.AsToken()));
     }
     else
     {
         throw new ArgumentException("", nameof(nodeOrToken));
     }
 }
Exemplo n.º 32
0
        public static SyntaxNode GetRootNode(this SyntaxNodeOrToken node)
        {
            SyntaxNode retVal = null;

            if (node.IsNode)
            {
                retVal = node.AsNode().GetRootNode();
            }
            else
            {
                retVal = node.AsToken().GetRootNode();
            }

            return(retVal);
        }
Exemplo n.º 33
0
        public static NodeInfo GetNodeInfo(this SyntaxNodeOrToken nodeOrToken)
        {
            NodeInfo retVal = null;

            if (nodeOrToken.IsNode)
            {
                retVal = GetNodeInfo(nodeOrToken.AsNode());
            }
            else
            {
                retVal = GetNodeInfo(nodeOrToken.AsToken());
            }

            return(retVal);
        }
Exemplo n.º 34
0
        public override Match Run(SyntaxNodeOrToken nodeOrToken)
        {
            if (nodeOrToken.Kind() != SyntaxKind.IdentifierToken)
                return Match.NoMatch;

            var identifier = nodeOrToken.AsToken().ValueText;
            var regex = _variable.Regex;
            if (!string.IsNullOrEmpty(regex))
            {
                var regexOptions = _variable.CaseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase;
                if (!Regex.IsMatch(identifier, regex, regexOptions))
                    return Match.NoMatch;
            }

            return Match.Success.AddCapture(_variable, nodeOrToken);
        }
Exemplo n.º 35
0
        public static void CheckParents(SyntaxNodeOrToken nodeOrToken, SyntaxTree expectedSyntaxTree)
        {
            Assert.Equal(expectedSyntaxTree, nodeOrToken.SyntaxTree);

            var span = nodeOrToken.Span;

            if (nodeOrToken.IsToken)
            {
                var token = nodeOrToken.AsToken();
                foreach (var trivia in token.LeadingTrivia)
                {
                    var tspan = trivia.Span;
                    var parentToken = trivia.Token;
                    Assert.Equal(parentToken, token);
                    if (trivia.HasStructure)
                    {
                        var parentTrivia = trivia.GetStructure().Parent;
                        Assert.Null(parentTrivia);
                        CheckParents((CSharpSyntaxNode)trivia.GetStructure(), expectedSyntaxTree);
                    }
                }

                foreach (var trivia in token.TrailingTrivia)
                {
                    var tspan = trivia.Span;
                    var parentToken = trivia.Token;
                    Assert.Equal(parentToken, token);
                    if (trivia.HasStructure)
                    {
                        var parentTrivia = trivia.GetStructure().Parent;
                        Assert.Null(parentTrivia);
                        CheckParents(trivia.GetStructure(), expectedSyntaxTree);
                    }
                }
            }
            else
            {
                var node = nodeOrToken.AsNode();
                foreach (var child in node.ChildNodesAndTokens())
                {
                    var parent = child.Parent;
                    Assert.Equal(node, parent);
                    CheckParents(child, expectedSyntaxTree);
                }
            }
        }
Exemplo n.º 36
0
            private bool CanReuse(SyntaxNodeOrToken nodeOrToken)
            {
                // Zero width nodes and tokens always indicate that the parser had to do
                // something tricky, so don't reuse them.
                // NOTE: this is slightly different from IsMissing because of omitted type arguments
                // and array size expressions.
                if (nodeOrToken.FullWidth == 0)
                {
                    return false;
                }

                // As of 2013/03/14, the compiler never attempts to incrementally parse a tree containing
                // annotations.  Our goal in instituting this restriction is to prevent API clients from
                // taking a depedency on the survival of annotations.
                if (nodeOrToken.ContainsAnnotations)
                {
                    return false;
                }

                // We can't reuse a node or token if it intersects a changed text range.
                if (this.IntersectsNextChange(nodeOrToken))
                {
                    return false;
                }

                // don't reuse nodes or tokens with skipped text or diagnostics attached to them
                if (nodeOrToken.ContainsDiagnostics ||
                    (nodeOrToken.IsToken && ((CSharpSyntaxNode)nodeOrToken.AsToken().Node).ContainsSkippedText && nodeOrToken.Parent.ContainsDiagnostics))
                {
                    return false;
                }

                // fabricated tokens did not come from the lexer (likely from parser)
                if (IsFabricatedToken(nodeOrToken.CSharpKind()))
                {
                    return false;
                }

                // don't reuse nodes that are incomplete. this helps cases were an incomplete node
                // completes differently after a change with far look-ahead.
                //
                // NOTE(cyrusn): It is very unfortunate that we even need this check given that we
                // have already checked for ContainsDiagnostics above.  However, there is a case where we
                // can have a node with a missing token *and* there are no diagnostics.
                // Specifically, this happens in the REPL when you have the last statement without a
                // trailing semicolon.  We treat this as an ExpressionStatement with a missing
                // semicolon, but we do not report errors.  It would be preferable to fix that so
                // that the semicolon can be optional rather than abusing the system.
                if ((nodeOrToken.IsToken && nodeOrToken.AsToken().IsMissing) ||
                    (nodeOrToken.IsNode && IsIncomplete((CSharp.CSharpSyntaxNode)nodeOrToken.AsNode())))
                {
                    return false;
                }

                if (!nodeOrToken.ContainsDirectives)
                {
                    return true;
                }

                return this.newDirectives.IncrementallyEquivalent(this.oldDirectives);
            }
        // Helpers for populating the treeview.

        private void AddNodeOrToken(TreeViewItem parentItem, SyntaxNodeOrToken nodeOrToken)
        {
            if (nodeOrToken.IsNode)
            {
                AddNode(parentItem, nodeOrToken.AsNode());
            }
            else
            {
                AddToken(parentItem, nodeOrToken.AsToken());
            }
        }
 private static int GetDepth(SyntaxNodeOrToken syntax, int depth = 0)
 {
     if (syntax.IsNode)
     {
         return syntax.ChildNodesAndTokens().Count == 0 ? depth : syntax.ChildNodesAndTokens().Max(x => GetDepth(x, depth + 1));
     }
     return (syntax.AsToken().HasLeadingTrivia || syntax.AsToken().HasTrailingTrivia) ? depth + 1 : depth;
 }
            private SyntaxNodeOrToken VisitNodeOrToken(SyntaxNodeOrToken nodeOrToken)
            {
                if (nodeOrToken.IsNode)
                    return Visit(nodeOrToken.AsNode());

                return VisitToken(nodeOrToken.AsToken());
            }
        private bool ValidateNodeOrToken(SyntaxNodeOrToken nodeOrtoken, SyntaxTree tree, string filename = "", List<Failure> failures = null)
        {
            var retVal = true;
            if (nodeOrtoken.IsNode)
            {
                retVal = ValidateNonTerminal(nodeOrtoken.AsNode(), tree, filename, failures);
            }
            else
            {
                retVal = ValidateToken(nodeOrtoken.AsToken(), tree, filename, failures);
            }

            return retVal;
        }
Exemplo n.º 41
0
        private void VisitImpl(SyntaxNodeOrToken nodeOrToken)
        {
            greatestChildPosition.Add(nodeOrToken, 0);

            SyntaxNode node = nodeOrToken.AsNode();

            IList<string> identity;
            if (node is CompilationUnitSyntax)
            {
                identity = new List<string>();
                identity.Add("CompilationUnit");
                identities.Add(nodeOrToken, identity);
            }
            else
            {
                identity = identities[nodeOrToken.Parent].ToList();
            }

            string name = null;
            if (node is NamespaceDeclarationSyntax)
            {
                name = ((NamespaceDeclarationSyntax)node).Name.ToString();
            }
            else if (node is ClassDeclarationSyntax)
            {
                name = ((ClassDeclarationSyntax)node).Identifier.ValueText;
            }
            else if (node is VariableDeclaratorSyntax)
            {
                name = ((VariableDeclaratorSyntax)node).Identifier.ValueText;
            }
            else if (node is MethodDeclarationSyntax)
            {
                name = ((MethodDeclarationSyntax)node).Identifier.ValueText;
            }
            else if (node is PropertyDeclarationSyntax)
            {
                name = ((PropertyDeclarationSyntax)node).Identifier.ValueText;
            }
            else if (node is UsingDirectiveSyntax)
            {
                name = ((UsingDirectiveSyntax)node).Name.ToFullString().Replace(".", string.Empty) ;
            }
            else if (nodeOrToken.IsToken)
            {
                name = nodeOrToken.AsToken().ValueText;
            }

            if (!(node is CompilationUnitSyntax))
            {
                identity.Add(
                    string.Format("{0}{1}", name,
                    (++greatestChildPosition[nodeOrToken.Parent]).ToString()));
                identities.Add(nodeOrToken, identity);
            }
        }
 private void ClassifyNodeOrToken(SyntaxNodeOrToken nodeOrToken)
 {
     var node = nodeOrToken.AsNode();
     if (node != null)
     {
         ClassifyNode(node);
     }
     else
     {
         ClassifyToken(nodeOrToken.AsToken());
     }
 }
Exemplo n.º 43
0
 public bool TryGetVariable(SyntaxNodeOrToken nodeOrToken, out PatternVariable variable)
 {
     return nodeOrToken.IsToken
         ? TryGetVariable(nodeOrToken.AsToken(), out variable)
         : TryGetVariable(nodeOrToken.AsNode(), out variable);
 }
 public SourceLocationWithAssociatedNode(SyntaxTree syntaxTree, SyntaxNodeOrToken nodeOrToken, bool associateInParent = false)
     : this(syntaxTree, nodeOrToken.Span, nodeOrToken.IsNode ? nodeOrToken.AsNode() : nodeOrToken.AsToken().Parent, associateInParent)
 {
 }