Commit 24a5b0c3 authored by Cullen Rhodes's avatar Cullen Rhodes

Improve REPL support

This fixes a bug with expressions inside loops in interactive mode
that resulted in expressions not being printed:

    >> for i in range(3):
    ...    i
    ...
    >>

Python prints the value every iteration:

    >> for i in range(3):
    ...    i
    ...
    0
    1
    2
    >>>

The same also applies to while loops.
parent 74ee55c8
......@@ -61,6 +61,8 @@ private:
InternedStringPool* pool = NULL;
int loop_depth = 0;
int in_finally = 0;
int interactive = 0;
int nestlevel = 0;
llvm::StringRef fn;
public:
......@@ -511,7 +513,9 @@ public:
auto v = stmt->v.FunctionDef;
r->name = convert(v.name);
r->args = convert(v.args, r);
nestlevel++;
r->body = convert<stmt_ty, AST_stmt*>(v.body);
nestlevel--;
r->decorator_list = convert<expr_ty, AST_expr*>(v.decorator_list);
return r;
}
......@@ -520,7 +524,9 @@ public:
auto v = stmt->v.ClassDef;
r->name = convert(v.name);
r->bases = convert<expr_ty, AST_expr*>(v.bases);
nestlevel++;
r->body = convert<stmt_ty, AST_stmt*>(v.body);
nestlevel--;
r->decorator_list = convert<expr_ty, AST_expr*>(v.decorator_list);
return r;
}
......@@ -666,6 +672,11 @@ public:
auto r = new AST_Expr();
auto v = stmt->v.Expr;
r->value = convert(v.value);
if (interactive && nestlevel <= 0) {
auto print_expr = new AST_LangPrimitive(AST_LangPrimitive::PRINT_EXPR);
print_expr->args.push_back(r->value);
r->value = print_expr;
}
return r;
}
case Pass_kind:
......@@ -704,11 +715,11 @@ public:
return rtn;
}
case Interactive_kind: {
this->interactive = 1;
AST_Module* rtn = new AST_Module(llvm::make_unique<InternedStringPool>());
assert(!this->pool);
this->pool = rtn->interned_strings.get();
convertAll<stmt_ty>(mod->v.Interactive.body, rtn->body);
makeModuleInteractive(rtn);
return rtn;
}
case Expression_kind: {
......
......@@ -2236,17 +2236,4 @@ void flatten(AST_expr* root, std::vector<AST*>& output, bool expand_scopes) {
root->accept(&visitor);
}
void makeModuleInteractive(AST_Module* m) {
for (int i = 0; i < m->body.size(); ++i) {
AST_stmt* s = m->body[i];
if (s->type != AST_TYPE::Expr)
continue;
AST_Expr* expr = (AST_Expr*)s;
AST_LangPrimitive* print_expr = new AST_LangPrimitive(AST_LangPrimitive::PRINT_EXPR);
print_expr->args.push_back(expr->value);
expr->value = print_expr;
}
}
}
......@@ -1444,10 +1444,6 @@ template <class T, class R> void findNodes(const R& roots, std::vector<T*>& outp
}
}
// Take a normally-parsed module, and convert it (inplace) to a form that will print out any bare expressions.
// This is used for "single" mode or the repl.
void makeModuleInteractive(AST_Module* m);
llvm::StringRef getOpSymbol(int op_type);
BORROWED(BoxedString*) getOpName(int op_type);
int getReverseCmpOp(int op_type, bool& success);
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment