summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorOskari Timperi <oskari.timperi@iki.fi>2015-12-10 19:28:45 +0200
committerOskari Timperi <oskari.timperi@iki.fi>2015-12-10 19:28:45 +0200
commita6285451de83de2aee777322f62fafeccea283da (patch)
tree8efe7f7bef5921b9a1f72718f0f463d531052915
parent2e8e6b243c329e4bcfe0bf7e66cf0a778740dede (diff)
downloadlbasi-a6285451de83de2aee777322f62fafeccea283da.tar.gz
lbasi-a6285451de83de2aee777322f62fafeccea283da.zip
TInterpreter: add Factor() and make Expr cleaner
-rw-r--r--calc1.pas74
1 files changed, 34 insertions, 40 deletions
diff --git a/calc1.pas b/calc1.pas
index fd52e45..9819c54 100644
--- a/calc1.pas
+++ b/calc1.pas
@@ -54,6 +54,7 @@ type
procedure Error;
procedure Eat(T: TokenType);
+ function Factor: Integer;
function Expr: Integer;
end;
@@ -194,53 +195,46 @@ begin
Error;
end;
-function TInterpreter.Expr: Integer;
+
+function TInterpreter.Factor: Integer;
var
- Left, Op, Right: Token;
+ T: Token;
begin
- CurrentToken := Lexer.GetNextToken;
-
- Left := CurrentToken;
+ T := CurrentToken;
Eat(TT_Integer);
+ Result := TokenInteger(T).Val;
+end;
- Op := CurrentToken;
+function TInterpreter.Expr: Integer;
+var
+ Tok: Token;
+begin
+ Result := Factor;
- while (Op.TokenType = TT_Plus) or (Op.TokenType = TT_Minus) do
+ while CurrentToken.TokenType in [TT_Asterisk, TT_Slash, TT_Plus, TT_Minus] do
begin
- Eat(Op.TokenType);
-
- Right := CurrentToken;
- Eat(TT_Integer);
-
- if Op.TokenType = TT_Plus then
- Result := TokenInteger(Left).Val + TokenInteger(Right).Val
- else
- Result := TokenInteger(Left).Val - TokenInteger(Right).Val;
-
- TokenInteger(Left).Val := Result;
-
- Op := CurrentToken;
-
- if Op.TokenType = TT_Eof then
- Exit;
+ Tok := CurrentToken;
+ if Tok.TokenType = TT_Asterisk then
+ begin
+ Eat(TT_Asterisk);
+ Result := Result * Factor;
+ end
+ else if Tok.TokenType = TT_Slash then
+ begin
+ Eat(TT_Slash);
+ Result := Round(Result / Factor);
+ end
+ else if Tok.TokenType = TT_Plus then
+ begin
+ Eat(TT_Plus);
+ Result := Round(Result + Factor);
+ end
+ else if Tok.TokenType = TT_Minus then
+ begin
+ Eat(TT_Minus);
+ Result := Round(Result - Factor);
+ end;
end;
-
- if Op.TokenType = TT_Asterisk then
- Eat(TT_Asterisk)
- else
- Eat(TT_Slash);
-
- Right := CurrentToken;
- Eat(TT_Integer);
-
- if Op.TokenType = TT_Plus then
- Result := TokenInteger(Left).Val + TokenInteger(Right).Val
- else if Op.TokenType = TT_Minus then
- Result := TokenInteger(Left).Val - TokenInteger(Right).Val
- else if Op.TokenType = TT_Asterisk then
- Result := TokenInteger(Left).Val * TokenInteger(Right).Val
- else
- Result := Round(TokenInteger(Left).Val / TokenInteger(Right).Val);
end;
var