Arithmetic evaluation: Difference between revisions

Updated D entry
(Updated D entry)
Line 792:
T[] data;
alias data this;
void push(T top) pure nothrow @safe { data ~= top; }
 
T pop(bool discard = true)() pure @nogc @safe {
immutable static exc = new immutable(Exception)("Stack Empty");
if (data.empty)
Line 809:
immutable opPrec = [ 0, -9, -9, 1, 1, 2, 2];
 
abstract class Visitor { void visit(XP e) pure @safe; }
 
final class XP {
Line 817:
XP LHS, RHS;
 
this(string s=")", int p = -1) pure nothrow @safe {
str = s;
pos = p;
Line 827:
}
 
override int opCmp(Object other) pure @safe {
auto rhs = cast(XP)other;
enforce(rhs !is null);
Line 833:
}
 
void accept(Visitor v) pure @safe { v.visit(this); }
}
 
Line 842:
int xpHead, xpTail;
 
void joinXP(XP x) pure @safe {
x.RHS = num.pop;
x.LHS = num.pop;
Line 848:
}
 
string nextToken() pure @safe {
while (xpHead < xpr.length && xpr[xpHead] == ' ')
xpHead++; // Skip spc.
Line 871:
} // End nextToken.
 
AST parse(in string s) /*@safe*/ {
bool expectingOP;
xpr = s;
Line 936:
// To display AST fancy struct.
void ins(ref char[][] s, in string v, in int p, in int l)
pure nothrow @safe {
if (l + 1 > s.length)
s.length++;
Line 949:
char[][] Tree;
 
static void opCall(AST a) @safe {
if (a && a.root) {
auto c = new CalcVis;
Line 976:
 
// Calc. the value, display AST struct and eval order.
override void visit(XP xp) @safe {
ins(Tree, xp.str, xp.pos, level);
level++;
Line 1,001:
}
 
void main(string[] args) /*@safe*/ {
immutable exp0 = "1 + 2*(3 - 2*(3 - 2)*((2 - 4)*5" ~
" - 22/(7 + 2*(3 - 1)) - 1)) + 1";
immutable exp = (args.length > 1) ? args[1 .. $].join("' "') : exp0;
new AST().parse(exp).CalcVis; // Should be 60.
}</lang>