Last active
August 29, 2015 14:01
-
-
Save stevenroose/22f5ff41f3faf0c3e23e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public abstract class Statement { | |
public void execute(Map<String, Type> context); | |
/** | |
* Updates the global context with the changes made in the local scope. | |
* Variables newly created in the scope are discarded. | |
*/ | |
protected void updateContext(Map<String, Type> context, Map<String, Type> scopeContext) { | |
for(String key : context.keySet()) { | |
context.put(key, scopeContext.get(key)); | |
} | |
} | |
/** | |
* Executes the given statement in a local scope. | |
* The variables in the context can be accessed and updates, but newly created variables will be discarded. | |
*/ | |
protected void executeWithScope(Statement statement, Map<String, Type> context) { | |
Map<String, Type> scopeContext = context.clone(); | |
statement.execute(scopeContext); | |
updateContext(context, scopeContext); | |
} | |
} | |
public class WhileStatement extends Statement{ | |
private Statement body; | |
private Expression condition; | |
public WhileStatement(Expression condition, Statement body){ | |
this.body = body; | |
this.condition = condition; | |
} | |
@Override | |
public void execute(){ | |
while (((BooleanType) condition.evaluate()).getValue()) { | |
executeWithScope(body, context); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment