@@ -772,7 +772,7 @@ String maybeMangleAndAddName(String name) {
772772 public BytecodeDSLCompilerResult visit (ModTy .Module node ) {
773773 return compileRootNode ("<module>" , ArgumentInfo .NO_ARGS , node .getSourceRange (), b -> {
774774 beginRootNode (node , null , b );
775- visitModuleBody (node .body , b );
775+ visitModuleBody (node .body , b , true );
776776 endRootNode (b );
777777 });
778778 }
@@ -792,12 +792,12 @@ public BytecodeDSLCompilerResult visit(ModTy.Expression node) {
792792 public BytecodeDSLCompilerResult visit (ModTy .Interactive node ) {
793793 return compileRootNode ("<module>" , ArgumentInfo .NO_ARGS , node .getSourceRange (), b -> {
794794 beginRootNode (node , null , b );
795- visitModuleBody (node .body , b );
795+ visitModuleBody (node .body , b , false );
796796 endRootNode (b );
797797 });
798798 }
799799
800- private void visitModuleBody (StmtTy [] body , Builder b ) {
800+ private void visitModuleBody (StmtTy [] body , Builder b , boolean returnLastStmt ) {
801801 if (body != null ) {
802802 if (containsAnnotations (body )) {
803803 b .emitSetupAnnotations ();
@@ -834,33 +834,30 @@ private void visitModuleBody(StmtTy[] body, Builder b) {
834834 endStoreLocal ("__doc__" , b );
835835 }
836836 }
837- if (i == body .length ) {
838- // Special case: module body just consists of a docstring.
837+
838+ for (; i < body .length - 1 ; i ++) {
839+ body [i ].accept (statementCompiler );
840+ }
841+
842+ /*
843+ * To support interop eval we need to return the value of the last statement even if
844+ * we're in file mode. Also used when parsing with arguments. Note that if there is
845+ * only a doc string, although we normally skip it, here we use it as a return
846+ * value.
847+ */
848+ StmtTy lastStatement = body [body .length - 1 ];
849+ if (returnLastStmt && lastStatement instanceof StmtTy .Expr expr ) {
850+ // Return the value of the last statement for interop eval.
851+ beginReturn (b );
852+ boolean closeTag = beginSourceSection (expr , b );
853+ expr .value .accept (statementCompiler );
854+ endSourceSection (b , closeTag );
855+ endReturn (b );
856+ } else {
857+ lastStatement .accept (statementCompiler );
839858 beginReturn (b );
840859 b .emitLoadConstant (PNone .NONE );
841860 endReturn (b );
842- return ;
843- }
844-
845- for (; i < body .length ; i ++) {
846- StmtTy bodyNode = body [i ];
847- if (i == body .length - 1 ) {
848- if (bodyNode instanceof StmtTy .Expr expr ) {
849- // Return the value of the last statement for interop eval.
850- beginReturn (b );
851- boolean closeTag = beginSourceSection (expr , b );
852- expr .value .accept (statementCompiler );
853- endSourceSection (b , closeTag );
854- endReturn (b );
855- } else {
856- bodyNode .accept (statementCompiler );
857- beginReturn (b );
858- b .emitLoadConstant (PNone .NONE );
859- endReturn (b );
860- }
861- } else {
862- bodyNode .accept (statementCompiler );
863- }
864861 }
865862 }
866863 } else {
0 commit comments