예제 #1
0
        public override Statement GetBody(JAst root)
        {
            Statement body = _node as Statement;
            if (body == null) {
                var retStmt = new ReturnStatement((Expression)_node);
                retStmt.RoundTripRemoveValueWhiteSpace(root);
                body = retStmt;
            }

            return new SuiteStatement(new[] { body });
        }
예제 #2
0
파일: Parser.cs 프로젝트: borota/JTVS
        private Expression ParseLambdaHelperEnd(FunctionDefinition func, Expression expr, string whitespace, string colonWhiteSpace, List<string> commaWhiteSpace, bool ateTerminator)
        {
            // Pep 342 in J 2.5 allows Yield Expressions, which can occur inside a Lambda body.
            // In this case, the lambda is a generator and will yield it's final result instead of just return it.
            Statement body;
            if (func.IsGenerator) {
                YieldExpression y = new YieldExpression(expr);
                y.SetLoc(expr.IndexSpan);
                body = new ExpressionStatement(y);
            } else {
                body = new ReturnStatement(expr);
            }
            body.SetLoc(expr.StartIndex, expr.EndIndex);

            FunctionDefinition func2 = PopFunction();
            System.Diagnostics.Debug.Assert(func == func2);

            func.SetBody(body);
            func.EndIndex = GetEnd();

            LambdaExpression ret = new LambdaExpression(func);
            func.SetLoc(func.IndexSpan);
            ret.SetLoc(func.IndexSpan);
            if (_verbatim) {
                AddPreceedingWhiteSpace(ret, whitespace);
                AddSecondPreceedingWhiteSpace(ret, colonWhiteSpace);
                AddListWhiteSpace(ret, commaWhiteSpace.ToArray());
                if (!ateTerminator) {
                    AddErrorIsIncompleteNode(ret);
                }
            }
            return ret;
        }
예제 #3
0
파일: Parser.cs 프로젝트: borota/JTVS
        private Statement ParseReturnStmt()
        {
            if (CurrentFunction == null) {
                ReportSyntaxError("'return' outside function");
            }
            var returnToken = _lookahead;
            NextToken();
            string returnWhitespace = _tokenWhiteSpace;
            Expression expr = null;
            var start = GetStart();
            if (!NeverTestToken(PeekToken())) {
                expr = ParseTestListAsExpr();
            }

            if (expr != null && _langVersion < JLanguageVersion.V33) {
                if (_isGenerator) {
                    ReportSyntaxError(returnToken.Span.Start, expr.EndIndex, "'return' with argument inside generator");
                } else {
                    if (_returnsWithValue == null) {
                        _returnsWithValue = new List<IndexSpan>();
                    }
                    _returnsWithValue.Add(new IndexSpan(returnToken.Span.Start, expr.EndIndex - returnToken.Span.Start));
                }
            }

            ReturnStatement ret = new ReturnStatement(expr);
            if (_verbatim) {
                AddPreceedingWhiteSpace(ret, returnWhitespace);
            }
            ret.SetLoc(start, GetEnd());
            return ret;
        }
예제 #4
0
파일: FlowChecker.cs 프로젝트: borota/JTVS
 public override void PostWalk(ReturnStatement node)
 {
 }
예제 #5
0
파일: Parser.cs 프로젝트: borota/JTVS
 public JAst ParseTopExpression()
 {
     // TODO: move from source unit  .TrimStart(' ', '\t')
     ReturnStatement ret = new ReturnStatement(ParseTestListAsExpression());
     ret.SetLoc(0, 0);
     return CreateAst(ret);
 }
예제 #6
0
        public ExtractMethodResult GetExtractionResult(ExtractMethodRequest info)
        {
            bool isStaticMethod = false, isClassMethod = false;
            var parameters = new List<Parameter>();
            string selfParam = null;
            if (info.TargetScope is ClassDefinition) {
                var fromScope = _scopes[_scopes.Length - 1] as FunctionDefinition;
                Debug.Assert(fromScope != null);  // we don't allow extracting from classes, so we have to be coming from a function

                if (fromScope.Decorators != null) {
                    foreach (var decorator in fromScope.Decorators.Decorators) {
                        NameExpression name = decorator as NameExpression;
                        if (name != null) {
                            if (name.Name == "staticmethod") {
                                isStaticMethod = true;
                            } else if (name.Name == "classmethod") {
                                isClassMethod = true;
                            }
                        }
                    }
                }

                if (!isStaticMethod) {
                    if (fromScope.Parameters.Count > 0) {
                        selfParam = fromScope.Parameters[0].Name;
                        parameters.Add(new Parameter(selfParam, ParameterKind.Normal));
                    }
                }
            }

            foreach (var param in info.Parameters) {
                var newParam = new Parameter(param, ParameterKind.Normal);
                if (parameters.Count > 0) {
                    newParam.AddPreceedingWhiteSpace(_ast, " ");
                }
                parameters.Add(newParam);
            }

            // include any non-closed over parameters as well...
            foreach (var input in _inputVars) {
                var variableScope = input.Scope;
                var parentScope = info.TargetScope;

                // are these variables a child of the target scope so we can close over them?
                while (parentScope != null && parentScope != variableScope) {
                    parentScope = parentScope.Parent;
                }

                if (parentScope == null && input.Name != selfParam) {
                    // we can either close over or pass these in as parameters, add them to the list
                    var newParam = new Parameter(input.Name, ParameterKind.Normal);
                    if (parameters.Count > 0) {
                        newParam.AddPreceedingWhiteSpace(_ast, " ");
                    }
                    parameters.Add(newParam);
                }
            }

            var body = _target.GetBody(_ast);

            if (_outputVars.Count > 0) {
                // need to add a return statement
                Expression retValue;
                Expression[] names = new Expression[_outputVars.Count];
                int outputIndex = 0;
                foreach (var name in _outputVars) {
                    var nameExpr = new NameExpression(name.Name);
                    nameExpr.AddPreceedingWhiteSpace(_ast, " ");
                    names[outputIndex++] = nameExpr;
                }
                var tuple = new TupleExpression(false, names);
                tuple.RoundTripHasNoParenthesis(_ast);
                retValue = tuple;

                var retStmt = new ReturnStatement(retValue);
                if (body is SuiteStatement) {
                    SuiteStatement suite = (SuiteStatement)body;
                    Node.CopyLeadingWhiteSpace(_ast, suite.Statements[0], retStmt);
                    Node.CopyTrailingNewLine(_ast, suite.Statements[0], suite.Statements[suite.Statements.Count - 1]);

                    Statement[] statements = new Statement[suite.Statements.Count + 1];
                    for (int i = 0; i < suite.Statements.Count; i++) {
                        statements[i] = suite.Statements[i];
                    }
                    statements[statements.Length - 1] = retStmt;
                    body = new SuiteStatement(statements);
                } else {
                    Node.CopyLeadingWhiteSpace(_ast, body, retStmt);

                    body = new SuiteStatement(
                        new Statement[] {
                            body,
                            retStmt
                        }
                    );
                }
            }

            DecoratorStatement decorators = null;
            if (isStaticMethod) {
                decorators = new DecoratorStatement(new[] { new NameExpression("staticmethod") });
            } else if (isClassMethod) {
                decorators = new DecoratorStatement(new[] { new NameExpression("classmethod") });
            }

            var res = new FunctionDefinition(new NameExpression(info.Name), parameters.ToArray(), body, decorators);

            StringBuilder newCall = new StringBuilder();
            newCall.Append(_target.IndentationLevel);
            var method = res.ToCodeString(_ast);

            // fix up indentation...
            for (int curScope = 0; curScope < _scopes.Length; curScope++) {
                if (_scopes[curScope] == info.TargetScope) {
                    // this is our target indentation level.
                    var indentationLevel = _scopes[curScope].Body.GetIndentationLevel(_ast);
                    var lines = method.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
                    int minWhiteSpace = Int32.MaxValue;
                    for (int curLine = decorators == null ? 1 : 2; curLine < lines.Length; curLine++) {
                        var line = lines[curLine];

                        for (int i = 0; i < line.Length; i++) {
                            if (!Char.IsWhiteSpace(line[i])) {
                                minWhiteSpace = Math.Min(minWhiteSpace, i);
                                break;
                            }
                        }
                    }

                    StringBuilder newLines = new StringBuilder();
                    newLines.Append(indentationLevel);
                    newLines.Append(lines[0]);
                    if (decorators != null) {
                        newLines.Append("\r\n");
                        newLines.Append(indentationLevel);
                        newLines.Append(lines[1]);
                    }

                    // don't include a bunch of blank lines...
                    int endLine = lines.Length - 1;
                    for (; endLine >= 0 && String.IsNullOrWhiteSpace(lines[endLine]); endLine--) {
                    }

                    newLines.Append("\r\n");
                    for (int curLine = decorators == null ? 1 : 2; curLine <= endLine; curLine++) {
                        var line = lines[curLine];

                        newLines.Append(indentationLevel);
                        if (_insertTabs) {
                            newLines.Append('\t');
                        } else {
                            newLines.Append(' ', _indentSize);
                        }

                        if (line.Length > minWhiteSpace) {
                            newLines.Append(line, minWhiteSpace, line.Length - minWhiteSpace);
                        }
                        newLines.Append("\r\n");
                    }
                    newLines.Append("\r\n");
                    method = newLines.ToString();
                    break;
                }
            }

            string comma;
            if (_outputVars.Count > 0) {
                comma = "";
                foreach (var outputVar in _outputVars) {
                    newCall.Append(comma);
                    newCall.Append(outputVar.Name);
                    comma = ", ";
                }
                newCall.Append(" = ");
            } else if (_target.ContainsReturn) {
                newCall.Append("return ");
            }

            if (info.TargetScope is ClassDefinition) {
                var fromScope = _scopes[_scopes.Length - 1] as FunctionDefinition;
                Debug.Assert(fromScope != null);  // we don't allow extracting from classes, so we have to be coming from a function

                if (isStaticMethod) {
                    newCall.Append(info.TargetScope.Name);
                    newCall.Append('.');
                } else if (fromScope.Parameters.Count > 0) {
                    newCall.Append(fromScope.Parameters[0].Name);
                    newCall.Append('.');
                }
            }

            newCall.Append(info.Name);
            newCall.Append('(');

            comma = "";
            foreach (var param in parameters) {
                if (param.Name != selfParam) {
                    newCall.Append(comma);
                    newCall.Append(param.Name);
                    comma = ", ";
                }
            }

            newCall.Append(')');

            return new ExtractMethodResult(
                method,
                newCall.ToString()
            );
        }
예제 #7
0
 public override bool Walk(ReturnStatement node)
 {
     UpdateChildRanges(node);
     return base.Walk(node);
 }
예제 #8
0
 // ReturnStatement
 public override bool Walk(ReturnStatement node)
 {
     return ShouldWalkWorker(node);
 }
예제 #9
0
 public override void PostWalk(ReturnStatement node)
 {
     PostWalkWorker(node);
 }
예제 #10
0
 public override bool Walk(ReturnStatement node)
 {
     Returns = true;
     ContainsReturn = true;
     return base.Walk(node);
 }