static bool GetMatch(IfStatementSyntax node, out ExpressionSyntax c, out ReturnStatementSyntax e1, out ReturnStatementSyntax e2, out ReturnStatementSyntax rs)
        {
            rs = e1 = e2 = null;
            c = node.Condition;
            //attempt to match if(condition) return else return
            e1 = ConvertIfStatementToNullCoalescingExpressionAction.GetSimpleStatement(node.Statement) as ReturnStatementSyntax;
            if (e1 == null)
                return false;
            e2 = node.Else != null ? ConvertIfStatementToNullCoalescingExpressionAction.GetSimpleStatement(node.Else.Statement) as ReturnStatementSyntax : null;
            //match
            if (e1 != null && e2 != null)
            {
                return true;
            }

            //attempt to match if(condition) return; return
            if (e1 != null)
            {
                var parentBlock = node.Parent as BlockSyntax;
                if (parentBlock == null)
                    return false;
                var index = parentBlock.Statements.IndexOf(node);
                if (index + 1 < parentBlock.Statements.Count)
                {
                    rs = parentBlock.Statements[index + 1] as ReturnStatementSyntax;
                }

                if (rs != null)
                {
                    e2 = rs;
                    return true;
                }
            }
            return false;
        }
        static bool GetMatch(IfStatementSyntax node, out ExpressionSyntax c, out ReturnStatementSyntax e1, out ReturnStatementSyntax e2, out ReturnStatementSyntax rs)
        {
            rs = e1 = e2 = null;
            c = node.Condition;
            //attempt to match if(condition) return else return
            e1 = ConvertIfStatementToNullCoalescingExpressionAction.GetSimpleStatement(node.Statement) as ReturnStatementSyntax;
            if (e1 == null)
                return false;
            e2 = node.Else != null ? ConvertIfStatementToNullCoalescingExpressionAction.GetSimpleStatement(node.Else.Statement) as ReturnStatementSyntax : null;
            //match
            if (e1 != null && e2 != null)
            {
                return true;
            }

            //attempt to match if(condition) return
            if (e1 != null)
            {
                rs = node.Parent.ChildThatContainsPosition(node.GetTrailingTrivia().Max(t => t.FullSpan.End) + 1).AsNode() as ReturnStatementSyntax;
                if (rs != null)
                {
                    e2 = rs;
                    return true;
                }
            }
            return false;
        }
示例#3
0
 private StatementSyntax CreateNewReturnStm(ReturnStatementSyntax ret)
 {
     var statements = new List<StatementSyntax>();
     var arg = DocumentWeaver.ParametersToArg(_m.ParameterList.Parameters, x => x.Modifiers.Count(y => y.Kind() == SyntaxKind.OutKeyword || y.Kind() == SyntaxKind.RefKeyword) > 0);
     if (DocumentWeaver.IsFunction(_m))
     {
         //pushResult
         var left = SyntaxFactory.IdentifierName(DocumentWeaver.RESULTMARKER);
         var newNode = SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, left, ret.Expression);
         var returnVar = SyntaxFactory.ReturnStatement(left);
         //specialvar = xxxx
         statements.Add(SyntaxFactory.ExpressionStatement(newNode));
         //pushresult (speacialvar)
         statements.Add(DocumentWeaver.ReportStatement("PushResult", SyntaxFactory.Argument(SyntaxFactory.IdentifierName(DocumentWeaver.RESULTMARKER))));
         //place here values of ref/out args
         if (arg != null)
             statements.Add(DocumentWeaver.ReportStatement("PushOutArgs", SyntaxFactory.Argument(arg)));
         //return specialvar
         statements.Add(returnVar);
     }
     else
     {
         //place here values of ref/out args
         if (arg != null)
             statements.Add(DocumentWeaver.ReportStatement("PushOutArgs", SyntaxFactory.Argument(arg)));
         //if void method there is no expression after return, so we add the same expression 'return;'
         statements.Add(ret);
     }
     return SyntaxFactory.Block(statements);
 }
 public override void VisitReturnStatement(ReturnStatementSyntax node)
 {
     if (node.Expression != null && node.Expression.Kind() == SyntaxKind.NullLiteralExpression)
     {
         AddMessage(node.Expression, "Can't return null");
     }
 }
示例#5
0
 public override SyntaxNode VisitReturnStatement(ReturnStatementSyntax node)
 {
     if (!IsInLambda(node))
     {
         modified = true;
         return CreateNewReturnStm(node);
     }
     return base.VisitReturnStatement(node);
 }
 private static MemberAccessExpressionSyntax GetMemberAccessExpressionFromReturn(ReturnStatementSyntax returnIf, ReturnStatementSyntax returnElse)
 {
     if (returnIf?.Expression == null || returnElse?.Expression == null) return null;
     var nullLiteral = returnElse.Expression as LiteralExpressionSyntax;
     if (nullLiteral == null) return null;
     if (!nullLiteral.IsKind(SyntaxKind.NullLiteralExpression)) return null;
     var memberAccessExpression = returnIf.Expression as MemberAccessExpressionSyntax;
     return memberAccessExpression;
 }
        public static string ReturnStatement(ReturnStatementSyntax statement)
        {
            var output = "return";

            if (statement.Expression != null)
            {
                output += " " + SyntaxNode(statement.Expression);
            }

            return output + Semicolon(statement.SemicolonToken);
        }
示例#8
0
            public override void VisitReturnStatement(CSS.ReturnStatementSyntax node)
            {
                if (!found && node.Expression != null)
                {
                    if (node.Ancestors().FirstOrDefault(_ => _ is CSS.LambdaExpressionSyntax) == parentNoe)
                    {
                        found = true;
                    }
                }

                base.VisitReturnStatement(node);
            }
        private async Task<Document> ReplaceWithEmptyEnumerable(Document document, ReturnStatementSyntax returnNullStatement, MethodDeclarationSyntax method, CancellationToken cancellationToken)
        {
            var semanticModel = await document.GetSemanticModelAsync(cancellationToken);
            var typeSymbol = semanticModel.GetSymbolInfo(method.ReturnType, cancellationToken).Symbol as INamedTypeSymbol;
            var genericTypeArgument = typeSymbol.TypeArguments.Single();

            var empty = SyntaxFactory.ParseExpression($"Enumerable.Empty<{genericTypeArgument.Name}>()");
            var returnEmptyStatement = returnNullStatement.WithExpression(empty);
            SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken);
            var newRoot = root.ReplaceNode(returnNullStatement, returnEmptyStatement);
            return document.WithSyntaxRoot(newRoot) ;
        }
 private static async Task<Document> UseExistenceOperatorAsyncWithReturnAsync(Document document, IfStatementSyntax ifStatement, CancellationToken cancellationToken, ReturnStatementSyntax returnIf)
 {
     var newMemberAccess = ((MemberAccessExpressionSyntax)returnIf.Expression).ToConditionalAccessExpression();
     var newReturn = SyntaxFactory.ReturnStatement(newMemberAccess)
         .WithLeadingTrivia(ifStatement.GetLeadingTrivia())
         .WithTrailingTrivia(ifStatement.GetTrailingTrivia())
         .WithAdditionalAnnotations(Formatter.Annotation);
     var root = await document.GetSyntaxRootAsync(cancellationToken);
     var newRoot = root.ReplaceNode(ifStatement, newReturn);
     var newDocument = document.WithSyntaxRoot(newRoot);
     return newDocument;
 }
            public override SyntaxNode VisitReturnStatement(ReturnStatementSyntax node)
            {

                var newNode = node.WithExpression(
                    SyntaxFactory.InvocationExpression(
                        SyntaxFactory.MemberAccessExpression(
                            SyntaxKind.SimpleMemberAccessExpression,
                            SyntaxFactory.ParseName("System.Threading.Tasks.Task")
                                .WithAdditionalAnnotations(Simplifier.Annotation),
                            SyntaxFactory.IdentifierName("FromResult")),
                        SyntaxFactory.ArgumentList().AddArguments(SyntaxFactory.Argument(node.Expression))));
                return base.VisitReturnStatement(newNode);
            }
        public static bool TryGetNewReturnStatement(IfStatementSyntax ifStatement, SemanticModel semanticModel, out ReturnStatementSyntax returnStatement)
        {
            returnStatement = null;

            var conditional = new ReturnConditionalAnalyzer(ifStatement, semanticModel).CreateConditional();
            if (conditional == null)
            {
                return false;
            }

            returnStatement = SyntaxFactory.ReturnStatement(conditional);

            return true;
        }
示例#13
0
        public override SyntaxList <StatementSyntax> VisitReturnStatement(CSS.ReturnStatementSyntax node)
        {
            StatementSyntax stmt;

            if (node.Expression == null)
            {
                stmt = SyntaxFactory.ReturnStatement();
            }
            else
            {
                stmt = SyntaxFactory.ReturnStatement((ExpressionSyntax)node.Expression.Accept(_nodesVisitor));
            }
            return(SyntaxFactory.SingletonList(stmt));
        }
        private static bool TryGetReturnStatements(IfStatementSyntax ifStatement, out ReturnStatementSyntax whenTrueStatement, out ReturnStatementSyntax whenFalseStatement)
        {
            Debug.Assert(ifStatement != null);
            Debug.Assert(ifStatement.Else != null);

            whenTrueStatement = null;
            whenFalseStatement = null;

            var statement = ifStatement.Statement.SingleStatementOrSelf() as ReturnStatementSyntax;
            if (statement == null)
            {
                return false;
            }

            var elseStatement = ifStatement.Else.Statement.SingleStatementOrSelf() as ReturnStatementSyntax;
            if (elseStatement == null)
            {
                return false;
            }

            whenTrueStatement = statement;
            whenFalseStatement = elseStatement;
            return true;
        }
示例#15
0
        public override SyntaxNode VisitReturnStatement(ReturnStatementSyntax node)
        {
            if (node.Expression != null)
            {
                _output.Write(node.ReturnKeyword, "return ");
                this.VisitExpression(node.Expression);
            }
            else
            {
                _output.Write(node.ReturnKeyword, "return");
            }

            return node;
        }
            private IEnumerable<ITypeSymbol> InferTypeForReturnStatement(ReturnStatementSyntax returnStatement, SyntaxToken? previousToken = null)
            {
                // If we are position based, then we have to be after the return statement.
                if (previousToken.HasValue && previousToken.Value != returnStatement.ReturnKeyword)
                {
                    return SpecializedCollections.EmptyEnumerable<ITypeSymbol>();
                }

                var ancestorExpressions = returnStatement.GetAncestorsOrThis<ExpressionSyntax>();

                // If we're in a lambda, then use the return type of the lambda to figure out what to
                // infer.  i.e.   Func<int,string> f = i => { return Foo(); }
                var lambda = ancestorExpressions.FirstOrDefault(e => e.IsKind(SyntaxKind.ParenthesizedLambdaExpression, SyntaxKind.SimpleLambdaExpression));
                if (lambda != null)
                {
                    return InferTypeInLambdaExpression(lambda);
                }

                // If we are inside a delegate then use the return type of the Invoke Method of the delegate type
                var delegateExpression = ancestorExpressions.FirstOrDefault(e => e.IsKind(SyntaxKind.AnonymousMethodExpression));
                if (delegateExpression != null)
                {
                    var delegateType = InferTypesWorker(delegateExpression).FirstOrDefault();
                    if (delegateType != null && delegateType.IsDelegateType())
                    {
                        var delegateInvokeMethod = delegateType.GetDelegateType(this.Compilation).DelegateInvokeMethod;
                        if (delegateInvokeMethod != null)
                        {
                            return SpecializedCollections.SingletonEnumerable(delegateInvokeMethod.ReturnType);
                        }
                    }
                }

                var memberSymbol = GetDeclaredMemberSymbolFromOriginalSemanticModel(this.semanticModel, returnStatement.GetAncestorOrThis<MemberDeclarationSyntax>());

                if (memberSymbol.IsKind(SymbolKind.Method))
                {
                    var method = memberSymbol as IMethodSymbol;
                    if (method.IsAsync)
                    {
                        var typeArguments = method.ReturnType.GetTypeArguments();
                        var taskOfT = this.Compilation.TaskOfTType();

                        return taskOfT != null && method.ReturnType.OriginalDefinition == taskOfT && typeArguments.Any()
                            ? SpecializedCollections.SingletonEnumerable(typeArguments.First())
                            : SpecializedCollections.EmptyEnumerable<ITypeSymbol>();
                    }
                    else
                    {
                        return SpecializedCollections.SingletonEnumerable(method.ReturnType);
                    }
                }
                else if (memberSymbol.IsKind(SymbolKind.Property))
                {
                    return SpecializedCollections.SingletonEnumerable((memberSymbol as IPropertySymbol).Type);
                }
                else if (memberSymbol.IsKind(SymbolKind.Field))
                {
                    return SpecializedCollections.SingletonEnumerable((memberSymbol as IFieldSymbol).Type);
                }

                return SpecializedCollections.EmptyEnumerable<ITypeSymbol>();
            }
示例#17
0
        private BoundStatement BindReturn(ReturnStatementSyntax syntax, DiagnosticBag diagnostics)
        {
            if (syntax.Expression == null)
            {
                return BindReturnParts(syntax, diagnostics);
            }

            var binder = GetBinder(syntax);
            Debug.Assert(binder != null);
            return binder.WrapWithVariablesIfAny(syntax, binder.BindReturnParts(syntax, diagnostics));
        }
示例#18
0
 public override void VisitReturnStatement(ReturnStatementSyntax node)
 {
     if (node.Expression != null)
     {
         var patternBinder = new PatternVariableBinder(node, _enclosing);
         AddToMap(node, patternBinder);
         Visit(node.Expression, patternBinder);
     }
 }
示例#19
0
 public override void VisitReturnStatement(ReturnStatementSyntax node)
 {
     SetResult(node.Expression);
     CurrentState = GetNextState();             // @Todo: make this currentState = currentState.Next
 }
示例#20
0
 public override void VisitReturnStatement(ReturnStatementSyntax node)
 {
     if (node.Expression != null)
     {
         Visit(node.Expression, _enclosing);
     }
 }
            // Checks the return value of the get accessor within SupportedDiagnostics
            private bool SuppDiagReturnCheck(CompilationAnalysisContext context, InvocationExpressionSyntax valueClause, ReturnStatementSyntax returnDeclarationLocation, List<string> ruleNames, PropertyDeclarationSyntax propertyDeclaration)
            {
                if (valueClause == null)
                {
                    ReportDiagnostic(context, IncorrectAccessorReturnRule, returnDeclarationLocation.ReturnKeyword.GetLocation());
                    return false;
                }

                var valueExpression = valueClause.Expression as MemberAccessExpressionSyntax;
                if (valueExpression == null)
                {
                    ReportDiagnostic(context, IncorrectAccessorReturnRule, returnDeclarationLocation.ReturnKeyword.GetLocation());
                    return false;
                }
                
                var valueExprExpr = valueExpression.Expression as IdentifierNameSyntax;
                var valueExprName = valueExpression.Name as IdentifierNameSyntax;

                if (valueExprExpr == null || valueExprExpr.Identifier.Text != "ImmutableArray")
                {
                    ReportDiagnostic(context, IncorrectAccessorReturnRule, valueExpression.GetLocation(), propertyDeclaration.Identifier.Text);
                    return false;
                }

                if (valueExprName == null || valueExprName.Identifier.Text != "Create")
                {
                    ReportDiagnostic(context, SuppDiagReturnValueRule, valueExpression.GetLocation(), propertyDeclaration.Identifier.Text);
                    return false;
                }
                
                var valueArguments = valueClause.ArgumentList as ArgumentListSyntax;
                if (valueArguments == null)
                {
                    ReportDiagnostic(context, SupportedRulesRule, valueExpression.GetLocation(), propertyDeclaration.Identifier.Text);
                    return false;
                }

                SeparatedSyntaxList<ArgumentSyntax> valueArgs = valueArguments.Arguments;
                if (valueArgs.Count == 0)
                {
                    ReportDiagnostic(context, SupportedRulesRule, valueExpression.GetLocation());
                    return false;
                }

                if (ruleNames.Count != valueArgs.Count)
                {
                    ReportDiagnostic(context, SupportedRulesRule, valueExpression.GetLocation());
                    return false;
                }

                List<string> newRuleNames = new List<string>();
                foreach (string rule in ruleNames)
                {
                    newRuleNames.Add(rule);
                }

                foreach (ArgumentSyntax arg in valueArgs)
                {

                    bool foundRule = false;
                    foreach (string ruleName in ruleNames)
                    {
                        var argExpression = arg.Expression as IdentifierNameSyntax;
                        if (argExpression != null)
                        {
                            if (argExpression.Identifier.Text == ruleName)
                            {
                                foundRule = true;
                            }
                        }
                    }
                    if (!foundRule)
                    {
                        ReportDiagnostic(context, SupportedRulesRule, valueExpression.GetLocation());
                        return false;
                    }
                }
                return true;
            }
示例#22
0
        private BoundReturnStatement BindReturn(ReturnStatementSyntax syntax, DiagnosticBag diagnostics)
        {
            var expressionSyntax = syntax.Expression;
            BoundExpression arg = null;
            if (expressionSyntax != null)
            {
                arg = BindValue(expressionSyntax, diagnostics, BindValueKind.RValue);
            }

            bool hasErrors;
            if (BindingTopLevelScriptCode)
            {
                diagnostics.Add(ErrorCode.ERR_ReturnNotAllowedInScript, syntax.ReturnKeyword.GetLocation());
                hasErrors = true;
            }
            else if (IsDirectlyInIterator)
            {
                diagnostics.Add(ErrorCode.ERR_ReturnInIterator, syntax.ReturnKeyword.GetLocation());
                hasErrors = true;
            }
            else if (arg != null)
            {
                hasErrors = arg.HasAnyErrors;
            }
            else
            {
                hasErrors = false;
            }

            if (hasErrors)
            {
                return new BoundReturnStatement(syntax, arg, hasErrors: true);
            }

            TypeSymbol retType = GetCurrentReturnType();

            // The return type could be null; we might be attempting to infer the return type either 
            // because of method type inference, or because we are attempting to do error analysis 
            // on a lambda expression of unknown return type.
            if ((object)retType != null)
            {
                if (retType.SpecialType == SpecialType.System_Void || IsTaskReturningAsyncMethod())
                {
                    if (arg != null)
                    {
                        var container = this.ContainingMemberOrLambda;
                        var lambda = container as LambdaSymbol;
                        if ((object)lambda != null)
                        {
                            // Error case: void-returning or async task-returning method or lambda with "return x;" 
                            var errorCode = retType.SpecialType == SpecialType.System_Void
                                ? ErrorCode.ERR_RetNoObjectRequiredLambda
                                : ErrorCode.ERR_TaskRetNoObjectRequiredLambda;

                            // Anonymous function converted to a void returning delegate cannot return a value
                            Error(diagnostics, errorCode, syntax.ReturnKeyword);

                            // COMPATIBILITY: The native compiler also produced an error
                            // COMPATIBILITY: "Cannot convert lambda expression to delegate type 'Action' because some of the
                            // COMPATIBILITY: return types in the block are not implicitly convertible to the delegate return type"
                            // COMPATIBILITY: This error doesn't make sense in the "void" case because the whole idea of 
                            // COMPATIBILITY: "conversion to void" is a bit unusual, and we've already given a good error.
                        }
                        else
                        {
                            // Error case: void-returning or async task-returning method or lambda with "return x;" 
                            var errorCode = retType.SpecialType == SpecialType.System_Void
                                ? ErrorCode.ERR_RetNoObjectRequired
                                : ErrorCode.ERR_TaskRetNoObjectRequired;

                            Error(diagnostics, errorCode, syntax.ReturnKeyword, container);
                        }
                    }
                }
                else
                {
                    if (arg == null)
                    {
                        // Error case: non-void-returning or Task<T>-returning method or lambda but just have "return;"
                        var requiredType = IsGenericTaskReturningAsyncMethod()
                            ? retType.GetMemberTypeArgumentsNoUseSiteDiagnostics().Single()
                            : retType;

                        Error(diagnostics, ErrorCode.ERR_RetObjectRequired, syntax.ReturnKeyword, requiredType);
                    }
                    else
                    {
                        arg = CreateReturnConversion(syntax, diagnostics, arg, retType);
                    }
                }
            }
            else
            {
                // Check that the returned expression is not void. "return void" is not allowed anywhere outside
                // expression-lambdas.
                //
                // Note: in the case of "return void" in non-async lambdas used in return-type-inference,
                // simply return "void" as the inferred return type and give an error if that didn't work.
                // We can't follow the same route in async methods, since empty-return-operands become a "Task"
                // return type.

                if ((object)arg?.Type != null && IsInAsyncMethod() && arg.Type.SpecialType == SpecialType.System_Void)
                {
                    Error(diagnostics, ErrorCode.ERR_CantReturnVoid, expressionSyntax);
                }
            }

            return new BoundReturnStatement(syntax, arg);
        }
示例#23
0
            public override void VisitReturnStatement(ReturnStatementSyntax node)
            {
                if (node.Expression != null)
                {
                    var symbol = context.SemanticModel.GetEnclosingSymbol(node.SpanStart);
                    if (symbol != null)
                    {
                        CheckAssignment(symbol, node.Expression);
                    }
                }

                base.VisitReturnStatement(node);
            }
示例#24
0
        private BoundReturnStatement BindReturn(ReturnStatementSyntax syntax, DiagnosticBag diagnostics)
        {
            var expressionSyntax = syntax.Expression;
            BoundExpression arg = null;
            if (expressionSyntax != null)
            {
                arg = BindValue(expressionSyntax, diagnostics, BindValueKind.RValue);
            }
            else
            {
                // If this is a void return statement in a script, return default(T).
                var interactiveInitializerMethod = this.ContainingMemberOrLambda as SynthesizedInteractiveInitializerMethod;
                if (interactiveInitializerMethod != null)
                {
                    arg = new BoundDefaultOperator(interactiveInitializerMethod.GetNonNullSyntaxNode(), interactiveInitializerMethod.ResultType);
                }
            }

            bool hasErrors;
            if (IsDirectlyInIterator)
            {
                diagnostics.Add(ErrorCode.ERR_ReturnInIterator, syntax.ReturnKeyword.GetLocation());
                hasErrors = true;
            }
            else if (arg != null)
            {
                hasErrors = arg.HasErrors || ((object)arg.Type != null && arg.Type.IsErrorType());
            }
            else
            {
                hasErrors = false;
            }

            if (hasErrors)
            {
                return new BoundReturnStatement(syntax, arg, hasErrors: true);
            }

            TypeSymbol retType = GetCurrentReturnType();

            // The return type could be null; we might be attempting to infer the return type either 
            // because of method type inference, or because we are attempting to do error analysis 
            // on a lambda expression of unknown return type.
            if ((object)retType != null)
            {
                if (retType.SpecialType == SpecialType.System_Void || IsTaskReturningAsyncMethod())
                {
                    if (arg != null)
                    {
                        var container = this.ContainingMemberOrLambda;
                        var lambda = container as LambdaSymbol;
                        if ((object)lambda != null)
                        {
                            // Error case: void-returning or async task-returning method or lambda with "return x;" 
                            var errorCode = retType.SpecialType == SpecialType.System_Void
                                ? ErrorCode.ERR_RetNoObjectRequiredLambda
                                : ErrorCode.ERR_TaskRetNoObjectRequiredLambda;

                            // Anonymous function converted to a void returning delegate cannot return a value
                            Error(diagnostics, errorCode, syntax.ReturnKeyword);

                            // COMPATIBILITY: The native compiler also produced an error
                            // COMPATIBILITY: "Cannot convert lambda expression to delegate type 'Action' because some of the
                            // COMPATIBILITY: return types in the block are not implicitly convertible to the delegate return type"
                            // COMPATIBILITY: This error doesn't make sense in the "void" case because the whole idea of 
                            // COMPATIBILITY: "conversion to void" is a bit unusual, and we've already given a good error.
                        }
                        else
                        {
                            // Error case: void-returning or async task-returning method or lambda with "return x;" 
                            var errorCode = retType.SpecialType == SpecialType.System_Void
                                ? ErrorCode.ERR_RetNoObjectRequired
                                : ErrorCode.ERR_TaskRetNoObjectRequired;

                            Error(diagnostics, errorCode, syntax.ReturnKeyword, container);
                        }
                    }
                }
                else
                {
                    if (arg == null)
                    {
                        // Error case: non-void-returning or Task<T>-returning method or lambda but just have "return;"
                        var requiredType = IsGenericTaskReturningAsyncMethod()
                            ? retType.GetMemberTypeArgumentsNoUseSiteDiagnostics().Single()
                            : retType;

                        Error(diagnostics, ErrorCode.ERR_RetObjectRequired, syntax.ReturnKeyword, requiredType);
                    }
                    else
                    {
                        arg = CreateReturnConversion(syntax, diagnostics, arg, retType);
                    }
                }
            }
            else
            {
                // Check that the returned expression is not void.
                if ((object)arg?.Type != null && arg.Type.SpecialType == SpecialType.System_Void)
                {
                    Error(diagnostics, ErrorCode.ERR_CantReturnVoid, expressionSyntax);
                }
            }

            return new BoundReturnStatement(syntax, arg);
        }
示例#25
0
 public override void VisitReturnStatement(ReturnStatementSyntax node)
 {
     Emit(node.ToString());
 }
            private void InferTypeForReturnStatement(
                ReturnStatementSyntax returnStatement, SyntaxToken? previousToken, out bool isAsync, out IEnumerable<ITypeSymbol> types)
            {
                isAsync = false;
                types = SpecializedCollections.EmptyEnumerable<ITypeSymbol>();

                // If we are position based, then we have to be after the return statement.
                if (previousToken.HasValue && previousToken.Value != returnStatement.ReturnKeyword)
                {
                    return;
                }

                var ancestorExpressions = returnStatement.GetAncestorsOrThis<ExpressionSyntax>();

                // If we're in a lambda, then use the return type of the lambda to figure out what to
                // infer.  i.e.   Func<int,string> f = i => { return Foo(); }
                var lambda = ancestorExpressions.FirstOrDefault(e => e.IsKind(SyntaxKind.ParenthesizedLambdaExpression, SyntaxKind.SimpleLambdaExpression));
                if (lambda != null)
                {
                    types= InferTypeInLambdaExpression(lambda);
                    isAsync = lambda is ParenthesizedLambdaExpressionSyntax && ((ParenthesizedLambdaExpressionSyntax)lambda).AsyncKeyword.Kind() != SyntaxKind.None;
                    return;
                }

                // If we are inside a delegate then use the return type of the Invoke Method of the delegate type
                var delegateExpression = (AnonymousMethodExpressionSyntax)ancestorExpressions.FirstOrDefault(e => e.IsKind(SyntaxKind.AnonymousMethodExpression));
                if (delegateExpression != null)
                {
                    var delegateType = InferTypes(delegateExpression).FirstOrDefault();
                    if (delegateType != null && delegateType.IsDelegateType())
                    {
                        var delegateInvokeMethod = delegateType.GetDelegateType(this.Compilation).DelegateInvokeMethod;
                        if (delegateInvokeMethod != null)
                        {
                            types = SpecializedCollections.SingletonEnumerable(delegateInvokeMethod.ReturnType);
                            isAsync = delegateExpression.AsyncKeyword.Kind() != SyntaxKind.None;
                            return;
                        }
                    }
                }

                var memberSymbol = GetDeclaredMemberSymbolFromOriginalSemanticModel(SemanticModel, returnStatement.GetAncestorOrThis<MemberDeclarationSyntax>());

                if (memberSymbol.IsKind(SymbolKind.Method))
                {
                    var method = memberSymbol as IMethodSymbol;

                    isAsync = method.IsAsync;
                    types = SpecializedCollections.SingletonEnumerable(method.ReturnType);
                    return;
                }
                else if (memberSymbol.IsKind(SymbolKind.Property))
                {
                    types = SpecializedCollections.SingletonEnumerable((memberSymbol as IPropertySymbol).Type);
                    return;
                }
                else if (memberSymbol.IsKind(SymbolKind.Field))
                {
                    types = SpecializedCollections.SingletonEnumerable((memberSymbol as IFieldSymbol).Type);
                    return;
                }
            }
            public override SyntaxNode VisitReturnStatement(ReturnStatementSyntax node)
            {
                var newNode = base.VisitReturnStatement(node);

                if (newNode is ReturnStatementSyntax)
                {
                    var newReturnStatement = (ReturnStatementSyntax)newNode;
                    if (newReturnStatement.Expression != null)
                    {
                        var parentLambda = node.FirstAncestorOrSelf<LambdaExpressionSyntax>();
                        if (parentLambda != null)
                        {
                            var returnType = (_semanticModel.GetSymbolInfo(parentLambda).Symbol as IMethodSymbol)?.ReturnType;
                            if (returnType != null)
                            {
                                ExpressionSyntax newExpressionWithCast;
                                if (TryCastTo(returnType, node.Expression, newReturnStatement.Expression, out newExpressionWithCast))
                                {
                                    newNode = newReturnStatement.WithExpression(newExpressionWithCast);
                                }
                            }
                        }
                    }
                }

                return newNode;
            }
示例#28
0
			public override void VisitReturnStatement(ReturnStatementSyntax node)
			{
				base.VisitReturnStatement(node);
				if (node.Expression != null)
				{
					_counter++;
				}
			}
 public override SyntaxList <VB.Syntax.StatementSyntax> VisitReturnStatement(CS.Syntax.ReturnStatementSyntax node)
 {
     return(List <VB.Syntax.StatementSyntax>(
                VB.SyntaxFactory.ReturnStatement(nodeVisitor.VisitExpression(node.Expression))));
 }
示例#30
0
        public override SyntaxList <StatementSyntax> VisitReturnStatement(CSS.ReturnStatementSyntax node)
        {
            var vbExpression = node.Expression?.Accept(_nodesVisitor);

            return(SyntaxFactory.SingletonList(ReturnStatement(vbExpression)));
        }
 private static bool ReturnStatementTracesBackToDbSet(ReturnStatementSyntax ret, SyntaxNodeAnalysisContext context, EFCodeFirstClassInfo clsInfo)
 {
     var expr = ret.Expression;
     var kind = expr.Kind();
     //TODO: There are many more cases to handle, so just handle them as the cases arise
     switch (kind)
     {
         case SyntaxKind.SimpleMemberAccessExpression: //return $a.$b
             {
                 var sma = (MemberAccessExpressionSyntax)expr;
                 //Is $a some DbContext?
                 if (sma.Expression.IsDbContextInstance(context) && 
                     sma.Name.Kind() == SyntaxKind.IdentifierName)
                 {
                     var si = context.SemanticModel.GetSymbolInfo(sma.Name);
                     if (si.Symbol != null)
                     {
                         var type = si.Symbol?.TryGetType() as INamedTypeSymbol;
                         //Should be DbSet<T>, but let's just verify
                         if (type.IsDbSet())
                         {
                             //T is our type
                             if (clsInfo?.ClassType == type.TypeArguments[0])
                                 return true;
                         }
                     }
                 }
             }
             break;
     }
     return false;
 }
示例#32
0
 public override void VisitReturnStatement(ReturnStatementSyntax node)
 {
     cb.AppendWithIndent("return ");
       base.VisitReturnStatement(node);
       cb.AppendLine(";");
 }
 public SuppDiagReturnSymbolInfo(InvocationExpressionSyntax valueClause = null, ReturnStatementSyntax returnDeclaration = null)
 {
     ValueClause = valueClause;
     ReturnDeclaration = returnDeclaration;
 }
            private IEnumerable<ITypeSymbol> InferTypeForReturnStatement(ReturnStatementSyntax returnStatement, SyntaxToken? previousToken = null)
            {
                bool isAsync;
                IEnumerable<ITypeSymbol> types;

                InferTypeForReturnStatement(returnStatement, previousToken, out isAsync, out types);

                if (!isAsync)
                {
                    return types;
                }

                var taskOfT = this.Compilation.TaskOfTType();
                if (taskOfT == null || types == null)
                {
                    return SpecializedCollections.EmptyEnumerable<ITypeSymbol>();
                }

                return from t in types
                       where t != null && t.OriginalDefinition.Equals(taskOfT)
                       let nt = (INamedTypeSymbol)t
                       where nt.TypeArguments.Length == 1
                       select nt.TypeArguments[0];
            }