diff src/luan/impl/LuanParser.java @ 1520:d9a5405a3102

try statement
author Franklin Schmidt <fschmidt@gmail.com>
date Sun, 21 Jun 2020 18:14:13 -0600
parents 6c830be6be98
children d4407e8de707
line wrap: on
line diff
--- a/src/luan/impl/LuanParser.java	Fri Jun 19 20:10:47 2020 -0600
+++ b/src/luan/impl/LuanParser.java	Sun Jun 21 18:14:13 2020 -0600
@@ -322,6 +322,7 @@
 			|| (stmt=WhileStmt()) != null
 			|| (stmt=RepeatStmt()) != null
 			|| (stmt=IfStmt()) != null
+			|| (stmt=TryStmt()) != null
 			|| (stmt=SetStmt()) != null
 			|| (stmt=ExpressionsStmt()) != null
 		) {
@@ -481,7 +482,7 @@
 		Expr expr = RequiredExpr().single();
 		RequiredKeyword("do");
 
-		String fnVar = "fn"+ ++forCounter;
+		String fnVar = "fn" + ++forCounter;
 		Expr fnExp = new Expr(null,false);
 		fnExp.add( fnVar + ".call()" );
 		Stmts stmt = new Stmts();
@@ -591,7 +592,7 @@
 		parser.begin();
 		if( !Keyword("repeat") )
 			return parser.failure(null);
-		Stmts loop =RequiredLoopBlock();
+		Stmts loop = RequiredLoopBlock();
 		RequiredKeyword("until");
 		Expr cnd = RequiredExpr().single();
 		Stmts stmt = new Stmts();
@@ -653,6 +654,42 @@
 		return parser.success( stmt );
 	}
 
+	int catchCounter = 0;
+
+	private Stmts TryStmt() throws ParseException {
+		parser.begin();
+		if( !Keyword("try") )
+			return parser.failure(null);
+		Stmts tryBlock = RequiredBlock();
+		Stmts catchBlock = null;
+		Stmts finallyBlock = null;
+		Stmts stmt = new Stmts();
+		stmt.add( "try {  LuanImpl.nopTry();  " );
+		stmt.addAll( tryBlock );
+		if( Keyword("catch") ) {
+			String name = Name();
+			Expr exp = new Expr(Val.SINGLE,false);
+			String var = "e" + ++catchCounter;
+			exp.add( var+".table(luan)" );
+			stmt.add( "} catch(LuanException "+var+") {  " );
+			stmt.addAll( addSymbol(name,exp) );
+			catchBlock = RequiredBlock();
+			stmt.addAll( catchBlock );
+			popSymbols(1);
+		}
+		if( Keyword("finally") ) {
+			finallyBlock = RequiredBlock();
+			stmt.add( "} finally {  " );
+			stmt.addAll( finallyBlock );
+		}
+		RequiredEnd("end_try");
+		if( catchBlock==null && finallyBlock==null )
+			stmt.add( "} finally {  " );
+		stmt.add( "}  " );
+		stmt.hasReturn = finallyBlock!=null && finallyBlock.hasReturn || tryBlock.hasReturn && (catchBlock==null || catchBlock.hasReturn);
+		return parser.success( stmt );
+	}
+
 	private Stmts SetStmt() throws ParseException {
 		parser.begin();
 		List<Var> vars = new ArrayList<Var>();
@@ -1467,6 +1504,7 @@
 	private static final Set<String> keywords = new HashSet<String>(Arrays.asList(
 		"and",
 		"break",
+		"catch",
 		"continue",
 		"do",
 		"else",
@@ -1476,8 +1514,10 @@
 		"end_for",
 		"end_function",
 		"end_if",
+		"end_try",
 		"end_while",
 		"false",
+		"finally",
 		"for",
 		"function",
 		"goto",