Exemplo n.º 1
0
        public static PatternCapture Create(PatternVariable variable, SyntaxNodeOrToken startNodeOrToken, SyntaxNodeOrToken endNodeOrToken)
        {
            Debug.Assert(endNodeOrToken.Parent != startNodeOrToken.Parent,
                         $"{nameof(endNodeOrToken)}.{nameof(endNodeOrToken.Parent)} must match {nameof(startNodeOrToken)}", nameof(endNodeOrToken));

            return new PatternCapture(variable, startNodeOrToken, endNodeOrToken);
        }
        private static TextSpan CreateSpan(SyntaxTokenList startOpt, SyntaxNodeOrToken startFallbackOpt, SyntaxNodeOrToken endOpt)
        {
            Debug.Assert(startFallbackOpt != default(SyntaxNodeOrToken) || endOpt != default(SyntaxNodeOrToken));

            int startPos;
            if (startOpt.Count > 0)
            {
                startPos = startOpt.First().SpanStart;
            }
            else if (startFallbackOpt != default(SyntaxNodeOrToken))
            {
                startPos = startFallbackOpt.SpanStart;
            }
            else
            {
                startPos = endOpt.SpanStart;
            }

            int endPos;
            if (endOpt != default(SyntaxNodeOrToken))
            {
                endPos = GetEndPosition(endOpt);
            }
            else
            {
                endPos = GetEndPosition(startFallbackOpt);
            }

            return TextSpan.FromBounds(startPos, endPos);
        }
Exemplo n.º 3
0
        public override Match Run(SyntaxNodeOrToken nodeOrToken)
        {
            if (nodeOrToken.Kind() != SyntaxKind.Argument)
                return Match.NoMatch;

            var argument = (ArgumentSyntax) nodeOrToken.AsNode();
            if (_variable.MinOccurrences == 1 && _variable.MaxOccurrences == 1)
                return Match.Success.WithSyntaxNodeOrToken(argument);

            var argumentList = argument.Parent as ArgumentListSyntax;
            if (argumentList == null)
                return Match.NoMatch;

            var currentIndex = argumentList.Arguments.IndexOf(argument);
            var availableCount = argumentList.Arguments.Count - currentIndex - _following;
            if (availableCount == 0)
                return Match.NoMatch;

            var captureCount = _variable.MaxOccurrences == null
                ? availableCount
                : Math.Min(availableCount, _variable.MaxOccurrences.Value);

            if (captureCount < _variable.MinOccurrences)
                return Match.NoMatch;

            var endIndex = currentIndex + captureCount - 1;
            var endArgument = argumentList.Arguments[endIndex];
            return Match.Success.AddCapture(_variable, argument, endArgument);
        }
Exemplo n.º 4
0
        public override Match Run(SyntaxNodeOrToken nodeOrToken)
        {
            if (nodeOrToken.Kind() != _kind)
                return Match.NoMatch;

            return nodeOrToken.AsToken().ValueText == _text ? Match.Success : Match.NoMatch;
        }
        public SyntaxNodeOrTokenListItem(SyntaxNodeOrToken syntaxNodeOrToken)
        {
            _lineSpan = syntaxNodeOrToken.GetLocation().GetLineSpan();

            Content = $"{_lineSpan}: {syntaxNodeOrToken.Kind()} {Truncate(syntaxNodeOrToken.ToString())}";
            ToolTip = syntaxNodeOrToken.ToString();
        }
        /// <summary>
        /// Returns the nodes in the new tree that do not share the same underlying 
        /// representation in the old tree. These may be entirely new nodes or rebuilt nodes.
        /// </summary>
        /// <param name="oldNode"></param>
        /// <param name="newNode"></param>
        /// <returns></returns>
        internal static IEnumerable<SyntaxNodeOrToken> GetRebuiltNodes(SyntaxNodeOrToken oldNode, SyntaxNodeOrToken newNode)
        {
            var hashSet = new HashSet<InternalSyntax.SyntaxNode>();
            GatherNodes(oldNode.UnderlyingNode.ToGreen(), hashSet);

            var stack = new Stack<ChildSyntaxList.Enumerator>();
            if (!hashSet.Contains(newNode.UnderlyingNode.ToGreen()))
            {
                yield return newNode;
                stack.Push(newNode.Children.GetEnumerator());
            }

            while (stack.Count > 0)
            {
                var newc = stack.Pop();
                if (newc.MoveNext())
                {
                    stack.Push(newc); // put enumerator changes back on stack..
                    newNode = newc.Current;
                    if (!hashSet.Contains(newNode.UnderlyingNode.ToGreen()))
                    {
                        yield return newNode;
                        stack.Push(newNode.Children.GetEnumerator());
                    }
                }
            }
        }
Exemplo n.º 7
0
 private PatternSearchResult(PatternSearch search, Document document, SyntaxNodeOrToken nodeOrToken,  ImmutableArray<PatternCapture> captures)
 {
     Search = search;
     Document = document;
     NodeOrToken = nodeOrToken;
     Captures = captures;
 }
Exemplo n.º 8
0
 private void WriteSourceMap(SyntaxNodeOrToken node, Position pos, string str)
 {
     if (node.Kind() == SyntaxKind.IdentifierName || node.Kind() == SyntaxKind.IdentifierToken || node.Kind() == SyntaxKind.ObjectCreationExpression)
     {
         System.Diagnostics.Debug.WriteLine($"{node} ---> [{node.Kind()} | {pos}] ---> {str}");
         _sourceMapOutput.AddMapping(node, pos);
     }
 }
Exemplo n.º 9
0
 private static void GatherNodes(SyntaxNodeOrToken node, HashSet<GreenNode> hashSet)
 {
     hashSet.Add(node.UnderlyingNode);
     foreach (var child in node.ChildNodesAndTokens())
     {
         GatherNodes(child, hashSet);
     }
 }
Exemplo n.º 10
0
 public SourceLabelSymbol(
     MethodSymbol containingMethod,
     ConstantValue switchCaseLabelConstant)
 {
     _containingMethod = containingMethod;
     _identifierNodeOrToken = default(SyntaxToken);
     _switchCaseLabelConstant = switchCaseLabelConstant;
 }
Exemplo n.º 11
0
 public SourceLabelSymbol(
     MethodSymbol containingMethod,
     SyntaxNodeOrToken identifierNodeOrToken,
     ConstantValue switchCaseLabelConstant = null)
 {
     _containingMethod = containingMethod;
     _identifierNodeOrToken = identifierNodeOrToken;
     _switchCaseLabelConstant = switchCaseLabelConstant;
 }
 public SourceLabelSymbol(
     MethodSymbol containingMethod,
     ConstantValue switchCaseLabelConstant = null)
     : base(switchCaseLabelConstant.ToString())
 {
     this.containingMethod = containingMethod;
     this.identifierNodeOrToken = default(SyntaxToken);
     this.switchCaseLabelConstant = switchCaseLabelConstant;
 }
Exemplo n.º 13
0
        public static PatternSearchResult Create(PatternSearch search, Document document, SyntaxNodeOrToken nodeOrToken, ImmutableArray<PatternCapture> captures)
        {
            if (search == null)
                throw new ArgumentNullException(nameof(search));

            if (document == null)
                throw new ArgumentNullException(nameof(document));

            return new PatternSearchResult(search, document, nodeOrToken, captures);
        }
Exemplo n.º 14
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.º 16
0
 public string GetId(SyntaxNodeOrToken node)
 {
     if (names.ContainsKey(node))
     {
         return names[node];
     }
     else
     {
         return "Ast_" + String.Join("_", identities[node]);
     }
 }
Exemplo n.º 17
0
        private static IEnumerable<ParsedToken> WalkTreeRangeKeepLevelAndParent(SyntaxNodeOrToken currentRoot, int blockLevel, SyntaxNode upperStatementNode, SyntaxNode immediateStatementNode, Range range)
        {
            if (!currentRoot.IsLeafNode)
            {
                SyntaxNode syntaxNode = (SyntaxNode)currentRoot;

                SyntaxNode nextUpperStatementNode = immediateStatementNode;
                SyntaxNode nextImmediateStatementNode = syntaxNode;

                if (SyntaxKind.TableConstructorExp != syntaxNode.Kind &&
                    SyntaxKind.TableConstructorArg != syntaxNode.Kind &&
                    !StatKinds.Contains(syntaxNode.Kind))
                {
                    nextImmediateStatementNode = immediateStatementNode;
                    nextUpperStatementNode = upperStatementNode;
                }

                if (nextUpperStatementNode == null)
                {
                    nextUpperStatementNode = nextImmediateStatementNode;
                }

                if ((syntaxNode.Kind == SyntaxKind.BlockNode && nextImmediateStatementNode != null) ||
                     syntaxNode.Kind == SyntaxKind.FieldList)
                {
                    blockLevel++;
                }

                foreach (SyntaxNodeOrToken node in syntaxNode.Children)
                {
                    foreach (ParsedToken parsedToken in WalkTreeRangeKeepLevelAndParent(node,
                        blockLevel,
                        nextUpperStatementNode, nextImmediateStatementNode,
                        range))
                    {
                        yield return parsedToken;
                    }
                }
            }
            else
            {
                Token token = currentRoot as Token;

                if (token != null && token.Kind != SyntaxKind.MissingToken && token.Start >= range.Start)
                {
                    if (token.FullStart > range.End)
                    {
                        yield break;
                    }

                    yield return new ParsedToken(token, blockLevel, upperStatementNode, immediateStatementNode);
                }
            }
        }
Exemplo n.º 18
0
        private static void GetRebuiltNodes(SyntaxNodeOrToken newNode, HashSet<GreenNode> hashSet, ArrayBuilder<SyntaxNodeOrToken> nodes)
        {
            if (hashSet.Contains(newNode.UnderlyingNode))
            {
                return;
            }

            nodes.Add(newNode);

            foreach (var child in newNode.ChildNodesAndTokens())
            {
                GetRebuiltNodes(child, hashSet, nodes);
            }
        }
Exemplo n.º 19
0
            public bool TryGetNextInSpan(ref /*readonly*/ TextSpan span, out SyntaxNodeOrToken value)
            {
                value = default(SyntaxNodeOrToken);

                while (stack[stackPtr].TryMoveNextAndGetCurrent(ref value))
                {
                    if (IsInSpan(ref span, value.FullSpan))
                    {
                        return true;
                    }
                }

                stackPtr--;
                return false;
            }
Exemplo n.º 20
0
        public override Match Run(SyntaxNodeOrToken nodeOrToken)
        {
            if (nodeOrToken.Kind() != _syntaxKind)
                return Match.NoMatch;

            var result = Match.Success;

            if (nodeOrToken.IsNode)
            {
                var node = nodeOrToken.AsNode();
                var children = node.ChildNodesAndTokens();

                var matcherIndex = 0;
                var matchedEnd = 0;

                for (var i = 0; i < children.Count; i++)
                {
                    if (matcherIndex >= _childMatchers.Length)
                        return Match.NoMatch;

                    while (i < children.Count && children[i].Span.Start < matchedEnd)
                        i++;

                    if (i >= children.Count)
                        break;

                    var child = children[i];
                    var matcher = _childMatchers[matcherIndex];
                    var match = matcher.Run(child);
                    if (!match.IsMatch)
                        return Match.NoMatch;

                    // Depending on much was captured, we need to skip some matchers.

                    if (match.Captures.Any())
                        matchedEnd = match.Captures.Max(c => c.EndNodeOrToken.Span.End);

                    result = result.AddCaptures(match.Captures);
                    matcherIndex++;
                }

                var allMatchersUsed = matcherIndex >= _childMatchers.Length;
                if (!allMatchersUsed)
                    return Match.NoMatch;
            }

            return result;
        }
Exemplo n.º 21
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);
        }
                private int GetChildIndex(SyntaxNodeOrToken child)
                {
                    var parent = child.Parent;
                    int index = 0;

                    foreach (var nodeOrToken in parent.ChildNodesAndTokens())
                    {
                        if (nodeOrToken == child)
                        {
                            return index;
                        }

                        index++;
                    }

                    throw new InvalidOperationException(CSharpWorkspaceResources.Node_not_in_parent_s_child_list);
                }
Exemplo n.º 23
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);
                }
            }
        }
        private static SyntaxNodeOrToken GetNewSyntaxListItem(SyntaxNodeOrToken item)
        {
            if (!item.IsNode)
            {
                return item;
            }

            var member = (AnonymousObjectMemberDeclaratorSyntax)item.AsNode();
            var identifier = member.Expression as IdentifierNameSyntax;
            if (identifier != null &&
                identifier.Identifier.ValueText == member.NameEquals.Name.Identifier.ValueText)
            {
                return SyntaxFactory.AnonymousObjectMemberDeclarator(member.Expression).WithTriviaFrom(member);
            }

            return item;
        }
                private int GetChildIndex(SyntaxNodeOrToken child)
                {
                    var parent = child.Parent;
                    int index = 0;

                    foreach (var snot in parent.ChildNodesAndTokens())
                    {
                        if (snot == child)
                        {
                            return index;
                        }

                        index++;
                    }

                    throw new InvalidOperationException(CSharpWorkspaceResources.NodeNotInParentsChildLis);
                }
        internal static IEnumerable<SyntaxNodeOrToken> GetRebuiltNodes(SyntaxNodeOrToken oldNode, SyntaxNodeOrToken newNode)
        {
            var stack = new Stack<DifferenceInfo>();
            if (oldNode.UnderlyingNode.ToGreen() != newNode.UnderlyingNode.ToGreen())
            {
                yield return newNode;
                stack.Push(new DifferenceInfo(oldNode.Children.GetEnumerator(), newNode.Children.GetEnumerator()));
            }
            while (stack.Count > 0)
            {
                var top = stack.Pop();
                var oldc = top.oldChildren;
                var newc = top.newChildren;
                if (oldc.MoveNext())
                {
                    if (newc.MoveNext())
                    {
                        stack.Push(new DifferenceInfo(oldc, newc)); // put changes back on stack..

                        oldNode = oldc.Current;
                        newNode = newc.Current;

                        if (oldNode.UnderlyingNode.ToGreen() != newNode.UnderlyingNode.ToGreen())
                        {
                            yield return newNode;
                            stack.Push(new DifferenceInfo(oldNode.Children.GetEnumerator(), newNode.Children.GetEnumerator()));
                        }
                    }
                    else
                    {
                        // no more new children.... I guess we are done here
                    }
                }
                else
                {
                    // yield any extra nodes in newChildren list
                    while (newc.MoveNext())
                    {
                        yield return newc.Current;
                    }
                }
            }
        }
Exemplo n.º 27
0
        public override Match Run(SyntaxNodeOrToken nodeOrToken)
        {
            if (nodeOrToken.Kind() != SyntaxKind.ArgumentList)
                return Match.NoMatch;

            var argumentList = (ArgumentListSyntax) nodeOrToken.AsNode();
            if (_variable.MinOccurrences > argumentList.Arguments.Count)
                return Match.NoMatch;

            if (_variable.MaxOccurrences != null && _variable.MaxOccurrences < argumentList.Arguments.Count)
                return Match.NoMatch;

            if (argumentList.Arguments.Count == 0)
                return Match.Success;

            var first = argumentList.Arguments.First();
            var last = argumentList.Arguments.Last();
            return Match.Success.AddCapture(_variable, first, last);
        }
Exemplo n.º 28
0
        private void NamedImpl(SyntaxNodeOrToken nodeOrToken)
        {
            string name = null;
            string astType = null;
            string comments = nodeOrToken.GetLeadingTrivia().ToFullString();
            string parentComments = nodeOrToken.Parent != null ? nodeOrToken.Parent.GetLeadingTrivia().ToFullString() : null;

            //if this is the hightest ast node for this comment, look for 1 bang, else 2 bangs
            string regex = @"@(?<ast_type>[^:\s]+):(?<name>\S+)";

            Match match = Regex.Match(comments, regex);
            if (match.Success)
            {
                name = match.Groups["name"].Value;
                astType = match.Groups["ast_type"].Value;

                SyntaxKind syntaxKind = (SyntaxKind)Enum.Parse(typeof(SyntaxKind), astType);

                if (nodeOrToken.Kind() == syntaxKind)
                {
                    names.Add(nodeOrToken, name);
                }
            }
        }
Exemplo n.º 29
0
 private static NamespaceOrTypeSymbol ResolveAliasTarget(Binder binder, SyntaxNodeOrToken syntax, DiagnosticBag diagnostics, ConsList <TypeSymbol> basesBeingResolved)
 {
     return((NamespaceOrTypeSymbol)binder.BindNamespaceOrTypeSymbol(syntax, diagnostics, basesBeingResolved));
 }
Exemplo n.º 30
0
        private static TextSpan CreateSpan(SyntaxTokenList startOpt, SyntaxNodeOrToken startFallbackOpt, SyntaxNodeOrToken endOpt)
        {
            Debug.Assert(startFallbackOpt != default(SyntaxNodeOrToken) || endOpt != default(SyntaxNodeOrToken));

            int startPos;

            if (startOpt.Count > 0)
            {
                startPos = startOpt.First().SpanStart;
            }
            else if (startFallbackOpt != default(SyntaxNodeOrToken))
            {
                startPos = startFallbackOpt.SpanStart;
            }
            else
            {
                startPos = endOpt.SpanStart;
            }

            int endPos;

            if (endOpt != default(SyntaxNodeOrToken))
            {
                endPos = GetEndPosition(endOpt);
            }
            else
            {
                endPos = GetEndPosition(startFallbackOpt);
            }

            return(TextSpan.FromBounds(startPos, endPos));
        }
Exemplo n.º 31
0
 public SyntaxNodeOrToken AddAnnotationTo(SyntaxAnnotation annotation, SyntaxNodeOrToken nodeOrToken)
 {
     return(nodeOrToken.WithAdditionalAnnotations(annotation));
 }
Exemplo n.º 32
0
 private Cursor(SyntaxNodeOrToken node, int indexInParent)
 {
     this.CurrentNodeOrToken = node;
     _indexInParent          = indexInParent;
 }
Exemplo n.º 33
0
 public override IEnumerable <Diagnostic> GetDiagnostics(SyntaxNodeOrToken nodeOrToken)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 34
0
        public static void AnalyzeBlockFlow(IList <Slot> newSlots, Compilation compilation, BlockSyntax block)
        {
            const string ExpressionToReturn = nameof(ExpressionToReturn);

            // Nothing to analyze
            if (block.Statements.Count == 0)
            {
                return;
            }

            // Create a compilation unit with our expression
            var compilationUnit = CreateCompilationUnitFromBlock(ref block);

            compilation = compilation.AddSyntaxTrees(compilationUnit.SyntaxTree);

            // Detect missing variables
            var unresolvedSymbolsTable = new Dictionary <string, int>();

            foreach (var diagnostic in compilation.GetDiagnostics())
            {
                // Only process diagnostics from our generated syntax tree
                if (diagnostic.Location.SourceTree != compilationUnit.SyntaxTree)
                {
                    continue;
                }

                if (diagnostic.Id == "CS0103")
                {
                    // error CS0103: The name 'foo' does not exist in the current context
                    var node = compilationUnit.FindNode(diagnostic.Location.SourceSpan);

                    var identifierName = node as IdentifierNameSyntax ?? node.ChildNodes().OfType <IdentifierNameSyntax>().FirstOrDefault();
                    if (identifierName != null)
                    {
                        var identifierText = identifierName.Identifier.Text;

                        // Update location with earliest found
                        int location;
                        if (!unresolvedSymbolsTable.TryGetValue(identifierText, out location))
                        {
                            location = Int32.MaxValue;
                        }

                        if (diagnostic.Location.SourceSpan.Start < location)
                        {
                            unresolvedSymbolsTable[identifierText] = diagnostic.Location.SourceSpan.Start;
                        }
                    }
                }
            }

            // Order symbols by appearance order in source code
            var unresolvedSymbols = unresolvedSymbolsTable.OrderBy(x => x.Value).Select(x => x.Key).ToList();

            if (unresolvedSymbols.Count > 0)
            {
                // Includes comma
                var syntaxNodesOrToken = new SyntaxNodeOrToken[unresolvedSymbols.Count * 2 - 1];
                for (int i = 0; i < unresolvedSymbols.Count; ++i)
                {
                    if (i > 0)
                    {
                        syntaxNodesOrToken[i * 2 - 1] = SyntaxFactory.Token(SyntaxKind.CommaToken);
                    }
                    syntaxNodesOrToken[i * 2] = SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(unresolvedSymbols[i]));
                }

                // Perform a second analysis with those missing symbols declared with var
                var newCompilationUnit = compilationUnit.ReplaceNode(
                    block,
                    SyntaxFactory.Block(SyntaxFactory.SingletonList <StatementSyntax>(SyntaxFactory.LocalDeclarationStatement(
                                                                                          SyntaxFactory.VariableDeclaration(SyntaxFactory.IdentifierName("var"))
                                                                                          .WithVariables(SyntaxFactory.SeparatedList <VariableDeclaratorSyntax>(syntaxNodesOrToken))))
                                        .AddRange(block.Statements)));

                compilation     = compilation.ReplaceSyntaxTree(compilationUnit.SyntaxTree, newCompilationUnit.SyntaxTree);
                compilationUnit = newCompilationUnit;
            }

            block = compilationUnit.DescendantNodes().OfType <BlockSyntax>().First();

            // Perform semantic analysis
            var semanticModel = compilation.GetSemanticModel(compilationUnit.SyntaxTree);

            // Perform data flow analysis to know which one is input, which one is output, which one is declared
            var dataFlow = semanticModel.AnalyzeDataFlow(block.Statements[unresolvedSymbols.Count > 0 ? 1 : 0], block.Statements.Last());

            // Input: belongs to unresolvedSymbols and DataFlowsIn
            // InOut: Input + belongs to WrittenInside
            foreach (var input in dataFlow.DataFlowsIn)
            {
                if (unresolvedSymbols.Contains(input.Name))
                {
                    // Input value
                    newSlots.Add(new Slot(SlotDirection.Input, SlotKind.Value, input.Name));

                    // Check if it's also an output
                    if (dataFlow.WrittenInside.Contains(input))
                    {
                        // Output value
                        newSlots.Add(new Slot(SlotDirection.Output, SlotKind.Value, input.Name));
                    }
                }
            }

            // Output: belongs to VariablesDeclared, AlwaysAssigned, and available after the scope
            foreach (var declaredVariable in dataFlow.VariablesDeclared)
            {
                if (dataFlow.AlwaysAssigned.Contains(declaredVariable) &&
                    semanticModel.LookupSymbols(block.Statements.Last().Span.End, null, declaredVariable.Name).Length > 0)
                {
                    // Output value
                    newSlots.Add(new Slot(SlotDirection.Output, SlotKind.Value, declaredVariable.Name));
                }
            }

            // Find if return type is not void
            var returnStatement = block.Statements.Last() as ReturnStatementSyntax;

            if (returnStatement != null)
            {
                var returnType = semanticModel.GetTypeInfo(returnStatement.Expression);

                if (returnType.Type.SpecialType != SpecialType.System_Void)
                {
                    // Output value
                    newSlots.Add(new Slot(SlotDirection.Output, SlotKind.Value));
                }
            }
        }
Exemplo n.º 35
0
 public bool HasAnnotations(SyntaxNodeOrToken nodeOrToken)
 {
     return(nodeOrToken.HasAnnotations(_annotationKind));
 }
        private static void Analyze <TNode>(
            SyntaxNodeAnalysisContext context,
            SyntaxNodeOrToken openNodeOrToken,
            SeparatedSyntaxList <TNode> nodes) where TNode : SyntaxNode
        {
            TNode first = nodes.FirstOrDefault();

            if (first == null)
            {
                return;
            }

            TextSpan span = nodes.GetSpan(includeExteriorTrivia: false);

            if (span.IsSingleLine(first.SyntaxTree))
            {
                SyntaxTriviaList trailing = openNodeOrToken.GetTrailingTrivia();

                if (!IsOptionalWhitespaceThenOptionalSingleLineCommentThenEndOfLineTrivia(trailing))
                {
                    return;
                }

                int indentationLength = GetIncreasedIndentationLength(openNodeOrToken.Parent);

                if (indentationLength == 0)
                {
                    return;
                }

                if (ShouldFixIndentation(first.GetLeadingTrivia(), indentationLength))
                {
                    ReportDiagnostic();
                }
            }
            else
            {
                TextLineCollection lines = null;

                IndentationAnalysis indentationAnalysis = IndentationAnalysis.Create(openNodeOrToken.Parent);

                int indentationLength = indentationAnalysis.IncreasedIndentationLength;

                if (indentationLength == 0)
                {
                    return;
                }

                for (int i = nodes.Count - 1; i >= 0; i--)
                {
                    context.CancellationToken.ThrowIfCancellationRequested();

                    SyntaxTriviaList trailing = (i == 0)
                        ? openNodeOrToken.GetTrailingTrivia()
                        : nodes.GetSeparator(i - 1).TrailingTrivia;

                    if (IsOptionalWhitespaceThenOptionalSingleLineCommentThenEndOfLineTrivia(trailing))
                    {
                        if (ShouldFixIndentation(nodes[i].GetLeadingTrivia(), indentationLength))
                        {
                            ReportDiagnostic();
                            break;
                        }
                    }
                    else
                    {
                        if (nodes.Count > 1 &&
                            ShouldWrapAndIndent(context.Node, i))
                        {
                            ReportDiagnostic();
                            break;
                        }

                        if (nodes.Count == 1 &&
                            first.IsKind(SyntaxKind.Argument))
                        {
                            var argument = (ArgumentSyntax)(SyntaxNode)first;

                            LambdaBlock lambdaBlock = GetLambdaBlock(argument, lines ??= first.SyntaxTree.GetText().Lines);

                            if (lambdaBlock.Block != null)
                            {
                                SyntaxToken      token   = lambdaBlock.Token;
                                SyntaxTriviaList leading = token.LeadingTrivia;

                                if (leading.Any())
                                {
                                    SyntaxTrivia trivia = leading.Last();

                                    if (trivia.IsWhitespaceTrivia() &&
                                        trivia.SpanStart == lambdaBlock.LineStartIndex &&
                                        trivia.Span.Length != indentationAnalysis.IndentationLength)
                                    {
                                        ReportDiagnostic();
                                        break;
                                    }
                                }
                                else if (lambdaBlock.LineStartIndex == token.SpanStart)
                                {
                                    ReportDiagnostic();
                                    break;
                                }

                                return;
                            }
                        }

                        if (lines == null)
                        {
                            lines = first.SyntaxTree.GetText().Lines;
                        }

                        int lineIndex = lines.IndexOf(span.Start);
                        if (lineIndex < lines.Count - 1)
                        {
                            int lineStartIndex = lines[lineIndex + 1].Start;

                            if (first.Span.Contains(lineStartIndex))
                            {
                                SyntaxToken token = first.FindToken(lineStartIndex);

                                if (!token.IsKind(SyntaxKind.None))
                                {
                                    SyntaxTriviaList leading = token.LeadingTrivia;

                                    if (leading.Any())
                                    {
                                        if (leading.FullSpan.Contains(lineStartIndex))
                                        {
                                            SyntaxTrivia trivia = leading.Last();

                                            if (trivia.IsWhitespaceTrivia() &&
                                                trivia.SpanStart == lineStartIndex &&
                                                trivia.Span.Length != indentationLength)
                                            {
                                                ReportDiagnostic();
                                                break;
                                            }
                                        }
                                    }
                                    else if (lineStartIndex == token.SpanStart)
                                    {
                                        ReportDiagnostic();
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            void ReportDiagnostic()
            {
                DiagnosticHelpers.ReportDiagnostic(
                    context,
                    DiagnosticDescriptors.FixFormattingOfList,
                    Location.Create(first.SyntaxTree, nodes.Span),
                    GetTitle());
            }
        public static async Task ComputeRefactoringsAsync(RefactoringContext context, InvocationExpressionSyntax invocationExpression)
        {
            if (context.IsAnyRefactoringEnabled(
                    RefactoringIdentifiers.UseElementAccessInsteadOfEnumerableMethod,
                    RefactoringIdentifiers.ReplaceAnyWithAllOrAllWithAny,
                    RefactoringIdentifiers.CallExtensionMethodAsInstanceMethod,
                    RefactoringIdentifiers.CallIndexOfInsteadOfContains))
            {
                ExpressionSyntax expression = invocationExpression.Expression;

                if (expression != null &&
                    invocationExpression.ArgumentList != null)
                {
                    if (expression.IsKind(SyntaxKind.SimpleMemberAccessExpression) &&
                        ((MemberAccessExpressionSyntax)expression).Name?.Span.Contains(context.Span) == true)
                    {
                        if (context.IsRefactoringEnabled(RefactoringIdentifiers.UseElementAccessInsteadOfEnumerableMethod))
                        {
                            await UseElementAccessRefactoring.ComputeRefactoringsAsync(context, invocationExpression).ConfigureAwait(false);
                        }

                        if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceAnyWithAllOrAllWithAny))
                        {
                            await ReplaceAnyWithAllOrAllWithAnyRefactoring.ComputeRefactoringAsync(context, invocationExpression).ConfigureAwait(false);
                        }

                        if (context.IsRefactoringEnabled(RefactoringIdentifiers.CallIndexOfInsteadOfContains))
                        {
                            await CallIndexOfInsteadOfContainsRefactoring.ComputeRefactoringAsync(context, invocationExpression).ConfigureAwait(false);
                        }
                    }

                    if (context.IsRefactoringEnabled(RefactoringIdentifiers.CallExtensionMethodAsInstanceMethod))
                    {
                        SyntaxNodeOrToken nodeOrToken = CallExtensionMethodAsInstanceMethodAnalysis.GetNodeOrToken(expression);

                        if (nodeOrToken.Span.Contains(context.Span))
                        {
                            SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                            CallExtensionMethodAsInstanceMethodAnalysisResult analysis = CallExtensionMethodAsInstanceMethodAnalysis.Analyze(invocationExpression, semanticModel, allowAnyExpression: true, cancellationToken: context.CancellationToken);

                            if (analysis.Success)
                            {
                                context.RegisterRefactoring(
                                    CallExtensionMethodAsInstanceMethodRefactoring.Title,
                                    cancellationToken =>
                                {
                                    return(context.Document.ReplaceNodeAsync(
                                               analysis.InvocationExpression,
                                               analysis.NewInvocationExpression,
                                               cancellationToken));
                                },
                                    RefactoringIdentifiers.CallExtensionMethodAsInstanceMethod);
                            }
                        }
                    }
                }
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceStringFormatWithInterpolatedString) &&
                context.SupportsCSharp6)
            {
                await ReplaceStringFormatWithInterpolatedStringRefactoring.ComputeRefactoringsAsync(context, invocationExpression).ConfigureAwait(false);
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.UseBitwiseOperationInsteadOfCallingHasFlag))
            {
                SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

                if (UseBitwiseOperationInsteadOfCallingHasFlagAnalysis.IsFixable(invocationExpression, semanticModel, context.CancellationToken))
                {
                    context.RegisterRefactoring(
                        UseBitwiseOperationInsteadOfCallingHasFlagRefactoring.Title,
                        cancellationToken =>
                    {
                        return(UseBitwiseOperationInsteadOfCallingHasFlagRefactoring.RefactorAsync(
                                   context.Document,
                                   invocationExpression,
                                   cancellationToken));
                    },
                        RefactoringIdentifiers.UseBitwiseOperationInsteadOfCallingHasFlag);
                }
            }

            if (context.IsRefactoringEnabled(RefactoringIdentifiers.InlineMethod))
            {
                await InlineMethodRefactoring.ComputeRefactoringsAsync(context, invocationExpression).ConfigureAwait(false);
            }
        }
 public void Add(SyntaxNodeOrToken item)
 {
     this.Add((Syntax.InternalSyntax.CSharpSyntaxNode)item.UnderlyingNode);
 }
Exemplo n.º 39
0
            private IEnumerable <ISymbol> GetSymbolsInNewSolution(Document newDocument, SemanticModel newDocumentSemanticModel, RenameActionAnnotation conflictAnnotation, SyntaxNodeOrToken tokenOrNode)
            {
                IEnumerable <ISymbol> newReferencedSymbols = RenameUtilities.GetSymbolsTouchingPosition(tokenOrNode.Span.Start, newDocumentSemanticModel, newDocument.Project.Solution.Workspace, _cancellationToken);

                if (conflictAnnotation.IsInvocationExpression)
                {
                    IEnumerable <ISymbol> invocationReferencedSymbols = null;
                    if (tokenOrNode.IsNode)
                    {
                        invocationReferencedSymbols = SymbolsForEnclosingInvocationExpressionWorker((SyntaxNode)tokenOrNode, newDocumentSemanticModel, _cancellationToken);
                    }

                    if (invocationReferencedSymbols != null)
                    {
                        newReferencedSymbols = invocationReferencedSymbols;
                    }
                }

                // if there are more than one symbol, then remove the alias symbols.
                // When using (not declaring) an alias, the alias symbol and the target symbol are returned
                // by GetSymbolsTouchingPosition
                if (newReferencedSymbols.Skip(1).Any())
                {
                    newReferencedSymbols = newReferencedSymbols.Where(a => a.Kind != SymbolKind.Alias);
                }

                return(newReferencedSymbols);
            }
Exemplo n.º 40
0
 public static string GetKind(this SyntaxNodeOrToken n)
 {
     return(KindProvider.Kind(n));
 }
Exemplo n.º 41
0
 protected abstract SyntaxNode GetInnermostNamespaceScope(SyntaxNodeOrToken node);
Exemplo n.º 42
0
 public IEnumerable <TSpecificAnnotation> GetAnnotations <TSpecificAnnotation>(SyntaxNodeOrToken nodeOrToken) where TSpecificAnnotation : TAnnotation
 {
     return(this.GetAnnotations(nodeOrToken).OfType <TSpecificAnnotation>());
 }
Exemplo n.º 43
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 dependency 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.Kind()))
                {
                    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(_newDirectives.IncrementallyEquivalent(_oldDirectives));
            }
Exemplo n.º 44
0
 public NodeOrTokenToReduce(SyntaxNodeOrToken nodeOrToken, bool simplifyAllDescendants, SyntaxNodeOrToken originalNodeOrToken, bool canBeSpeculated = true)
 {
     this.NodeOrToken            = nodeOrToken;
     this.SimplifyAllDescendants = simplifyAllDescendants;
     this.OriginalNodeOrToken    = originalNodeOrToken;
     this.CanBeSpeculated        = canBeSpeculated;
 }
Exemplo n.º 45
0
 /// <summary>
 /// Create the Edit representing the deletion of all trivia between left and right.
 /// </summary>
 public static Edit DeleteBetween(SyntaxNodeOrToken left, SyntaxNodeOrToken right)
 => UpdateBetween(left, default, default(SyntaxTriviaList), right);
Exemplo n.º 46
0
        protected override SyntaxNode GetInnermostNamespaceScope(SyntaxNodeOrToken nodeOrToken)
        {
            var node = nodeOrToken.IsNode ? nodeOrToken.AsNode() : nodeOrToken.Parent;

            return(node.GetAncestorOrThis <NamespaceDeclarationSyntax>() ?? (SyntaxNode)node.GetAncestorOrThis <CompilationUnitSyntax>());
        }
Exemplo n.º 47
0
        internal static List <TextChange> GetFixListChanges <TNode>(
            SyntaxNode containingNode,
            SyntaxNodeOrToken openNodeOrToken,
            IReadOnlyList <TNode> nodes,
            ListFixMode fixMode = ListFixMode.Fix,
            CancellationToken cancellationToken = default) where TNode : SyntaxNode
        {
            IndentationAnalysis indentationAnalysis = AnalyzeIndentation(containingNode, cancellationToken);

            string increasedIndentation = indentationAnalysis.GetIncreasedIndentation();

            bool isSingleLine;
            SeparatedSyntaxList <TNode> separatedList = default;

            if (nodes is SyntaxList <TNode> list)
            {
                isSingleLine = list.IsSingleLine(includeExteriorTrivia: false, cancellationToken: cancellationToken);
            }
            else
            {
                separatedList = (SeparatedSyntaxList <TNode>)nodes;

                isSingleLine = separatedList.IsSingleLine(
                    includeExteriorTrivia: false,
                    cancellationToken: cancellationToken);
            }

            if (isSingleLine &&
                fixMode == ListFixMode.Fix)
            {
                TNode node = nodes[0];

                SyntaxTriviaList leading = node.GetLeadingTrivia();

                TextSpan span = (leading.Any() && leading.Last().IsWhitespaceTrivia())
                    ? leading.Last().Span
                    : new TextSpan(node.SpanStart, 0);

                return(new List <TextChange>()
                {
                    new TextChange(span, increasedIndentation)
                });
            }

            var textChanges              = new List <TextChange>();
            TextLineCollection lines     = null;
            string             endOfLine = DetermineEndOfLine(containingNode).ToString();

            for (int i = 0; i < nodes.Count; i++)
            {
                SyntaxToken token;
                if (i == 0)
                {
                    token = (openNodeOrToken.IsNode)
                        ? openNodeOrToken.AsNode().GetLastToken()
                        : openNodeOrToken.AsToken();
                }
                else
                {
                    token = (list == default)
                        ? separatedList.GetSeparator(i - 1)
                        : list[i - 1].GetLastToken();
                }

                SyntaxTriviaList trailing = token.TrailingTrivia;
                TNode            node     = nodes[i];
                var indentationAdded      = false;

                if (IsOptionalWhitespaceThenOptionalSingleLineCommentThenEndOfLineTrivia(trailing))
                {
                    SyntaxTrivia last = node.GetLeadingTrivia().LastOrDefault();

                    if (last.IsWhitespaceTrivia())
                    {
                        if (last.Span.Length == increasedIndentation.Length)
                        {
                            continue;
                        }

                        textChanges.Add(last.Span, increasedIndentation);
                    }
                    else
                    {
                        textChanges.Add(new TextSpan(node.SpanStart, 0), increasedIndentation);
                    }

                    indentationAdded = true;
                }
                else
                {
                    if (nodes.Count == 1 &&
                        node is ArgumentSyntax argument)
                    {
                        LambdaBlock lambdaBlock = GetLambdaBlock(argument, lines ??= argument.SyntaxTree.GetText().Lines);

                        if (lambdaBlock.Block != null)
                        {
                            increasedIndentation = indentationAnalysis.Indentation.ToString();
                        }
                    }

                    if ((nodes.Count > 1 || fixMode == ListFixMode.Wrap) &&
                        ShouldWrapAndIndent(containingNode, i))
                    {
                        textChanges.Add(
                            (trailing.Any() && trailing.Last().IsWhitespaceTrivia())
                                ? trailing.Last().Span
                                : new TextSpan(token.FullSpan.End, 0),
                            endOfLine);

                        textChanges.Add(new TextSpan(node.FullSpan.Start, 0), increasedIndentation);

                        indentationAdded = true;
                    }
                }

                ImmutableArray <IndentationInfo> indentations = FindIndentations(node, node.Span).ToImmutableArray();

                if (!indentations.Any())
                {
                    continue;
                }

                LambdaBlock lambdaBlock2 = GetLambdaBlock(node, lines ??= node.SyntaxTree.GetText().Lines);

                bool isLambdaBlockWithOpenBraceAtEndOfLine = lambdaBlock2.Token == indentations.Last().Token;

                int baseIndentationLength = (isLambdaBlockWithOpenBraceAtEndOfLine)
                    ? indentations.Last().Span.Length
                    : indentations[0].Span.Length;

                for (int j = indentations.Length - 1; j >= 0; j--)
                {
                    IndentationInfo indentationInfo = indentations[j];

                    if (indentationAdded &&
                        node is ArgumentSyntax argument &&
                        (argument.Expression as AnonymousFunctionExpressionSyntax)?.Block != null)
                    {
                        indentationAdded = false;
                    }

                    string replacement = increasedIndentation;

                    if (indentationAdded)
                    {
                        replacement += indentationAnalysis.GetSingleIndentation();
                    }

                    if ((j > 0 || isLambdaBlockWithOpenBraceAtEndOfLine) &&
                        indentationInfo.Span.Length > baseIndentationLength)
                    {
                        replacement += indentationInfo.ToString().Substring(baseIndentationLength);
                    }

                    if (indentationInfo.Span.Length != replacement.Length)
                    {
                        textChanges.Add(indentationInfo.Span, replacement);
                    }
                }
            }

            FormattingVerifier.VerifyChangedSpansAreWhitespace(containingNode, textChanges);

            return(textChanges);
        }
Exemplo n.º 48
0
 public static Edit UpdateBetween(
     SyntaxNodeOrToken left, SyntaxTriviaList leftTrailingTrivia,
     SyntaxTrivia rightLeadingTrivia, SyntaxNodeOrToken right)
 {
     return(UpdateBetween(left, leftTrailingTrivia, new SyntaxTriviaList(rightLeadingTrivia), right));
 }
Exemplo n.º 49
0
 private static bool IsNonZeroWidthOrIsEndOfFile(SyntaxNodeOrToken token)
 {
     return(token.Kind() == SyntaxKind.EndOfFileToken || token.FullWidth != 0);
 }
 /// <summary>
 /// Finds node enclosing current from navigation point of view (that is, some immediate ancestors
 /// may be skipped during this process).
 /// </summary>
 private SyntaxNodeOrToken? GetEnclosingNode(SyntaxNodeOrToken node)
 {
     var parent = SkipSameSpanParents(node).Parent;
     if (parent != null)
     {
         return parent;
     }
     else
     {
         return null;
     }
 }
Exemplo n.º 51
0
 public bool HasAnnotations <TSpecificAnnotation>(SyntaxNodeOrToken nodeOrToken) where TSpecificAnnotation : TAnnotation
 {
     return(this.GetAnnotations(nodeOrToken).OfType <TSpecificAnnotation>().Any());
 }
Exemplo n.º 52
0
 public SyntaxNodeOrToken WithAdditionalAnnotations(SyntaxNodeOrToken nodeOrToken, params TAnnotation[] annotations)
 {
     return(nodeOrToken.WithAdditionalAnnotations(this.GetOrCreateRealAnnotations(annotations).ToArray()));
 }
Exemplo n.º 53
0
 public IEnumerable <TAnnotation> GetAnnotations(SyntaxNodeOrToken nodeOrToken)
 {
     return(GetAnnotations(nodeOrToken.GetAnnotations(_annotationKind)));
 }
Exemplo n.º 54
0
        public void Write(SyntaxNodeOrToken syntax, String str)
        {
            var pos = _jsOutput.Write(str);

            this.WriteSourceMap(syntax, pos, str);
        }
Exemplo n.º 55
0
 private static void Print(SyntaxNodeOrToken node)
 {
     Debug.WriteLine("{0}(SyntaxKind.{1});", node.IsMissing ? "M" : "N", node.Kind());
 }
Exemplo n.º 56
0
 public SyntaxNodeOrToken WithoutAnnotations(SyntaxNodeOrToken nodeOrToken, params TAnnotation[] annotations)
 {
     return(nodeOrToken.WithoutAnnotations(GetRealAnnotations(annotations).ToArray()));
 }
            /// <summary>
            /// Returns first ancestor of the node which has a span wider than node's span.
            /// If none exist, returns the last available ancestor.
            /// </summary>
            private SyntaxNodeOrToken SkipSameSpanParents(SyntaxNodeOrToken node)
            {
                while (node.Parent != null && node.Parent.Span == node.Span)
                {
                    node = node.Parent;
                }

                return node;
            }
        private void TreeToString(SyntaxNodeOrToken syntaxNodeOrToken, string indent, CodeActionValidationMode validationMode, StringBuilder result)
        {
            if (syntaxNodeOrToken.IsNode)
            {
                result.AppendLine($"{indent}Node({Kind(syntaxNodeOrToken.RawKind)}):");

                var childIndent = indent + "  ";
                foreach (var child in syntaxNodeOrToken.ChildNodesAndTokens())
                {
                    TreeToString(child, childIndent, validationMode, result);
                }
            }
            else
            {
                var syntaxToken = syntaxNodeOrToken.AsToken();
                result.AppendLine($"{indent}Token({Kind(syntaxToken.RawKind)}): {Escape(syntaxToken.Text)}");

                if (validationMode == CodeActionValidationMode.Full)
                {
                    var childIndent = indent + "  ";
                    foreach (var trivia in syntaxToken.LeadingTrivia)
                    {
                        if (trivia.HasStructure)
                        {
                            result.AppendLine($"{childIndent}Leading({Kind(trivia.RawKind)}):");
                            TreeToString(trivia.GetStructure(), childIndent + "  ", validationMode, result);
                        }
                        else
                        {
                            result.AppendLine($"{childIndent}Leading({Kind(trivia.RawKind)}): {Escape(trivia.ToString())}");
                        }
                    }

                    foreach (var trivia in syntaxToken.TrailingTrivia)
                    {
                        if (trivia.HasStructure)
                        {
                            result.AppendLine($"{childIndent}Trailing({Kind(trivia.RawKind)}):");
                            TreeToString(trivia.GetStructure(), childIndent + "  ", validationMode, result);
                        }
                        else
                        {
                            result.AppendLine($"{childIndent}Trailing({Kind(trivia.RawKind)}): {Escape(trivia.ToString())}");
                        }
                    }
                }
            }

            // Local functions
            string Escape(string text)
            {
                return(text
                       .Replace("\\", "\\\\")
                       .Replace("\t", "\\t")
                       .Replace("\r", "\\r")
                       .Replace("\n", "\\n"));
            }

            string Kind(int syntaxKind)
            {
                if (SyntaxKindType.GetTypeInfo()?.IsEnum ?? false)
                {
                    return(Enum.Format(SyntaxKindType, (ushort)syntaxKind, "G"));
                }
                else
                {
                    return(syntaxKind.ToString());
                }
            }
        }
Exemplo n.º 59
0
 public override int GetHashCode()
 {
     return(SyntaxNodeOrToken.GetHashCode());
 }
Exemplo n.º 60
0
 public bool HasAnnotation(SyntaxNodeOrToken nodeOrToken, TAnnotation annotation)
 {
     return(nodeOrToken.HasAnnotation(this.GetRealAnnotation(annotation)));
 }