Example #1
0
        /* #End Region
         */
        /* #Region "Consume Functions"
         */
        public NameSyntax ConsumeIdentifer()
        {
            var identifier = new IdentifierNameSyntax(ConsumeToken());
            // This is just "System"
            if (!AtDot())
            {
            return identifier;
            }

            return ConsumeQualifiedName(identifier);
        }
        private BoundExpression ProcessIdentifierName(IdentifierNameSyntax node)
        {
            var symbol = _symbolTable.FindSymbol(node.Name.Text, _symbolContext);

            var localSymbol = symbol as LocalSymbol;
            if (localSymbol != null)
                return new BoundLocalExpression(node, localSymbol);

            var globalSymbol = symbol as GlobalSymbol;
            if (globalSymbol != null)
                return new BoundGlobalExpression(node, globalSymbol);

            // TODO: Static method calls.

            Debug.Fail("Shouldn't be here.");
            return null;
        }
Example #3
0
 public override SyntaxNode?VisitIdentifierName(IdentifierNameSyntax node)
 {
     return(HandleTypeName(node, base.VisitIdentifierName(node)));
 }
Example #4
0
 public override void VisitIdentifierName(IdentifierNameSyntax node)
 {
     this.identifiers.Add(node);
     base.VisitIdentifierName(node);
 }
 public override HashSet <SyntaxTree> VisitIdentifierName(IdentifierNameSyntax node)
 {
     return(AnalyzeNode(node));
 }
        public static async Task ComputeRefactoringsAsync(RefactoringContext context, IdentifierNameSyntax identifierName)
        {
            SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false);

            INamespaceSymbol namespaceSymbol = null;

            SyntaxNode node     = identifierName;
            SyntaxNode prevNode = null;

            while (node.IsParentKind(
                       SyntaxKind.QualifiedName,
                       SyntaxKind.AliasQualifiedName,
                       SyntaxKind.SimpleMemberAccessExpression))
            {
                ISymbol symbol = semanticModel.GetSymbol(node, context.CancellationToken);

                if (symbol?.Kind == SymbolKind.Namespace)
                {
                    namespaceSymbol = (INamespaceSymbol)symbol;
                    prevNode        = node;
                    node            = node.Parent;
                }
                else
                {
                    break;
                }
            }

            node = prevNode;

            if (node.IsParentKind(SyntaxKind.QualifiedName, SyntaxKind.AliasQualifiedName, SyntaxKind.SimpleMemberAccessExpression) &&
                !node.IsDescendantOf(SyntaxKind.UsingDirective) &&
                !CSharpUtility.IsNamespaceInScope(node, namespaceSymbol, semanticModel, context.CancellationToken))
            {
                context.RegisterRefactoring(
                    $"using {namespaceSymbol};",
                    cancellationToken => RefactorAsync(context.Document, node, namespaceSymbol, cancellationToken),
                    RefactoringIdentifiers.AddUsingDirective);
            }
        }
Example #7
0
 public IdentifierNameTranslation(IdentifierNameSyntax syntax, SyntaxTranslation parent) : base(syntax, parent)
 {
 }
        public override void VisitIdentifierName(IdentifierNameSyntax node)
        {
            var symbol = _semanticModel.GetSymbol(node);
            if (symbol != null)
                CreateTag(node.Name, GetClassificationType(symbol));

            base.VisitIdentifierName(node);
        }
Example #9
0
 internal static NameSyntax PrependExternAlias(IdentifierNameSyntax externAliasSyntax, NameSyntax nameSyntax)
 {
     var qualifiedNameSyntax = nameSyntax as QualifiedNameSyntax;
     if (qualifiedNameSyntax != null)
     {
         return SyntaxFactory.QualifiedName(
             PrependExternAlias(externAliasSyntax, qualifiedNameSyntax.Left),
             qualifiedNameSyntax.Right);
     }
     else
     {
         return SyntaxFactory.AliasQualifiedName(externAliasSyntax, (SimpleNameSyntax)nameSyntax);
     }
 }
Example #10
0
 public override bool VisitIdentifierName(IdentifierNameSyntax node)
 {
     return(CheckRecursion((SyntaxNode)(node.Parent as MemberAccessExpressionSyntax) ?? node));
 }
Example #11
0
 public override void VisitIdentifierName(IdentifierNameSyntax node)
 {
     cb.Append(node.Identifier.Text);
 }
Example #12
0
        public static Maybe <InvocationOrObjectCreation> GetInvocationOrObjectCreation(IdentifierNameSyntax node)
        {
            switch (node.Parent)
            {
            case InvocationExpressionSyntax invocation:
                return(new InvocationOrObjectCreation.Invocation(invocation));

            case ObjectCreationExpressionSyntax objectCreation:
                return(new InvocationOrObjectCreation.ObjectCreation(objectCreation));

            case MemberAccessExpressionSyntax memberAccess when memberAccess.Parent is InvocationExpressionSyntax invocation:
                return(new InvocationOrObjectCreation.Invocation(invocation));

            default:
                return(Maybe.NoValue);
            }
        }
Example #13
0
             ImmutableArray <IParameterSymbol> parametersToRemove) GetChangeToContainingMethodParameters(
 Document document,
 IdentifierNameSyntax invokedMethodIdentifierSyntax,
 SemanticModel semanticModel,
 ImmutableArray <(IArgumentOperation arg, WhatToDoWithArgument whatTodo)> argsAndWhatToDoWithThem,
Example #14
0
        private async Task <Solution> ExtractDependency(Document document,
                                                        InvocationExpressionSyntax invocationSyntax,
                                                        IdentifierNameSyntax invokedMethodIdentifierSyntax,
                                                        SemanticModel semanticModel,
                                                        CancellationToken cancellationToken, IInvocationOperation invocationOperation,
                                                        Maybe <ImmutableArray <WhatToDoWithArgument> > whatToDoWithArgsMaybe,
                                                        BaseMethodDeclarationSyntax containingMethod)
        {
            var solution = document.Project.Solution;

            if (whatToDoWithArgsMaybe.HasNoValue)
            {
                return(solution);
            }

            var whatToDoWithArgs = whatToDoWithArgsMaybe.GetValue();

            var documentRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);


            var nodesToReplace =
                new Dictionary <Document, List <NodeChange> >();

            void AddNewChangeToDocument(Document doc, NodeChange change)
            {
                nodesToReplace.GetOrAdd(doc, () => new List <NodeChange>()).Add(change);
            }

            var argsAndWhatToDoWithThem =
                invocationOperation.Arguments
                .Zip(whatToDoWithArgs, (arg, whatTodo) => (arg, whatTodo))
                .ToImmutableArray();

            var(parameterListChange, replacementFunctionParameterName, parametersToRemove) =
                GetChangeToContainingMethodParameters(
                    document,
                    invokedMethodIdentifierSyntax,
                    semanticModel,
                    argsAndWhatToDoWithThem,
                    containingMethod,
                    documentRoot,
                    invocationOperation,
                    whatToDoWithArgs,
                    invocationSyntax);

            AddNewChangeToDocument(
                document,
                parameterListChange);

            var nodeChange =
                GetMethodInvocationChange(
                    invocationSyntax,
                    invokedMethodIdentifierSyntax,
                    argsAndWhatToDoWithThem,
                    replacementFunctionParameterName);

            AddNewChangeToDocument(document, nodeChange);

            var changesToCallers = await GetChangesToCallers(
                semanticModel,
                cancellationToken,
                containingMethod,
                solution,
                invocationOperation.TargetMethod,
                argsAndWhatToDoWithThem,
                parametersToRemove,
                invocationSyntax).ConfigureAwait(false);

            foreach (var changeToCallers in changesToCallers)
            {
                AddNewChangeToDocument(changeToCallers.document, changeToCallers.change);
            }

            return(await UpdateSolution(cancellationToken, solution, nodesToReplace).ConfigureAwait(false));
        }
Example #15
0
        /// <summary>
        /// Generates switch cases for the provided grain type.
        /// </summary>
        /// <param name="grainType">
        /// The grain type.
        /// </param>
        /// <param name="methodIdArgument">
        /// The method id argument, which is used to select the correct switch label.
        /// </param>
        /// <param name="generateMethodHandler">
        /// The function used to generate switch block statements for each method.
        /// </param>
        /// <returns>
        /// The switch cases for the provided grain type.
        /// </returns>
        public static SwitchSectionSyntax[] GenerateGrainInterfaceAndMethodSwitch(
            Type grainType,
            IdentifierNameSyntax methodIdArgument,
            Func <MethodInfo, StatementSyntax[]> generateMethodHandler)
        {
            var interfaces = GrainInterfaceData.GetRemoteInterfaces(grainType);

            interfaces[GrainInterfaceData.GetGrainInterfaceId(grainType)] = grainType;

            // Switch on interface id.
            var interfaceCases = new List <SwitchSectionSyntax>();

            foreach (var @interface in interfaces)
            {
                var interfaceType = @interface.Value;
                var interfaceId   = @interface.Key;
                var methods       = GrainInterfaceData.GetMethods(interfaceType);

                var methodCases = new List <SwitchSectionSyntax>();

                // Switch on method id.
                foreach (var method in methods)
                {
                    // Generate switch case.
                    var methodId   = GrainInterfaceData.ComputeMethodId(method);
                    var methodType = method;

                    // Generate the switch label for this interface id.
                    var methodIdSwitchLabel =
                        SF.CaseSwitchLabel(
                            SF.LiteralExpression(SyntaxKind.NumericLiteralExpression, SF.Literal(methodId)));

                    // Generate the switch body.
                    var methodInvokeStatement = generateMethodHandler(methodType);

                    methodCases.Add(
                        SF.SwitchSection().AddLabels(methodIdSwitchLabel).AddStatements(methodInvokeStatement));
                }

                // Generate the switch label for this interface id.
                var interfaceIdSwitchLabel =
                    SF.CaseSwitchLabel(
                        SF.LiteralExpression(SyntaxKind.NumericLiteralExpression, SF.Literal(interfaceId)));

                // Generate the default case, which will throw a NotImplementedException.
                var errorMessage = SF.BinaryExpression(
                    SyntaxKind.AddExpression,
                    "interfaceId=".GetLiteralExpression(),
                    SF.BinaryExpression(
                        SyntaxKind.AddExpression,
                        SF.LiteralExpression(SyntaxKind.NumericLiteralExpression, SF.Literal(interfaceId)),
                        SF.BinaryExpression(
                            SyntaxKind.AddExpression,
                            ",methodId=".GetLiteralExpression(),
                            methodIdArgument)));
                var throwStatement =
                    SF.ThrowStatement(
                        SF.ObjectCreationExpression(typeof(NotImplementedException).GetTypeSyntax())
                        .AddArgumentListArguments(SF.Argument(errorMessage)));
                var defaultCase = SF.SwitchSection().AddLabels(SF.DefaultSwitchLabel()).AddStatements(throwStatement);

                // Generate switch statements for the methods in this interface.
                var methodSwitchStatements =
                    SF.SwitchStatement(methodIdArgument).AddSections(methodCases.ToArray()).AddSections(defaultCase);

                // Generate the switch section for this interface.
                interfaceCases.Add(
                    SF.SwitchSection().AddLabels(interfaceIdSwitchLabel).AddStatements(methodSwitchStatements));
            }

            return(interfaceCases.ToArray());
        }
        public override SyntaxNode VisitIdentifierName(IdentifierNameSyntax node)
        {
            bool skip =
                (node.Parent.Kind == SyntaxKind.PageField) &&
                (((PageFieldSyntax)node.Parent).Name == node);

            //check if it is field access parameter that should not have record variable name at the fromt
            //i.e. Rec.Setrange(FieldName, ...);
            if (node.Parent.Kind == SyntaxKind.ArgumentList)
            {
                //get parameter index
                ArgumentListSyntax argumentList = (ArgumentListSyntax)node.Parent;
                if (argumentList.Arguments.Contains(node))
                {
                    int        parameterIndex  = argumentList.Arguments.IndexOf(node);
                    IOperation methodOperation = this.SemanticModel.GetOperation(argumentList.Parent);
                    if ((methodOperation != null) && (methodOperation.Kind == OperationKind.InvocationExpression))
                    {
                        IInvocationExpression invocationExpression = methodOperation as IInvocationExpression;
                        if ((invocationExpression.TargetMethod != null) && (invocationExpression.TargetMethod.Parameters.Length > parameterIndex))
                        {
                            IParameterSymbol parameter = invocationExpression.TargetMethod.Parameters[parameterIndex];
                            if (parameter.MemberMustBeOnSame)
                            {
                                skip = true;
                            }
                        }
                    }
                }
            }

            if (!skip)
            {
                IOperation operation = this.SemanticModel.GetOperation(node);
                if (operation != null)
                {
                    IOperation operationInstance = this.GetOperationInstance(operation);

                    if ((operationInstance != null) &&
                        (operationInstance.Syntax != null))
                    {
                        //part of with?
                        if ((operationInstance.Syntax.Parent != null) &&
                            (operationInstance.Syntax.Parent.Kind == SyntaxKind.WithStatement))
                        {
                            return(SyntaxFactory.MemberAccessExpression(
                                       (CodeExpressionSyntax)operationInstance.Syntax.WithoutTrivia(),
                                       node.WithoutTrivia()).WithTriviaFrom(node));
                        }

                        //global variable reference?
                        else if ((operationInstance.Kind == OperationKind.GlobalReferenceExpression) &&
                                 (node.Parent.Kind != SyntaxKind.MemberAccessExpression))
                        {
                            IGlobalReferenceExpression globalRef = (IGlobalReferenceExpression)operationInstance;
                            string name = globalRef.GlobalVariable.Name.ToString();

                            return(SyntaxFactory.MemberAccessExpression(
                                       SyntaxFactory.IdentifierName(name),
                                       node.WithoutTrivia()).WithTriviaFrom(node));
                        }
                    }
                }
            }

            return(base.VisitIdentifierName(node));
        }
Example #17
0
        public void VisitIdentifierName(IdentifierNameSyntax node)
        {
            if (node == null)
                throw new ArgumentNullException("node");

            node.Validate();

            ExpressionStart(node);

            if (node.IsVar)
                _writer.WriteKeyword(PrinterKeyword.Var);
            else if (node.Identifier == "global")
                _writer.WriteKeyword(PrinterKeyword.Global);
            else
                _writer.WriteIdentifier(node.Identifier);

            ExpressionEnd(node);
        }
Example #18
0
        private static IMethodSymbol DetectCalledMethod(SemanticModel semanticModel, InvocationExpressionSyntax invocation, IdentifierNameSyntax identifier)
        {
            var symbolInfo = semanticModel.GetSymbolInfo(identifier);

            if (symbolInfo.CandidateReason == CandidateReason.OverloadResolutionFailure)
            {
                var arguments = invocation.ArgumentList.Arguments;

                // we might have multiple symbols, so we have to choose the right one (compare parameter types)
                foreach (var candidate in symbolInfo.CandidateSymbols.OfType <IMethodSymbol>()
                         .Where(_ => _.Parameters.Length == arguments.Count)
                         .Where(_ => ParametersHaveSameTypes(_.Parameters, arguments, semanticModel)))
                {
                    return(candidate);
                }
            }

            return(symbolInfo.Symbol as IMethodSymbol);
        }
 public override void VisitIdentifierName(IdentifierNameSyntax node)
 {
     // TODO: Figure out what type of identifier this is.
     base.VisitIdentifierName(node);
 }
Example #20
0
        private EssentialOCL.IOclExpression ConstructOCLExpression(QVTRelations.IRelation relation, ExpressionSyntax parsedExpression, QVTBase.IPattern
                                                                   pattern, EMOF.IType type = null)
        {
            // Case single identifier => OCL VariableExp
            if (parsedExpression is IdentifierNameSyntax)
            {
                EssentialOCL.IVariable variable = ConstructVariable(relation, parsedExpression.ToString(), type);
                pattern?.BindsTo.Add(variable);
                return(new EssentialOCL.VariableExp()
                {
                    ReferredVariable = variable
                });
            }

            // Case method call => QVT RelationCallExp (if the relation exists) of function call (if the function exists)
            if (parsedExpression is InvocationExpressionSyntax)
            {
                InvocationExpressionSyntax invocationExpressionSyntax = (InvocationExpressionSyntax)parsedExpression;

                // We are only interested in direct calls
                if (invocationExpressionSyntax.Expression is IdentifierNameSyntax)
                {
                    IdentifierNameSyntax   methodIdentifier = (IdentifierNameSyntax)invocationExpressionSyntax.Expression;
                    ArgumentListSyntax     argumentList     = invocationExpressionSyntax.ArgumentList;
                    QVTRelations.IRelation calledRelation   = FindRelation((QVTRelations.IRelationalTransformation)(relation.Transformation), methodIdentifier.ToString());
                    QVTBase.IFunction      calledFunction   = FindFunction((QVTRelations.IRelationalTransformation)(relation.Transformation), methodIdentifier.ToString());
                    if (calledRelation != null)
                    {
                        QVTRelations.RelationCallExp call = new QVTRelations.RelationCallExp
                        {
                            ReferredRelation = calledRelation
                        };

                        if (argumentList.Arguments.Count != calledRelation.Domain.Count)
                        {
                            throw new InvalidQVTRelationsModelException("Relation " + relation.Name + ": wrong number of arguments in relation call " + calledRelation.Name);
                        }

                        foreach (ArgumentSyntax argumentSyntax in argumentList.Arguments)
                        {
                            QVTRelations.IRelationDomain correspondingDomain   = (QVTRelations.IRelationDomain)calledRelation.Domain[argumentList.Arguments.IndexOf(argumentSyntax)];
                            ExpressionSyntax             argumentExpression    = argumentSyntax.Expression;
                            EssentialOCL.IOclExpression  argumentOCLExpression = ConstructOCLExpression(relation, argumentExpression, pattern, correspondingDomain.RootVariable.Type);
                            call.Argument.Add(argumentOCLExpression);
                        }

                        return(call);
                    }
                    else if (calledFunction != null)
                    {
                        string methodname = methodIdentifier.ToString();
                        EssentialOCL.IOperationCallExp call = new EssentialOCL.OperationCallExp()
                        {
                            Type = calledFunction.Type,
                            ReferredOperation = calledFunction,
                            Name = calledFunction.Name,
                        };

                        foreach (ArgumentSyntax argumentSyntax in argumentList.Arguments)
                        {
                            ExpressionSyntax            argumentExpression    = argumentSyntax.Expression;
                            EssentialOCL.IOclExpression argumentOCLExpression = ConstructOCLExpression(relation, argumentExpression, pattern, calledFunction.Type);
                            call.Argument.Add(argumentOCLExpression);
                        }

                        return(call);
                    }
                }
            }

            // Case assignment => Custom Assignment //TODO replace by OCL '=='? Meaning having to provide basic parts of OCL standard lib
            if (parsedExpression is AssignmentExpressionSyntax)
            {
                AssignmentExpressionSyntax assignmentExpressionSyntax = (AssignmentExpressionSyntax)parsedExpression;
                IdentifierNameSyntax       leftIdentifier             = (IdentifierNameSyntax)assignmentExpressionSyntax.Left;
                ExpressionSyntax           right    = assignmentExpressionSyntax.Right;
                EssentialOCL.IVariable     variable = ConstructVariable(relation, leftIdentifier.ToString());
                pattern?.BindsTo.Add(variable);
                return(new EssentialOCL.Assignment()
                {
                    AssignedVariable = variable,
                    Value = ConstructOCLExpression(relation, right, pattern)
                });
            }
            // Any other case => Custom CSharpOpaqueExpression // TODO replace by QVT "Function" with a black box implementation?
            EssentialOCL.CSharpOpaqueExpression cSharpOpaqueExpression = new EssentialOCL.CSharpOpaqueExpression()
            {
                Code = parsedExpression.ToString()
            };
            SetBindings(relation, pattern, cSharpOpaqueExpression, parsedExpression);
            return(cSharpOpaqueExpression);
        }
 public override SyntaxToken VisitIdentifierName(IdentifierNameSyntax node) => node.Identifier;
Example #22
0
        private static void AnalyzeNode(SyntaxNodeAnalysisContext context)
        {
            if (context.IsGenerated())
            {
                return;
            }
            var ifStatement = (IfStatementSyntax)context.Node;

            // ignoring else if
            if (ifStatement.Parent is ElseClauseSyntax)
            {
                return;
            }

            // ignoring simple if statement
            if (ifStatement.Else == null)
            {
                return;
            }

            var nestedIfs = FindNestedIfs(ifStatement).ToArray();

            // ignoring less than 3 nested ifs
            if (nestedIfs.Length < 3)
            {
                return;
            }

            // ignoring when not all conditionals are "equals"
            IdentifierNameSyntax common = null;

            for (int i = 0; i < nestedIfs.Length; i++)
            {
                var condition = nestedIfs[i].Condition as BinaryExpressionSyntax;

                // all ifs should have binary expressions as conditions
                if (condition == null)
                {
                    return;
                }

                // all conditions should be "equal"
                if (!condition.IsKind(SyntaxKind.EqualsExpression))
                {
                    return;
                }

                var left = condition.Left as IdentifierNameSyntax;
                // all conditions should have an identifier in the left
                if (left == null)
                {
                    return;
                }

                if (i == 0)
                {
                    common = left;
                }
                else if (!left.Identifier.IsEquivalentTo(common.Identifier))
                {
                    // all conditions should have the same identifier in the left
                    return;
                }

                var right = context.SemanticModel.GetConstantValue(condition.Right);
                // only constants in the right side
                if (!right.HasValue)
                {
                    return;
                }
            }

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

            context.ReportDiagnostic(diagnostic);
        }
Example #23
0
            public bool MatchesIdentifier(IdentifierNameSyntax id, SemanticModel semanticModel)
            {
                var symbol = semanticModel.GetSymbolInfo(id).Symbol;

                return(Equals(parameterSymbol, symbol));
            }
 public override void VisitIdentifierName(IdentifierNameSyntax node)
 {
     AddDependentType(node);
     base.VisitIdentifierName(node);
 }
Example #25
0
 internal static bool IsTypeInContextWhichNeedsDynamicAttribute(this IdentifierNameSyntax typeNode)
 {
     Debug.Assert(typeNode != null);
     return(SyntaxFacts.IsInTypeOnlyContext(typeNode) && IsInContextWhichNeedsDynamicAttribute(typeNode));
 }
            static async Task <bool> IsSemanticTypeArgumentAsync(Document document, int position, IdentifierNameSyntax identifier, CancellationToken cancellationToken)
            {
                var semanticModel = await document.ReuseExistingSpeculativeModelAsync(position, cancellationToken).ConfigureAwait(false);

                var info = semanticModel.GetSymbolInfo(identifier, cancellationToken);

                return(info.CandidateSymbols.Any(static s => s.GetArity() > 0));
Example #27
0
 protected static void VerifyNotInScope(SemanticModel model, IdentifierNameSyntax reference)
 {
     Assert.Null(model.GetSymbolInfo(reference).Symbol);
     Assert.False(model.LookupSymbols(reference.SpanStart, name: reference.Identifier.ValueText).Any());
     Assert.False(model.LookupNames(reference.SpanStart).Contains(reference.Identifier.ValueText));
 }
Example #28
0
        public override async Task RegisterCodeFixesAsync(CodeFixContext context)
        {
            var diagnostic = context.Diagnostics.First();

            var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

            var syntaxNode = (ExpressionSyntax)root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true);

            var container = Utils.GetContainingFunction(syntaxNode);

            if (container.BlockOrExpression == null)
            {
                return;
            }

            var semanticModel = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false);

            var enclosingSymbol = semanticModel.GetEnclosingSymbol(diagnostic.Location.SourceSpan.Start, context.CancellationToken);

            if (enclosingSymbol == null)
            {
                return;
            }

            bool convertToAsync = !container.IsAsync && Utils.HasAsyncCompatibleReturnType(enclosingSymbol as IMethodSymbol);

            if (convertToAsync)
            {
                // We don't support this yet, and we don't want to take the sync method path in this case.
                // The user will have to fix this themselves.
                return;
            }

            Regex lookupKey = (container.IsAsync || convertToAsync)
                ? CommonInterest.FileNamePatternForMethodsThatSwitchToMainThread
                : CommonInterest.FileNamePatternForMethodsThatAssertMainThread;

            string[] options = diagnostic.Properties[lookupKey.ToString()].Split('\n');
            if (options.Length > 0)
            {
                // For any symbol lookups, we want to consider the position of the very first statement in the block.
                int positionForLookup = container.BlockOrExpression.GetLocation().SourceSpan.Start + 1;

                var cancellationTokenSymbol = new Lazy <ISymbol>(() => semanticModel.LookupSymbols(positionForLookup)
                                                                 .Where(s => (s.IsStatic || !enclosingSymbol.IsStatic) && s.CanBeReferencedByName && IsSymbolTheRightType(s, nameof(CancellationToken), Namespaces.SystemThreading))
                                                                 .OrderBy(s => s.ContainingSymbol.Equals(enclosingSymbol) ? 1 : s.ContainingType.Equals(enclosingSymbol.ContainingType) ? 2 : 3) // prefer locality
                                                                 .FirstOrDefault());
                foreach (var option in options)
                {
                    var(fullTypeName, methodName) = SplitOffLastElement(option);
                    var(ns, leafTypeName)         = SplitOffLastElement(fullTypeName);
                    string[] namespaces = ns?.Split('.');
                    if (fullTypeName == null)
                    {
                        continue;
                    }

                    var proposedType = semanticModel.Compilation.GetTypeByMetadataName(fullTypeName);

                    // We're looking for methods that either require no parameters,
                    // or (if we have one to give) that have just one parameter that is a CancellationToken.
                    var proposedMethod = proposedType?.GetMembers(methodName).OfType <IMethodSymbol>()
                                         .FirstOrDefault(m => !m.Parameters.Any(p => !p.HasExplicitDefaultValue) ||
                                                         (cancellationTokenSymbol.Value != null && m.Parameters.Length == 1 && IsCancellationTokenParameter(m.Parameters[0])));
                    if (proposedMethod == null)
                    {
                        // We can't find it, so don't offer to use it.
                        continue;
                    }

                    if (proposedMethod.IsStatic)
                    {
                        OfferFix(option);
                    }
                    else
                    {
                        // Search fields on the declaring type.
                        // Consider local variables too, if they're captured in a closure from some surrounding code block
                        // such that they would presumably be initialized by the time the first statement in our own code block runs.
                        ITypeSymbol enclosingTypeSymbol = enclosingSymbol as ITypeSymbol ?? enclosingSymbol.ContainingType;
                        if (enclosingTypeSymbol != null)
                        {
                            var candidateMembers = from symbol in semanticModel.LookupSymbols(positionForLookup, enclosingTypeSymbol)
                                                   where symbol.IsStatic || !enclosingSymbol.IsStatic
                                                   where IsSymbolTheRightType(symbol, leafTypeName, namespaces)
                                                   select symbol;
                            foreach (var candidate in candidateMembers)
                            {
                                OfferFix($"{candidate.Name}.{methodName}");
                            }
                        }

                        // Find static fields/properties that return the matching type from other public, non-generic types.
                        var candidateStatics = from offering in semanticModel.LookupStaticMembers(positionForLookup).OfType <ITypeSymbol>()
                                               from symbol in offering.GetMembers()
                                               where symbol.IsStatic && symbol.CanBeReferencedByName && IsSymbolTheRightType(symbol, leafTypeName, namespaces)
                                               select symbol;
                        foreach (var candidate in candidateStatics)
                        {
                            OfferFix($"{candidate.ContainingNamespace}.{candidate.ContainingType.Name}.{candidate.Name}.{methodName}");
                        }
                    }

                    void OfferFix(string fullyQualifiedMethod)
                    {
                        context.RegisterCodeFix(CodeAction.Create($"Add call to {fullyQualifiedMethod}", ct => Fix(fullyQualifiedMethod, proposedMethod, cancellationTokenSymbol, ct), fullyQualifiedMethod), context.Diagnostics);
                    }
                }
            }

            bool IsSymbolTheRightType(ISymbol symbol, string typeName, IReadOnlyList <string> namespaces)
            {
                var fieldSymbol     = symbol as IFieldSymbol;
                var propertySymbol  = symbol as IPropertySymbol;
                var parameterSymbol = symbol as IParameterSymbol;
                var localSymbol     = symbol as ILocalSymbol;
                var memberType      = fieldSymbol?.Type ?? propertySymbol?.Type ?? parameterSymbol?.Type ?? localSymbol?.Type;

                return(memberType?.Name == typeName && memberType.BelongsToNamespace(namespaces));
            }

            Task <Document> Fix(string fullyQualifiedMethod, IMethodSymbol methodSymbol, Lazy <ISymbol> cancellationTokenSymbol, CancellationToken cancellationToken)
            {
                int typeAndMethodDelimiterIndex    = fullyQualifiedMethod.LastIndexOf('.');
                IdentifierNameSyntax methodName    = SyntaxFactory.IdentifierName(fullyQualifiedMethod.Substring(typeAndMethodDelimiterIndex + 1));
                ExpressionSyntax     invokedMethod = Utils.MemberAccess(fullyQualifiedMethod.Substring(0, typeAndMethodDelimiterIndex).Split('.'), methodName);
                var invocationExpression           = SyntaxFactory.InvocationExpression(invokedMethod);
                var cancellationTokenParameter     = methodSymbol.Parameters.FirstOrDefault(IsCancellationTokenParameter);

                if (cancellationTokenParameter != null && cancellationTokenSymbol.Value != null)
                {
                    var arg = SyntaxFactory.Argument(SyntaxFactory.IdentifierName(cancellationTokenSymbol.Value.Name));
                    if (methodSymbol.Parameters.IndexOf(cancellationTokenParameter) > 0)
                    {
                        arg = arg.WithNameColon(SyntaxFactory.NameColon(SyntaxFactory.IdentifierName(cancellationTokenParameter.Name)));
                    }

                    invocationExpression = invocationExpression.AddArgumentListArguments(arg);
                }

                ExpressionSyntax awaitExpression = container.IsAsync ? SyntaxFactory.AwaitExpression(invocationExpression) : null;
                var addedStatement = SyntaxFactory.ExpressionStatement(awaitExpression ?? invocationExpression)
                                     .WithAdditionalAnnotations(Simplifier.Annotation, Formatter.Annotation);
                var initialBlockSyntax = container.BlockOrExpression as BlockSyntax;

                if (initialBlockSyntax == null)
                {
                    initialBlockSyntax = SyntaxFactory.Block(SyntaxFactory.ReturnStatement((ExpressionSyntax)container.BlockOrExpression))
                                         .WithAdditionalAnnotations(Formatter.Annotation);
                }

                var newBlock = initialBlockSyntax.WithStatements(initialBlockSyntax.Statements.Insert(0, addedStatement));

                return(Task.FromResult(context.Document.WithSyntaxRoot(root.ReplaceNode(container.BlockOrExpression, newBlock))));
            }

            bool IsCancellationTokenParameter(IParameterSymbol parameterSymbol) => parameterSymbol.Type.Name == nameof(CancellationToken) && parameterSymbol.Type.BelongsToNamespace(Namespaces.SystemThreading);
        }
Example #29
0
 public override void VisitIdentifierName(IdentifierNameSyntax node)
 {
     VisitSimpleName(node, node.Identifier.ValueText);
 }
 public BqlInvocationDataFlowAnalyserBase(SyntaxNodeAnalysisContext syntaxContext, PXContext pxContext, IdentifierNameSyntax identifierNode)
 {
     SyntaxContext       = syntaxContext;
     PXContext           = pxContext;
     Invocation          = SyntaxContext.Node as InvocationExpressionSyntax;
     InvocationStatement = Invocation.GetStatementNode();
     VariableName        = identifierNode.Identifier.ValueText;
 }
Example #31
0
 private static string GetIdentifierFromIdentifierNameSyntax(IdentifierNameSyntax syntax) =>
 syntax.Identifier.Value.ToString();
Example #32
0
        /// <summary>
        /// Resolves and returns all possible side effects at the point of the
        /// given call argument list.
        /// </summary>
        /// <param name="argumentList">Argument list</param>
        /// <param name="model">SemanticModel</param>
        /// <returns>Set of side effects</returns>
        internal Dictionary <ISymbol, HashSet <ISymbol> > GetResolvedSideEffects(ArgumentListSyntax argumentList,
                                                                                 SemanticModel model)
        {
            Dictionary <ISymbol, HashSet <ISymbol> > sideEffects = new Dictionary <ISymbol, HashSet <ISymbol> >();

            foreach (var sideEffect in this.SideEffects)
            {
                HashSet <ISymbol> argSymbols = new HashSet <ISymbol>();
                foreach (var index in sideEffect.Value)
                {
                    IdentifierNameSyntax arg = null;
                    var argExpr = argumentList.Arguments[index].Expression;
                    if (argExpr is IdentifierNameSyntax)
                    {
                        arg = argExpr as IdentifierNameSyntax;
                        var argType = model.GetTypeInfo(arg).Type;
                        if (Utilities.IsTypeAllowedToBeSend(argType) ||
                            Utilities.IsMachineType(argType, model))
                        {
                            continue;
                        }

                        argSymbols.Add(model.GetSymbolInfo(arg).Symbol);
                    }
                    else if (argExpr is MemberAccessExpressionSyntax)
                    {
                        var name    = (argExpr as MemberAccessExpressionSyntax).Name;
                        var argType = model.GetTypeInfo(name).Type;
                        if (Utilities.IsTypeAllowedToBeSend(argType) ||
                            Utilities.IsMachineType(argType, model))
                        {
                            continue;
                        }

                        arg = Utilities.GetFirstNonMachineIdentifier(argExpr, model);
                        argSymbols.Add(model.GetSymbolInfo(arg).Symbol);
                    }
                    else if (argExpr is ObjectCreationExpressionSyntax)
                    {
                        var objCreation = argExpr as ObjectCreationExpressionSyntax;
                        var summary     = MethodSummary.TryGetSummary(objCreation, model);
                        if (summary == null)
                        {
                            continue;
                        }

                        var nestedSideEffects = summary.GetResolvedSideEffects(
                            objCreation.ArgumentList, model);
                        foreach (var nestedSideEffect in nestedSideEffects)
                        {
                            sideEffects.Add(nestedSideEffect.Key, nestedSideEffect.Value);
                        }
                    }
                    else if (argExpr is InvocationExpressionSyntax)
                    {
                        var invocation = argExpr as InvocationExpressionSyntax;
                        var summary    = MethodSummary.TryGetSummary(invocation, model);
                        if (summary == null)
                        {
                            continue;
                        }

                        var nestedSideEffects = summary.GetResolvedSideEffects(
                            invocation.ArgumentList, model);
                        foreach (var nestedSideEffect in nestedSideEffects)
                        {
                            sideEffects.Add(nestedSideEffect.Key, nestedSideEffect.Value);
                        }
                    }
                }

                sideEffects.Add(sideEffect.Key, argSymbols);
            }

            return(sideEffects);
        }
Example #33
0
        public QualifiedNameSyntax ConsumeQualifiedName(NameSyntax left)
        {
            var period = ConsumeToken();
            var id2 = new IdentifierNameSyntax(ConsumeToken());
            var qual = new QualifiedNameSyntax(left, period, id2);
            if (AtDot())
            {
            return ConsumeQualifiedName(qual);
            }

            return qual;
        }
Example #34
0
            private MethodDeclarationSyntax CreateParamsElementArrayMethod(MetaField field, IdentifierNameSyntax methodName, SimpleNameSyntax collectionMutationMethodName, bool passThroughChildSync = false)
            {
                var paramsArrayMethod = CreateMethodStarter(methodName.Identifier, field)
                                        .WithParameterList(CreateParamsElementArrayParameters(field));

                var lambdaParameter = SyntaxFactory.Parameter(SyntaxFactory.Identifier("v"));
                var argument        = passThroughChildSync
                    ? (ExpressionSyntax)Syntax.EnumerableExtension(
                    SyntaxFactory.IdentifierName(nameof(Enumerable.Select)),
                    ValuesParameterName,
                    SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList(
                                                   SyntaxFactory.Argument(Syntax.ThisDot(SyncImmediateChildToCurrentVersionMethodName)))))
                    : ValuesParameterName;

                paramsArrayMethod = this.AddMethodBody(
                    paramsArrayMethod,
                    field,
                    receiver => SyntaxFactory.InvocationExpression(
                        SyntaxFactory.MemberAccessExpression(
                            SyntaxKind.SimpleMemberAccessExpression,
                            receiver,
                            collectionMutationMethodName),
                        SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList(
                                                       SyntaxFactory.Argument(argument)))));

                return(paramsArrayMethod);
            }
Example #35
0
        private NameSyntax ParseName()
        {
            var result = ParseIdentifier() as NameSyntax;

            while (Current.Kind == SyntaxKind.ColonColonToken)
            {
                var colonColon = Match(SyntaxKind.ColonColonToken);
                var right = new IdentifierNameSyntax(Match(SyntaxKind.IdentifierToken));

                result = new QualifiedNameSyntax(result, colonColon, right);
            }

            return result;
        }
Example #36
0
            private MethodDeclarationSyntax CreateSingleElementMethod(MetaField field, IdentifierNameSyntax methodName, SimpleNameSyntax collectionMutationMethodName, bool passThroughChildSync = false)
            {
                var paramsArrayMethod = CreateMethodStarter(methodName.Identifier, field)
                                        .WithParameterList(SyntaxFactory.ParameterList(SyntaxFactory.SingletonSeparatedList(
                                                                                           SyntaxFactory.Parameter(ValueParameterName.Identifier).WithType(GetFullyQualifiedSymbolName(field.ElementType)))));

                var argument = passThroughChildSync
                    ? (ExpressionSyntax)SyntaxFactory.InvocationExpression(
                    Syntax.ThisDot(SyncImmediateChildToCurrentVersionMethodName),
                    SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList(SyntaxFactory.Argument(ValueParameterName))))
                    : ValueParameterName;

                paramsArrayMethod = this.AddMethodBody(
                    paramsArrayMethod,
                    field,
                    receiver => SyntaxFactory.InvocationExpression(
                        SyntaxFactory.MemberAccessExpression(
                            SyntaxKind.SimpleMemberAccessExpression,
                            receiver,
                            collectionMutationMethodName),
                        SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList(
                                                       SyntaxFactory.Argument(argument)))));

                return(paramsArrayMethod);
            }
Example #37
0
 public virtual void VisitIdentifierName(IdentifierNameSyntax node)
 {
     DefaultVisit(node);
 }
 public override bool VisitIdentifierName(IdentifierNameSyntax node)
 => string.Equals("nameof", node.Identifier.ValueText, StringComparison.Ordinal);
Example #39
0
        private ExpressionSyntax ParseDirectiveTerm()
        {
            ExpressionSyntax expr;

            var tk = Current.Kind;
            switch (tk)
            {
                case SyntaxKind.IdentifierToken:
                    expr = ParseIdentifier();
                    break;
                case SyntaxKind.FalseKeyword:
                case SyntaxKind.TrueKeyword:
                case SyntaxKind.IntegerLiteralToken:
                case SyntaxKind.FloatLiteralToken:
                    expr = new LiteralExpressionSyntax(SyntaxFacts.GetLiteralExpression(Current.Kind), NextToken());
                    break;
                case SyntaxKind.OpenParenToken:
                    expr = ParseDirectiveParenthesizedExpression();
                    break;
                default:
                    expr = CreateMissingIdentifierName();

                    if (tk == SyntaxKind.EndOfFileToken)
                        expr = WithDiagnostic(expr, DiagnosticId.ExpressionExpected);
                    else
                        expr = WithDiagnostic(expr, DiagnosticId.InvalidExprTerm, tk.GetText());

                    break;
            }

            // Might be function invocation. We only have one function in the preprocessor - "defined".
            if (Current.Kind == SyntaxKind.OpenParenToken && expr.Kind == SyntaxKind.IdentifierName
                && ((IdentifierNameSyntax) expr).Name.ContextualKind == SyntaxKind.DefinedKeyword)
            {
                _lexer.ExpandMacros = false;

                var openParen = Match(SyntaxKind.OpenParenToken);
                var name = new IdentifierNameSyntax(NextToken());

                _lexer.ExpandMacros = true;

                var closeParen = Match(SyntaxKind.CloseParenToken);
                expr = new InvocationExpressionSyntax(expr, new ArgumentListSyntax(
                    openParen,
                    new SeparatedSyntaxList<ExpressionSyntax>(new List<SyntaxNode> { name }),
                    closeParen));
            }

            return expr;
        }
 public override void VisitIdentifierName(IdentifierNameSyntax node) => IdentifierName = node.Identifier.ValueText;