Skip to content

Instantly share code, notes, and snippets.

@stevenroose
Last active August 29, 2015 14:01
Show Gist options
  • Save stevenroose/22f5ff41f3faf0c3e23e to your computer and use it in GitHub Desktop.
Save stevenroose/22f5ff41f3faf0c3e23e to your computer and use it in GitHub Desktop.
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