|
| 1 | +package com.annimon.ownlang.parser.ast; |
| 2 | + |
| 3 | +import com.annimon.ownlang.lib.ArrayValue; |
| 4 | +import com.annimon.ownlang.lib.MapValue; |
| 5 | +import com.annimon.ownlang.lib.Types; |
| 6 | +import com.annimon.ownlang.lib.Value; |
| 7 | +import com.annimon.ownlang.lib.Variables; |
| 8 | +import java.util.Iterator; |
| 9 | +import java.util.List; |
| 10 | +import java.util.Map; |
| 11 | + |
| 12 | +/** |
| 13 | + * |
| 14 | + * @author aNNiMON |
| 15 | + */ |
| 16 | +public final class DestructuringAssignmentStatement implements Statement { |
| 17 | + |
| 18 | + public final List<String> variables; |
| 19 | + public final Expression containerExpression; |
| 20 | + |
| 21 | + public DestructuringAssignmentStatement(List<String> arguments, Expression container) { |
| 22 | + this.variables = arguments; |
| 23 | + this.containerExpression = container; |
| 24 | + } |
| 25 | + |
| 26 | + @Override |
| 27 | + public void execute() { |
| 28 | + final Value container = containerExpression.eval(); |
| 29 | + switch (container.type()) { |
| 30 | + case Types.ARRAY: |
| 31 | + execute((ArrayValue) container); |
| 32 | + break; |
| 33 | + case Types.MAP: |
| 34 | + execute((MapValue) container); |
| 35 | + break; |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + private void execute(ArrayValue array) { |
| 40 | + final int size = variables.size(); |
| 41 | + for (int i = 0; i < size; i++) { |
| 42 | + final String variable = variables.get(i); |
| 43 | + if (variable != null) { |
| 44 | + Variables.set(variable, array.get(i)); |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | + private void execute(MapValue map) { |
| 49 | + int i = 0; |
| 50 | + for (Map.Entry<Value, Value> entry : map) { |
| 51 | + final String variable = variables.get(i); |
| 52 | + if (variable != null) { |
| 53 | + Variables.set(variable, new ArrayValue( |
| 54 | + new Value[] { entry.getKey(), entry.getValue() } |
| 55 | + )); |
| 56 | + } |
| 57 | + i++; |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + @Override |
| 62 | + public void accept(Visitor visitor) { |
| 63 | + visitor.visit(this); |
| 64 | + } |
| 65 | + |
| 66 | + @Override |
| 67 | + public String toString() { |
| 68 | + return variables.toString(); |
| 69 | + } |
| 70 | +} |
0 commit comments