11package org .piccode .ast ;
22
3+ import java .util .function .Function ;
4+ import java .util .function .Supplier ;
5+ import org .antlr .v4 .runtime .Token ;
36import org .piccode .piccodescript .TargetEnvironment ;
7+ import org .piccode .rt .Context ;
8+ import org .piccode .rt .PiccodeException ;
9+ import org .piccode .rt .PiccodeReturnException ;
410import org .piccode .rt .PiccodeValue ;
511
612/**
@@ -13,6 +19,58 @@ public abstract class Ast {
1319 public abstract PiccodeValue execute (Integer frame );
1420 public abstract String codeGen (TargetEnvironment target );
1521
22+
23+ public static PiccodeValue safeExecute (Integer frame , Ast expr , Function <Ast , PiccodeValue > func ) {
24+ var ctx = frame == null
25+ ? Context .top
26+ : Context .getContextAt (frame );
27+
28+ try {
29+ ctx .pushStackFrame (expr );
30+ var result = func .apply (expr );
31+ ctx .dropStackFrame ();
32+ return result ;
33+ } catch (PiccodeReturnException ret ) {
34+ ctx .dropStackFrame ();
35+ return ret .value ;
36+ } catch (PiccodeException exception ) {
37+ throw exception ;
38+ }
39+ }
40+
41+ public static PiccodeValue safeExecute (Integer frame , Supplier <PiccodeValue > fx ) {
42+ var ctx = frame == null
43+ ? Context .top
44+ : Context .getContextAt (frame );
45+ ctx .pushScope ();
46+ try {
47+ var result = fx .get ();
48+ ctx .dropScope ();
49+ return result ;
50+ }
51+ catch (PiccodeReturnException ret ) {
52+ ctx .dropScope ();
53+ return ret .value ;
54+ } catch (PiccodeException exception ) {
55+ ctx .dropScope ();
56+ throw exception ;
57+ }
58+ }
59+
60+ public static Ast finalizeNode (Ast node , Ast other ) {
61+ node .file = other .file ;
62+ node .line = other .line ;
63+ node .column = other .column ;
64+ return node ;
65+ }
66+
67+
68+ public static Ast finalizeNode (Ast node , Token token ) {
69+ node .line = token .getLine ();
70+ node .column = token .getCharPositionInLine ();
71+ return node ;
72+ }
73+
1674 public static class Location {
1775 public int line ;
1876 public int col ;
@@ -23,6 +81,8 @@ public Location(int line, int col) {
2381 }
2482 }
2583
84+
85+
2686 public static Location getLocation (Ast node ) {
2787 if (node instanceof IdentifierAst id ) {
2888 return new Location (id .line , id .column );
0 commit comments