Skip to content

Commit 5a0be8d

Browse files
committed
Compiler: Add a method that executes all declarations and returns expressions only
1 parent fa5d33b commit 5a0be8d

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

src/main/java/org/piccode/backend/Compiler.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313
import org.piccode.ast.CallAst;
1414
import org.piccode.ast.FunctionAst;
1515
import org.piccode.ast.IdentifierAst;
16+
import org.piccode.ast.ImportAst;
17+
import org.piccode.ast.ModuleAst;
1618
import org.piccode.ast.PiccodeVisitor;
1719
import org.piccode.ast.ReturnAst;
1820
import org.piccode.ast.StatementList;
@@ -105,6 +107,44 @@ public static PiccodeValue compile(String file, String code, List<PiccodeValue>
105107
}
106108
}
107109

110+
111+
public static List<Ast> compileDeclarationsAndGetExpressions(String file, String code, List<PiccodeValue> args) {
112+
List<Ast> nodes = new ArrayList<>();
113+
try {
114+
var result = program(file, code);
115+
prepareGlobalScope(file);
116+
117+
for (var stmt : result.nodes) {
118+
if ((stmt instanceof ImportAst) || (stmt instanceof ModuleAst) || (stmt instanceof FunctionAst)) {
119+
stmt.execute(null);
120+
} else {
121+
nodes.add(stmt);
122+
}
123+
}
124+
125+
Context.top.dropStackFrame();
126+
return nodes;
127+
} catch (PiccodeReturnException ret) {
128+
if (Context.top.getFramesCount() > 0) {
129+
Context.top.dropStackFrame();
130+
}
131+
return nodes;
132+
} catch (PiccodeException e) {
133+
if (Context.top.getFramesCount() > 0) {
134+
Context.top.dropStackFrame();
135+
}
136+
e.reportError();
137+
return nodes;
138+
} catch (Exception rte) {
139+
if (Context.top.getFramesCount() > 0) {
140+
Context.top.dropStackFrame();
141+
}
142+
rte.printStackTrace();
143+
return nodes;
144+
}
145+
}
146+
147+
108148
public static List<Ast> parse(String file, String code) {
109149
return program(file, code).nodes;
110150
}

0 commit comments

Comments
 (0)