1 | using HeuristicLab.Algorithms.PushGP.Interpreter;
|
---|
2 | using HeuristicLab.Algorithms.PushGP.Stack;
|
---|
3 |
|
---|
4 | namespace HeuristicLab.Algorithms.PushGP.Expressions
|
---|
5 | {
|
---|
6 | public abstract class LoopExpression : Expression
|
---|
7 | {
|
---|
8 | public long destinationIndex;
|
---|
9 | public long currentIndex;
|
---|
10 | public long incrementor;
|
---|
11 | public bool pushCurrentIndex = false;
|
---|
12 | public Expression body;
|
---|
13 |
|
---|
14 | public LoopExpression(string stringRepresentation) : base(stringRepresentation) { }
|
---|
15 |
|
---|
16 | protected void Eval(IInterpreter interpreter, IStack<Expression> sourceStack)
|
---|
17 | {
|
---|
18 | // if not initialized
|
---|
19 | if (body == null)
|
---|
20 | {
|
---|
21 | if (this.HasInsufficientArguments(interpreter, sourceStack))
|
---|
22 | {
|
---|
23 | return;
|
---|
24 | }
|
---|
25 |
|
---|
26 | this.InitState(interpreter, sourceStack);
|
---|
27 |
|
---|
28 | interpreter.ExecStack.Push(this, this.body);
|
---|
29 |
|
---|
30 | return;
|
---|
31 | }
|
---|
32 |
|
---|
33 | // if loop end reached
|
---|
34 | if (destinationIndex == currentIndex)
|
---|
35 | {
|
---|
36 | this.PushLastIteration(interpreter);
|
---|
37 | this.Clear();
|
---|
38 |
|
---|
39 | return;
|
---|
40 | }
|
---|
41 |
|
---|
42 | this.PushIteration(interpreter);
|
---|
43 | this.currentIndex += this.incrementor;
|
---|
44 | }
|
---|
45 |
|
---|
46 | protected virtual void Clear()
|
---|
47 | {
|
---|
48 | this.body = null;
|
---|
49 | }
|
---|
50 |
|
---|
51 | protected virtual void PushIteration(IInterpreter interpreter)
|
---|
52 | {
|
---|
53 | interpreter.IntegerStack.Push(this.currentIndex);
|
---|
54 | interpreter.ExecStack.Push(this, this.body);
|
---|
55 | }
|
---|
56 |
|
---|
57 | protected virtual void PushLastIteration(IInterpreter interpreter)
|
---|
58 | {
|
---|
59 | interpreter.IntegerStack.Push(this.currentIndex);
|
---|
60 | interpreter.ExecStack.Push(this.body);
|
---|
61 | }
|
---|
62 |
|
---|
63 | public override bool Equals(object obj)
|
---|
64 | {
|
---|
65 | if (!base.Equals(obj))
|
---|
66 | {
|
---|
67 | return false;
|
---|
68 | }
|
---|
69 |
|
---|
70 | var other = obj as LoopExpression;
|
---|
71 |
|
---|
72 | var isBodyEqual =
|
---|
73 | (this.body == null && other.body == null) ||
|
---|
74 | (this.body != null && other.body != null && this.body.Equals(other.body));
|
---|
75 |
|
---|
76 | return isBodyEqual &&
|
---|
77 | this.currentIndex == other.currentIndex &&
|
---|
78 | this.destinationIndex == other.destinationIndex &&
|
---|
79 | this.incrementor == other.incrementor;
|
---|
80 | }
|
---|
81 |
|
---|
82 | protected abstract bool HasInsufficientArguments(IInterpreter interpreter, IStack<Expression> sourceStack);
|
---|
83 | protected abstract void InitState(IInterpreter interpreter, IStack<Expression> sourceStack);
|
---|
84 | }
|
---|
85 | }
|
---|