private static SyntaxNode GetContainingMember(SyntaxNode oldNode)
        {
            foreach (var node in oldNode.Ancestors())
            {
                switch (node.Kind())
                {
                    case SyntaxKind.ParenthesizedLambdaExpression:
                    case SyntaxKind.SimpleLambdaExpression:
                    case SyntaxKind.AnonymousMethodExpression:
                        if ((node as AnonymousFunctionExpressionSyntax)?.AsyncKeyword.Kind() != SyntaxKind.AsyncKeyword)
                        {
                            return node;
                        }
                        break;
                    case SyntaxKind.MethodDeclaration:
                        if ((node as MethodDeclarationSyntax)?.Modifiers.Any(SyntaxKind.AsyncKeyword) == false)
                        {
                            return node;
                        }
                        break;
                    default:
                        continue;
                }
            }

            return null;
        }
 private static SyntaxToken GetIdentifierOrKeywordAtPosition(SyntaxNode root, SourceLocation position)
 {
     var syntaxToken = root.FindTokenOnLeft(position);
     return syntaxToken.Kind.IsIdentifierOrKeyword() && syntaxToken.SourceRange.ContainsOrTouches(position)
         ? syntaxToken
         : null;
 }
 public PathSyntaxReference(SyntaxNode node)
 {
     _tree = node.SyntaxTree;
     _kind = node.Kind();
     _textSpan = node.Span;
     _pathFromRoot = ComputePathFromRoot(node);
 }
        private void ReplayVarUsage(LocalFunctionSymbol localFunc,
                                    SyntaxNode syntax,
                                    bool isWrite)
        {
            LocalFuncUsages usages = GetOrCreateLocalFuncUsages(localFunc);
            var state = isWrite ? usages.WrittenVars : usages.ReadVars;

            // Start at slot 1 (slot 0 just indicates reachability)
            for (int slot = 1; slot < state.Capacity; slot++)
            {
                if (state[slot])
                {
                    if (isWrite)
                    {
                        SetSlotAssigned(slot);
                    }
                    else
                    {
                        var symbol = variableBySlot[slot].Symbol;
                        CheckAssigned(symbol, syntax, slot);
                    }
                }
            }

            usages.LocalFuncVisited = true;
        }
                private ImmutableArray<int> ComputePathFromRoot(SyntaxNode node)
                {
                    var path = new List<int>();
                    var root = _tree.GetRoot();

                    while (node != root)
                    {
                        for (; node.Parent != null; node = node.Parent)
                        {
                            var index = GetChildIndex(node);
                            path.Add(index);
                        }

                        // if we were part of structure trivia, continue searching until we get to the true root
                        if (node.IsStructuredTrivia)
                        {
                            var trivia = node.ParentTrivia;
                            var triviaIndex = GetTriviaIndex(trivia);
                            path.Add(triviaIndex);
                            var tokenIndex = GetChildIndex(trivia.Token);
                            path.Add(tokenIndex);
                            node = trivia.Token.Parent;
                            continue;
                        }
                        else if (node != root)
                        {
                            throw new InvalidOperationException(CSharpWorkspaceResources.Node_does_not_descend_from_root);
                        }
                    }

                    path.Reverse();
                    return path.ToImmutableArray();
                }
 public void AnalyzeCodeBlock(SyntaxNode codeBlock, ISymbol ownerSymbol, SemanticModel semanticModel, Action<Diagnostic> addDiagnostic, AnalyzerOptions options, CancellationToken cancellationToken)
 {
     if (IsEmptyFinalizer(codeBlock, semanticModel))
     {
         addDiagnostic(ownerSymbol.CreateDiagnostic(Rule));
     }
 }
Example #7
0
        public static SyntaxNode FindPartner(SyntaxNode leftRoot, SyntaxNode rightRoot, SyntaxNode leftNode)
        {
            // Finding a partner of a zero-width node is complicated and not supported atm:
            Debug.Assert(leftNode.FullSpan.Length > 0);
            Debug.Assert(leftNode.SyntaxTree == leftRoot.SyntaxTree);

            SyntaxNode originalLeftNode = leftNode;
            int leftPosition = leftNode.SpanStart;
            leftNode = leftRoot;
            SyntaxNode rightNode = rightRoot;

            while (leftNode != originalLeftNode)
            {
                Debug.Assert(leftNode.RawKind == rightNode.RawKind);
                var leftChild = leftNode.ChildThatContainsPosition(leftPosition, out var childIndex);

                // Can only happen when searching for zero-width node.
                Debug.Assert(!leftChild.IsToken);

                rightNode = rightNode.ChildNodesAndTokens()[childIndex].AsNode();
                leftNode = leftChild.AsNode();
            }

            return rightNode;
        }
        private string GetOutsideTypeQualifiedName(SyntaxNode node)
        {
            // Get the name space name enclosing this node.
            string namespaceName = node.AncestorsAndSelf().
                // ancestors whose kind is name space node.
                Where(n => n.Kind == SyntaxKind.NamespaceDeclaration).
                // conver to the syntax and get the name.
                Select(n => (NamespaceDeclarationSyntax)n).First().Name.PlainName;

            // Get the class name enclosing this node.
            var classesNames = node.AncestorsAndSelf().
                // ancestors whose kind is class node.
                Where(n => n.Kind == SyntaxKind.ClassDeclaration).
                // convert each one to the kind class node syntax.
                Select(n => (ClassDeclarationSyntax)n).
                // order all the class decs by their length, in decending order.
                OrderByDescending(n => n.Span.Length).
                // select their names.
                Select(n => n.Identifier.ValueText);

            // Combine all the names to get the scope string.
            var qualifiedName = namespaceName + "." + StringUtil.ConcatenateAll(".", classesNames);
            logger.Info(qualifiedName);
            return qualifiedName;
        }
 public CommentsAnalyzerTests()
 {
     this.code = FileUtil.ReadAllText(path);
     this.root = ASTUtil.GetSyntaxTreeFromSource(code).GetRoot();
     this.retriever = RetrieverFactory.GetCommentsRetriever();
     this.logger = NLoggerUtil.GetNLogger(typeof (CommentsAnalyzerTests));
 }
        private void AddEdits(
            SyntaxNode root, 
            SyntaxEditor editor, 
            Diagnostic diagnostic, 
            CancellationToken cancellationToken)
        {
            var localDeclarationLocation = diagnostic.AdditionalLocations[0];
            var ifStatementLocation = diagnostic.AdditionalLocations[1];
            var conditionLocation = diagnostic.AdditionalLocations[2];
            var asExpressionLocation = diagnostic.AdditionalLocations[3];

            var localDeclaration = (LocalDeclarationStatementSyntax)localDeclarationLocation.FindNode(cancellationToken);
            var ifStatement = (IfStatementSyntax)ifStatementLocation.FindNode(cancellationToken);
            var condition = (BinaryExpressionSyntax)conditionLocation.FindNode(cancellationToken);
            var asExpression = (BinaryExpressionSyntax)asExpressionLocation.FindNode(cancellationToken);

            var updatedCondition = SyntaxFactory.IsPatternExpression(
                asExpression.Left, SyntaxFactory.DeclarationPattern(
                    ((TypeSyntax)asExpression.Right).WithoutTrivia(),
                    localDeclaration.Declaration.Variables[0].Identifier.WithoutTrivia()));

            var trivia = localDeclaration.GetLeadingTrivia().Concat(localDeclaration.GetTrailingTrivia())
                                         .Where(t => t.IsSingleOrMultiLineComment())
                                         .SelectMany(t => ImmutableArray.Create(t, SyntaxFactory.ElasticCarriageReturnLineFeed))
                                         .ToImmutableArray();

            var updatedIfStatement = ifStatement.ReplaceNode(condition, updatedCondition)
                                                .WithPrependedLeadingTrivia(trivia)
                                                .WithAdditionalAnnotations(Formatter.Annotation);

            editor.RemoveNode(localDeclaration);
            editor.ReplaceNode(ifStatement, updatedIfStatement);
        }
        public static bool AreSemanticallyEquivalent(
            SemanticModel semanticModel1,
            SemanticModel semanticModel2,
            SyntaxNode node1,
            SyntaxNode node2,
            Func<SyntaxNode, bool> predicate = null)
        {
            // First check for syntactic equivalency.  If two nodes aren't structurally equivalent,
            // then they're not semantically equivalent.
            if (node1 == null && node2 == null)
            {
                return true;
            }

            if (node1 == null || node2 == null)
            {
                return false;
            }

            if (!node1.IsEquivalentTo(node2, topLevel: false))
            {
                return false;
            }

            // From this point on we can assume the tree structure is the same.  So no need to check
            // kinds, child counts or token contents.
            return AreSemanticallyEquivalentWorker(
                semanticModel1, semanticModel2, node1, node2, predicate);
        }
        public override SignatureHelpState GetCurrentArgumentState(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, TextSpan currentSpan, CancellationToken cancellationToken)
        {
            if (GetOuterMostTupleExpressionInSpan(root, position, syntaxFacts, currentSpan, cancellationToken, out var expression))
            {
                return CommonSignatureHelpUtilities.GetSignatureHelpState(expression, position,
                   getOpenToken: s_getOpenToken,
                   getCloseToken: s_getCloseToken,
                   getArgumentsWithSeparators: s_getArgumentsWithSeparators,
                   getArgumentNames: s_getArgumentNames);
            }

            if (GetOuterMostParenthesizedExpressionInSpan(root, position, syntaxFacts, currentSpan, cancellationToken, out var parenthesizedExpression))
            {
                if (currentSpan.Start == parenthesizedExpression.SpanStart)
                {
                    return new SignatureHelpState(
                        argumentIndex: 0,
                        argumentCount: 0,
                        argumentName: string.Empty,
                        argumentNames: null);
                }
            }

            return null;
        }
Example #13
0
 private BoundNode BindGlobalDeclaration(SyntaxNode declaration, Symbol parent)
 {
     switch (declaration.Kind)
     {
         case SyntaxKind.VariableDeclarationStatement:
             return BindVariableDeclarationStatement((VariableDeclarationStatementSyntax) declaration, parent);
         case SyntaxKind.FunctionDeclaration:
             return BindFunctionDeclaration((FunctionDeclarationSyntax) declaration, parent);
         case SyntaxKind.FunctionDefinition:
             return BindFunctionDefinition((FunctionDefinitionSyntax) declaration, parent);
         case SyntaxKind.ConstantBufferDeclaration:
             return BindConstantBufferDeclaration((ConstantBufferSyntax) declaration);
         case SyntaxKind.TypeDeclarationStatement:
             return BindTypeDeclaration((TypeDeclarationStatementSyntax) declaration, parent);
         case SyntaxKind.Namespace:
             return BindNamespace((NamespaceSyntax) declaration);
         case SyntaxKind.TechniqueDeclaration:
             return BindTechniqueDeclaration((TechniqueSyntax) declaration);
         case SyntaxKind.TypedefStatement:
             return BindTypedefStatement((TypedefStatementSyntax) declaration);
         case SyntaxKind.EmptyStatement:
             return BindEmptyStatement((EmptyStatementSyntax) declaration);
         default:
             throw new ArgumentOutOfRangeException(declaration.Kind.ToString());
     }
 }
Example #14
0
 public override void DefaultVisit(SyntaxNode node)
 {
     foreach (var child in node.ChildNodes())
     {
         child.Accept(this);
     }
 }
Example #15
0
 public override void DefaultVisit(SyntaxNode node)
 {
     foreach (var child in node.ChildNodes())
     {
         Visit(child);
     }
 }
Example #16
0
        public ICodeBlockEndedAnalyzer OnCodeBlockStarted(SyntaxNode codeBlock, ISymbol ownerSymbol, SemanticModel semanticModel, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken)
        {
            var methodSymbol = ownerSymbol as IMethodSymbol;

            if (methodSymbol == null ||
                methodSymbol.ReturnsVoid ||
                methodSymbol.ReturnType.Kind == SymbolKind.ArrayType ||
                methodSymbol.Parameters.Length > 0 ||
                !(methodSymbol.DeclaredAccessibility == Accessibility.Public || methodSymbol.DeclaredAccessibility == Accessibility.Protected) ||
                methodSymbol.IsAccessorMethod() ||
                !IsPropertyLikeName(methodSymbol.Name))
            {
                return null;
            }

            // Fxcop has a few additional checks to reduce the noise for this diagnostic:
            // Ensure that the method is non-generic, non-virtual/override, has no overloads and doesn't have special names: 'GetHashCode' or 'GetEnumerator'.
            // Also avoid generating this diagnostic if the method body has any invocation expressions.
            if (methodSymbol.IsGenericMethod ||
                methodSymbol.IsVirtual ||
                methodSymbol.IsOverride ||
                methodSymbol.ContainingType.GetMembers(methodSymbol.Name).Length > 1 ||
                methodSymbol.Name == GetHashCodeName ||
                methodSymbol.Name == GetEnumeratorName)
            {
                return null;
            }

            return GetCodeBlockEndedAnalyzer();
        }
        public override void AddIndentBlockOperations(List<IndentBlockOperation> list, SyntaxNode node, OptionSet optionSet, NextAction<IndentBlockOperation> nextOperation)
        {
            nextOperation.Invoke(list);

            var queryExpression = node as QueryExpressionSyntax;
            if (queryExpression != null)
            {
                var firstToken = queryExpression.FromClause.Expression.GetFirstToken(includeZeroWidth: true);
                var lastToken = queryExpression.FromClause.Expression.GetLastToken(includeZeroWidth: true);
                AddIndentBlockOperation(list, queryExpression.FromClause.FromKeyword, firstToken, lastToken);

                for (int i = 0; i < queryExpression.Body.Clauses.Count; i++)
                {
                    // if it is nested query expression
                    var fromClause = queryExpression.Body.Clauses[i] as FromClauseSyntax;
                    if (fromClause != null)
                    {
                        firstToken = fromClause.Expression.GetFirstToken(includeZeroWidth: true);
                        lastToken = fromClause.Expression.GetLastToken(includeZeroWidth: true);
                        AddIndentBlockOperation(list, fromClause.FromKeyword, firstToken, lastToken);
                    }
                }

                // set alignment line for query expression
                var baseToken = queryExpression.GetFirstToken(includeZeroWidth: true);
                var endToken = queryExpression.GetLastToken(includeZeroWidth: true);
                if (!baseToken.IsMissing && !baseToken.Equals(endToken))
                {
                    var startToken = baseToken.GetNextToken(includeZeroWidth: true);
                    SetAlignmentBlockOperation(list, baseToken, startToken, endToken);
                }
            }
        }
 private void AddFix(string codeFixTitle, CodeFixContext context, SyntaxNode root, SyntaxNode classDecl, SyntaxGenerator generator, params string[] languages)
 {
     var fix = new MyCodeAction(
         codeFixTitle,
         c => GetFix(context.Document, root, classDecl, generator, languages));
     context.RegisterCodeFix(fix, context.Diagnostics);
 }
        private IEnumerable<SyntaxNode> EnumerateNonRootChildren(SyntaxNode node)
        {
            foreach (var child in node.ChildNodes())
            {
                if (LambdaUtilities.IsLambdaBodyStatementOrExpression(child))
                {
                    continue;
                }

                if (HasLabel(child))
                {
                    yield return child;
                }
                else
                {
                    foreach (var descendant in child.DescendantNodes(DescendIntoChildren))
                    {
                        if (HasLabel(descendant))
                        {
                            yield return descendant;
                        }
                    }
                }
            }
        }
 internal CorrectAllSignaturesInSolution(ISolution solution, SyntaxNode declaration,
                                         IEnumerable<Tuple<int, int>> mappings)
 {
     this.solution = solution;
     this.declaration = declaration;
     this.mappings = mappings;
 }
 private Task<Document> AddNonSerializedAttribute(Document document, SemanticModel model, SyntaxNode root, SyntaxNode fieldNode, SyntaxGenerator generator)
 {
     var attr = generator.Attribute(generator.TypeExpression(WellKnownTypes.NonSerializedAttribute(model.Compilation)));
     var newNode = generator.AddAttributes(fieldNode, attr);
     var newDocument = document.WithSyntaxRoot(root.ReplaceNode(fieldNode, newNode));
     return Task.FromResult(newDocument);
 }
 internal StatementSyntaxComparer(SyntaxNode oldRootChild, SyntaxNode newRootChild)
 {
     _oldRootChild = oldRootChild;
     _newRootChild = newRootChild;
     _oldRoot = oldRootChild.Parent;
     _newRoot = newRootChild.Parent;
 }
Example #23
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="syntaxNode">SyntaxNode</param>
 /// <param name="node">IControlFlowNode</param>
 /// <param name="summary">MethodSummary</param>
 private Statement(SyntaxNode syntaxNode, IControlFlowNode node,
     MethodSummary summary)
 {
     this.SyntaxNode = syntaxNode;
     this.ControlFlowNode = node;
     this.Summary = summary;
 }
 public void AddOrAccess(SyntaxNode instance, IWeakAction<SyntaxNode> evictor)
 {
     if (!trees.ContainsKey(instance))
     {
         trees[instance] = evictor;
     }
 }
 private State(SyntaxNode node, INamedTypeSymbol classType, INamedTypeSymbol abstractClassType, IList<Tuple<INamedTypeSymbol, IList<ISymbol>>> unimplementedMembers)
 {
     this.Location = node;
     this.ClassType = classType;
     this.AbstractClassType = abstractClassType;
     this.UnimplementedMembers = unimplementedMembers;
 }
        private async Task<Solution> RenameThenRemoveAsyncTokenAsync(Document document, SyntaxNode node, IMethodSymbol methodSymbol, CancellationToken cancellationToken)
        {
            var name = methodSymbol.Name;
            var newName = name.Substring(0, name.Length - AsyncSuffix.Length);
            var solution = document.Project.Solution;
            var options = solution.Workspace.Options;

            // Store the path to this node.  That way we can find it post rename.
            var syntaxPath = new SyntaxPath(node);

            // Rename the method to remove the 'Async' suffix, then remove the 'async' keyword.
            var newSolution = await Renamer.RenameSymbolAsync(solution, methodSymbol, newName, options, cancellationToken).ConfigureAwait(false);
            var newDocument = newSolution.GetDocument(document.Id);
            var newRoot = await newDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            SyntaxNode newNode;
            if (syntaxPath.TryResolve<SyntaxNode>(newRoot, out newNode))
            {
                var semanticModel = await newDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
                var newMethod = (IMethodSymbol)semanticModel.GetDeclaredSymbol(newNode, cancellationToken);
                return await RemoveAsyncTokenAsync(newDocument, newMethod, newNode, cancellationToken).ConfigureAwait(false);
            }

            return newSolution;
        }
            private SyntaxNode GetNewNode(Document document, SyntaxNode node, CancellationToken cancellationToken)
            {
                SyntaxNode newNode = null;

                var propertyStatement = node as PropertyDeclarationSyntax;
                if (propertyStatement != null)
                {
                    newNode = propertyStatement.AddModifiers(SyntaxFactory.Token(SyntaxKind.NewKeyword)) as SyntaxNode;
                }

                var methodStatement = node as MethodDeclarationSyntax;
                if (methodStatement != null)
                {
                    newNode = methodStatement.AddModifiers(SyntaxFactory.Token(SyntaxKind.NewKeyword));
                }

                var fieldDeclaration = node as FieldDeclarationSyntax;
                if (fieldDeclaration != null)
                {
                    newNode = fieldDeclaration.AddModifiers(SyntaxFactory.Token(SyntaxKind.NewKeyword));
                }

                //Make sure we preserve any trivia from the original node
                newNode = newNode.WithTriviaFrom(node);

                return newNode.WithAdditionalAnnotations(Formatter.Annotation);
            }
        internal override Task<IEnumerable<CodeAction>> GetFixesAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, CancellationToken cancellationToken)
        {
            var actions = ImmutableArray.CreateBuilder<CodeAction>();

            // Fix 1: Add a NonSerialized attribute to the field
            var fieldNode = GetFieldDeclarationNode(nodeToFix);
            if (fieldNode != null)
            {
                var generator = SyntaxGenerator.GetGenerator(document);
                var codeAction = new MyDocumentCodeAction(FxCopFixersResources.AddNonSerializedAttribute,
                                                          async ct => await AddNonSerializedAttribute(document, model, root, fieldNode, generator).ConfigureAwait(false));
                actions.Add(codeAction);

                // Fix 2: If the type of the field is defined in source, then add the serializable attribute to the type.
                var fieldSymbol = model.GetDeclaredSymbol(nodeToFix, cancellationToken) as IFieldSymbol;
                var type = fieldSymbol.Type;
                if (type.Locations.Any(l => l.IsInSource))
                {
                    var typeCodeAction = new MySolutionCodeAction(FxCopFixersResources.AddSerializableAttribute,
                                                                  async ct => await AddSerializableAttributeToType(document, model, generator, type, cancellationToken).ConfigureAwait(false));

                    actions.Add(typeCodeAction);
                }
            }

            return Task.FromResult<IEnumerable<CodeAction>>(actions.ToImmutable());
        }
 // This constructor can be used to have the span and associated node be arbitrarily different.
 public SourceLocationWithAssociatedNode(SyntaxTree syntaxTree, TextSpan span, SyntaxNode associatedNode, bool associateInParent)
     : base(syntaxTree, span)
 {
     Debug.Assert(associatedNode != null); //if it's null, construct a SourceLocation instead
     this.associatedNode = new WeakReference<SyntaxNode>(associatedNode);
     this.associateInParent = associateInParent;
 }
 public PathSyntaxReference(SyntaxNode node)
 {
     this.tree = node.SyntaxTree;
     this.kind = node.CSharpKind();
     this.textSpan = node.Span;
     this.pathFromRoot = ComputePathFromRoot(node);
 }
 protected abstract Task <SyntaxNode> ReplaceNodeAsync(SyntaxNode node, string containerName, CancellationToken cancellationToken);
 protected abstract (string description, bool hasExistingImport) GetDescription(Document document, INamespaceOrTypeSymbol symbol, SemanticModel semanticModel, SyntaxNode root, CancellationToken cancellationToken);
Example #33
0
 protected abstract TNode RewriteCore <TNode>(
     TNode node,
     SyntaxNode replacementNode,
     ISet <TExpressionSyntax> matches)
     where TNode : SyntaxNode;
 public static bool IsInstance(SyntaxNode node)
 {
     return(node != null && LightupHelpers.CanWrapNode(node, WrappedType));
 }
Example #35
0
 public void Replace(SyntaxNode oldNode, SyntaxNode newNode)
 {
     _replace[oldNode] = newNode;
 }
        private static SyntaxNode GetNegationOfBinaryExpression(
            SyntaxNode expressionNode,
            SyntaxGenerator generator,
            SemanticModel semanticModel,
            CancellationToken cancellationToken)
        {
            var syntaxFacts = generator.SyntaxFacts;

            syntaxFacts.GetPartsOfBinaryExpression(expressionNode, out var leftOperand, out var operatorToken, out var rightOperand);

            var binaryOperation = semanticModel.GetOperation(expressionNode, cancellationToken) as IBinaryOperation;

            if (binaryOperation == null)
            {
                // Apply the logical not operator if it is not a binary operation.
                return(generator.LogicalNotExpression(expressionNode));
            }

            if (!s_negatedBinaryMap.TryGetValue(binaryOperation.OperatorKind, out var negatedKind))
            {
                return(generator.LogicalNotExpression(expressionNode));
            }
            else
            {
                var negateOperands = false;
                switch (binaryOperation.OperatorKind)
                {
                case BinaryOperatorKind.Or:
                case BinaryOperatorKind.And:
                case BinaryOperatorKind.ConditionalAnd:
                case BinaryOperatorKind.ConditionalOr:
                    negateOperands = true;
                    break;
                }

                //Workaround for https://github.com/dotnet/roslyn/issues/23956
                //Issue to remove this when above is merged
                if (binaryOperation.OperatorKind == BinaryOperatorKind.Or && syntaxFacts.IsConditionalOr(expressionNode))
                {
                    negatedKind = BinaryOperatorKind.ConditionalAnd;
                }
                else if (binaryOperation.OperatorKind == BinaryOperatorKind.And && syntaxFacts.IsConditionalAnd(expressionNode))
                {
                    negatedKind = BinaryOperatorKind.ConditionalOr;
                }

                var newLeftOperand  = leftOperand;
                var newRightOperand = rightOperand;
                if (negateOperands)
                {
                    newLeftOperand  = generator.Negate(leftOperand, semanticModel, cancellationToken);
                    newRightOperand = generator.Negate(rightOperand, semanticModel, cancellationToken);
                }

                var newBinaryExpressionSyntax = NewBinaryOperation(binaryOperation, newLeftOperand, negatedKind, newRightOperand, generator, cancellationToken)
                                                .WithTriviaFrom(expressionNode);

                var newToken           = syntaxFacts.GetOperatorTokenOfBinaryExpression(newBinaryExpressionSyntax);
                var newTokenWithTrivia = newToken.WithTriviaFrom(operatorToken);
                return(newBinaryExpressionSyntax.ReplaceToken(newToken, newTokenWithTrivia));
            }
        }
        public static void ComputeRefactoring(RefactoringContext context, MemberDeclarationSyntax member)
        {
            SyntaxNode parent = member.Parent;

            if (parent?.IsKind(
                SyntaxKind.NamespaceDeclaration,
                SyntaxKind.ClassDeclaration,
                SyntaxKind.StructDeclaration,
                SyntaxKind.InterfaceDeclaration) == true)
            {
                var parentMember = (MemberDeclarationSyntax)parent;

                SyntaxList<MemberDeclarationSyntax> members = parentMember.GetMembers();

                if (members.Count > 1)
                {
                    int index = IndexOfMemberToSwap(member, members, context.Span);

                    if (index != -1)
                    {
                        SyntaxTree tree = member.SyntaxTree;

                        FileLinePositionSpan fileLinePositionSpan = tree.GetLineSpan(context.Span, context.CancellationToken);

                        int startLine = fileLinePositionSpan.StartLine();
                        int endLine = fileLinePositionSpan.EndLine();

                        if (startLine > tree.GetEndLine(members[index].TrimmedSpan(), context.CancellationToken)
                            && endLine < tree.GetStartLine(members[index + 1].TrimmedSpan(), context.CancellationToken))
                        {
                            if (context.IsRefactoringEnabled(RefactoringIdentifiers.RemoveMemberDeclarations))
                            {
                                context.RegisterRefactoring(
                                    "Remove members above",
                                    cancellationToken =>
                                    {
                                        return ReplaceMembersAsync(
                                            context.Document,
                                            parentMember,
                                            List(members.Skip(index + 1)),
                                            cancellationToken);
                                    });

                                context.RegisterRefactoring(
                                    "Remove members below",
                                    cancellationToken =>
                                    {
                                        return ReplaceMembersAsync(
                                            context.Document,
                                            parentMember,
                                            List(members.Take(index + 1)),
                                            cancellationToken);
                                    });
                            }

                            if (context.IsRefactoringEnabled(RefactoringIdentifiers.SwapMemberDeclarations))
                            {
                                context.RegisterRefactoring(
                                    "Swap members",
                                    cancellationToken =>
                                    {
                                        return RefactorAsync(
                                            context.Document,
                                            parentMember,
                                            members,
                                            index,
                                            cancellationToken);
                                    });
                            }
                        }
                    }
                }
            }
        }
 protected abstract Task <Document> AddImportAsync(SyntaxNode contextNode, IReadOnlyList <string> nameSpaceParts, Document document, bool specialCaseSystem, CancellationToken cancellationToken);
 protected abstract bool IsViableExtensionMethod(IMethodSymbol method, SyntaxNode expression, SemanticModel semanticModel, ISyntaxFacts syntaxFacts, CancellationToken cancellationToken);
 protected abstract bool IsAddMethodContext(SyntaxNode node, SemanticModel semanticModel);
 protected abstract ITypeSymbol GetDeconstructInfo(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken);
 protected abstract Task <Document> AddImportAsync(SyntaxNode contextNode, INamespaceOrTypeSymbol symbol, Document document, bool specialCaseSystem, CancellationToken cancellationToken);
 protected abstract bool CanAddImportForType(string diagnosticId, SyntaxNode node, out TSimpleNameSyntax nameNode);
 protected abstract ITypeSymbol GetQueryClauseInfo(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken);
 protected abstract bool CanAddImportForGetAsyncEnumerator(string diagnosticId, ISyntaxFacts syntaxFactsService, SyntaxNode node);
 protected abstract ISet <INamespaceSymbol> GetImportNamespacesInScope(SemanticModel semanticModel, SyntaxNode node, CancellationToken cancellationToken);
 protected abstract bool CanAddImportForMethod(string diagnosticId, ISyntaxFacts syntaxFacts, SyntaxNode node, out TSimpleNameSyntax nameNode);
 protected abstract bool CanAddImportForQuery(string diagnosticId, SyntaxNode node);
Example #49
0
 public override SyntaxTree WithRootAndOptions(SyntaxNode root, ParseOptions options)
 {
     throw new NotImplementedException();
 }
 protected abstract bool CanAddImportForDeconstruct(string diagnosticId, SyntaxNode node);
Example #51
0
        static IEnumerable <IClassificationType> GetClassificationType(SyntaxNode node, SemanticModel semanticModel)
        {
            node = node.Kind() == SyntaxKind.Argument ? (node as ArgumentSyntax).Expression : node;
            //System.Diagnostics.Debug.WriteLine(node.GetType().Name + node.Span.ToString());
            var symbol = semanticModel.GetSymbolInfo(node).Symbol;

            if (symbol == null)
            {
                symbol = semanticModel.GetDeclaredSymbol(node);
                if (symbol != null)
                {
                    switch (symbol.Kind)
                    {
                    case SymbolKind.NamedType:
                        yield return(symbol.ContainingType != null ? _Classifications.NestedDeclaration : _Classifications.Declaration);

                        break;

                    case SymbolKind.Event:
                    case SymbolKind.Method:
                        yield return(_Classifications.NestedDeclaration);

                        break;

                    case SymbolKind.Property:
                        if (symbol.ContainingType.IsAnonymousType == false)
                        {
                            yield return(_Classifications.NestedDeclaration);
                        }
                        break;

                    case SymbolKind.Field:
                        if (node.IsKind(SyntaxKind.TupleElement) && (node as TupleElementSyntax).Identifier.IsKind(SyntaxKind.None))
                        {
                            symbol = semanticModel.GetTypeInfo((node as TupleElementSyntax).Type).Type;
                        }
                        break;
                    }
                }
                else
                {
                    // NOTE: handle alias in using directive
                    if ((node.Parent as NameEqualsSyntax)?.Parent is UsingDirectiveSyntax)
                    {
                        yield return(_Classifications.AliasNamespace);
                    }
                    else if (node is AttributeArgumentSyntax)
                    {
                        symbol = semanticModel.GetSymbolInfo((node as AttributeArgumentSyntax).Expression).Symbol;
                        if (symbol != null && symbol.Kind == SymbolKind.Field && (symbol as IFieldSymbol)?.IsConst == true)
                        {
                            yield return(_Classifications.ConstField);

                            yield return(_Classifications.StaticMember);
                        }
                    }
                    symbol = node.Parent is MemberAccessExpressionSyntax?semanticModel.GetSymbolInfo(node.Parent).CandidateSymbols.FirstOrDefault()
                                 : node.Parent.IsKind(SyntaxKind.Argument) ? semanticModel.GetSymbolInfo((node.Parent as ArgumentSyntax).Expression).CandidateSymbols.FirstOrDefault()
                                                : node.IsKind(SyntaxKind.SimpleBaseType) ? semanticModel.GetTypeInfo((node as SimpleBaseTypeSyntax).Type).Type
                                                : node.IsKind(SyntaxKind.TypeConstraint) ? semanticModel.GetTypeInfo((node as TypeConstraintSyntax).Type).Type
                                                : null;

                    if (symbol == null)
                    {
                        yield break;
                    }
                }
            }
            switch (symbol.Kind)
            {
            case SymbolKind.Alias:
            case SymbolKind.ArrayType:
            case SymbolKind.Assembly:
            case SymbolKind.DynamicType:
            case SymbolKind.ErrorType:
            case SymbolKind.NetModule:
            case SymbolKind.PointerType:
            case SymbolKind.RangeVariable:
            case SymbolKind.Preprocessing:
                //case SymbolKind.Discard:
                yield break;

            case SymbolKind.Label:
                yield return(_Classifications.Label);

                yield break;

            case SymbolKind.TypeParameter:
                yield return(_Classifications.TypeParameter);

                yield break;

            case SymbolKind.Field:
                var fieldSymbol = symbol as IFieldSymbol;
                yield return(fieldSymbol.IsConst ? _Classifications.ConstField : fieldSymbol.IsReadOnly ? _Classifications.ReadonlyField : _Classifications.Field);

                break;

            case SymbolKind.Property:
                yield return(_Classifications.Property);

                break;

            case SymbolKind.Event:
                yield return(_Classifications.Event);

                break;

            case SymbolKind.Local:
                var localSymbol = symbol as ILocalSymbol;
                yield return(localSymbol.IsConst ? _Classifications.ConstField : _Classifications.LocalVariable);

                break;

            case SymbolKind.Namespace:
                yield return(_Classifications.Namespace);

                yield break;

            case SymbolKind.Parameter:
                yield return(_Classifications.Parameter);

                break;

            case SymbolKind.Method:
                var methodSymbol = symbol as IMethodSymbol;
                switch (methodSymbol.MethodKind)
                {
                case MethodKind.Constructor:
                    yield return
                        (node is AttributeSyntax || node.Parent is AttributeSyntax || node.Parent?.Parent is AttributeSyntax
                                                                        ? _Classifications.AttributeName
                                                                        : _Classifications.ConstructorMethod);

                    break;

                case MethodKind.Destructor:
                case MethodKind.StaticConstructor:
                    yield return(_Classifications.ConstructorMethod);

                    break;

                default:
                    yield return(methodSymbol.IsExtensionMethod ? _Classifications.ExtensionMethod
                                                                : methodSymbol.IsExtern ? _Classifications.ExternMethod
                                                                : _Classifications.Method);

                    break;
                }
                break;

            case SymbolKind.NamedType:
                break;

            default:
                yield break;
            }

            if (SymbolMarkManager.HasBookmark)
            {
                var markerStyle = SymbolMarkManager.GetSymbolMarkerStyle(symbol);
                if (markerStyle != null)
                {
                    yield return(markerStyle);
                }
            }

            if (TextEditorHelper.IdentifySymbolSource && symbol.IsMemberOrType() && symbol.ContainingAssembly != null)
            {
                yield return(symbol.ContainingAssembly.GetSourceType() == AssemblySource.Metadata
                                        ? _Classifications.MetadataSymbol
                                        : _Classifications.UserSymbol);
            }

            if (symbol.IsStatic)
            {
                if (symbol.Kind != SymbolKind.Namespace)
                {
                    yield return(_Classifications.StaticMember);
                }
            }
            else if (symbol.IsSealed)
            {
                if (symbol.Kind == SymbolKind.NamedType && (symbol as ITypeSymbol).TypeKind != TypeKind.Class)
                {
                    yield break;
                }
                yield return(_Classifications.SealedMember);
            }
            else if (symbol.IsOverride)
            {
                yield return(_Classifications.OverrideMember);
            }
            else if (symbol.IsVirtual)
            {
                yield return(_Classifications.VirtualMember);
            }
            else if (symbol.IsAbstract)
            {
                yield return(_Classifications.AbstractMember);
            }
        }
 protected abstract bool CanAddImport(SyntaxNode node, CancellationToken cancellationToken);
 public static SyntaxNode Simplify(this SyntaxNode node) =>
     SyntaxNodeSimplifier.Simplify(node);
Example #54
0
 public override SyntaxReference GetReference(SyntaxNode node)
 {
     return(new Reference(this, underlyingTree.GetReference(node)));
 }
Example #55
0
            internal BaseMethodWrapperSymbol(NamedTypeSymbol containingType, MethodSymbol methodBeingWrapped, SyntaxNode syntax, string name)
                : base(containingType, methodBeingWrapped, syntax.SyntaxTree.GetReference(syntax), syntax.GetLocation(), name, DeclarationModifiers.Private)
            {
                Debug.Assert(containingType.ContainingModule is SourceModuleSymbol);
                Debug.Assert(ReferenceEquals(methodBeingWrapped, methodBeingWrapped.ConstructedFrom));
                Debug.Assert(!methodBeingWrapped.IsStatic);

                TypeMap typeMap = null;
                ImmutableArray <TypeParameterSymbol> typeParameters;

                var substitutedType = methodBeingWrapped.ContainingType as SubstitutedNamedTypeSymbol;

                typeMap = ((object)substitutedType == null ? TypeMap.Empty : substitutedType.TypeSubstitution);

                if (!methodBeingWrapped.IsGenericMethod)
                {
                    typeParameters = ImmutableArray <TypeParameterSymbol> .Empty;
                }
                else
                {
                    typeMap = typeMap.WithAlphaRename(methodBeingWrapped, this, out typeParameters);
                }

                AssignTypeMapAndTypeParameters(typeMap, typeParameters);
            }
Example #56
0
        static IClassificationType ClassifySyntaxNode(SyntaxNode node)
        {
            switch (node.Kind())
            {
            case SyntaxKind.MethodDeclaration:
            case SyntaxKind.AnonymousMethodExpression:
            case SyntaxKind.SimpleLambdaExpression:
            case SyntaxKind.ParenthesizedLambdaExpression:
            case SyntaxKind.LocalFunctionStatement:
                return(_Classifications.Method);

            case SyntaxKind.InvocationExpression:
                return((((node as InvocationExpressionSyntax).Expression as IdentifierNameSyntax)?.Identifier.ValueText == "nameof") ? null : _Classifications.Method);

            case SyntaxKind.ConstructorDeclaration:
            case SyntaxKind.AnonymousObjectCreationExpression:
            case SyntaxKind.ObjectInitializerExpression:
            case SyntaxKind.ObjectCreationExpression:
            case SyntaxKind.CollectionInitializerExpression:
            case SyntaxKind.ArrayInitializerExpression:
            case SyntaxKind.ThisConstructorInitializer:
                return(_Classifications.ConstructorMethod);

            case SyntaxKind.PropertyDeclaration: return(_Classifications.Property);

            case SyntaxKind.ClassDeclaration: return(_Classifications.ClassName);

            case SyntaxKind.InterfaceDeclaration: return(_Classifications.InterfaceName);

            case SyntaxKind.EnumDeclaration: return(_Classifications.EnumName);

            case SyntaxKind.StructDeclaration: return(_Classifications.StructName);

            case SyntaxKind.Attribute: return(_Classifications.AttributeName);

            case SyntaxKind.NamespaceDeclaration:
                return(_Classifications.Namespace);

            case SyntaxKind.IfStatement:
            case SyntaxKind.ElseClause:
            case SyntaxKind.SwitchStatement:
            case SyntaxKind.SwitchSection:
                return(_GeneralClassifications.BranchingKeyword);

            case SyntaxKind.ForStatement:
            case SyntaxKind.ForEachStatement:
            case SyntaxKind.WhileStatement:
            case SyntaxKind.DoStatement:
                return(_GeneralClassifications.LoopKeyword);

            case SyntaxKind.UsingStatement:
            case SyntaxKind.LockStatement:
            case SyntaxKind.FixedStatement:
            case SyntaxKind.UnsafeStatement:
            case SyntaxKind.TryStatement:
            case SyntaxKind.CatchClause:
            case SyntaxKind.CatchFilterClause:
            case SyntaxKind.FinallyClause:
                return(_Classifications.ResourceKeyword);
            }
            return(null);
        }
 public static bool IsEquivalentWhenNormalized(this SyntaxNode node, SyntaxNode other) =>
     SyntaxNodeComparer.IsEquivalentToNormalized(node, other);
        private async Task <Document> ProcessNode(Document document, SyntaxNode node, string containerName, CancellationToken cancellationToken)
        {
            var newRoot = await this.ReplaceNodeAsync(node, containerName, cancellationToken).ConfigureAwait(false);

            return(document.WithSyntaxRoot(newRoot));
        }
Example #59
0
 protected abstract BoundExpression FramePointer(SyntaxNode syntax, NamedTypeSymbol frameClass);
 protected abstract bool CanFullyQualify(Diagnostic diagnostic, ref SyntaxNode node);