@@ -149,7 +149,56 @@ public static List<Ast> compileDeclarationsAndGetExpressions(String file, String
149149 return nodes ;
150150 }
151151 }
152+ public static PiccodeValue execute (List <Ast > nodes ) {
153+ try {
154+ PiccodeValue res = new PiccodeUnit ();
155+ var has_main = false ;
156+ for (var stmt : nodes ) {
157+ if (stmt instanceof FunctionAst func && func .name .equals ("main" ) && (func .arg == null || func .arg .isEmpty ())) {
158+ has_main = true ;
159+ }
160+
161+ if (stmt instanceof ReturnAst ret ) {
162+ res = ret .expr .execute (null );
163+ break ;
164+ }
165+ try {
166+ res = stmt .execute (null );
167+ } catch (PiccodeReturnException pre ) {
168+ res = pre .value ;
169+ } catch (Exception e ) {
170+ throw e ;
171+ }
172+ }
173+
174+ if (has_main ) {
175+ var _result = new CallAst (new IdentifierAst ("main" ), List .of ()).execute (null );
176+ return _result ;
177+ }
152178
179+ Context .top .dropStackFrame ();
180+ return res ;
181+ } catch (PiccodeReturnException ret ) {
182+ if (Context .top .getFramesCount () > 0 ) {
183+ Context .top .dropStackFrame ();
184+ }
185+ return ret .value ;
186+ } catch (PiccodeException e ) {
187+ if (Context .top .getFramesCount () > 0 ) {
188+ Context .top .dropStackFrame ();
189+ }
190+ //Context.top.dropStackFrame();
191+ e .reportError (exitOnError );
192+ //e.printStackTrace();
193+ return new PiccodeUnit ();
194+ } catch (Exception rte ) {
195+ if (Context .top .getFramesCount () > 0 ) {
196+ Context .top .dropStackFrame ();
197+ }
198+ rte .printStackTrace ();
199+ return new PiccodeUnit ();
200+ }
201+ }
153202
154203 public static List <Ast > parse (String file , String code ) {
155204 return program (file , code ).nodes ;
0 commit comments