ZetCode

A calculator in Pascal

last modified November 19, 2026 Free Pascal 3.2.2

A recursive-descent parser is the standard way to evaluate an arithmetic expression. It reads one token at a time, follows a grammar in which each function handles one precedence level, and returns a number. The whole calculator fits in about a hundred lines of Pascal: a tokenizer, four parsing functions, a case statement for the operators, and an exception handler for bad input. This article builds it step by step.

The grammar

The grammar has three levels. An expression is a sequence of terms joined by + and -; a term is a sequence of factors joined by * and /; and a factor is a number, a parenthesized expression, or a negated factor. Because a factor can contain parentheses that contain an expression, the parser is recursive.

expression := term { ("+" | "-") term }
term       := factor { ("*" | "/") factor }
factor     := "-" factor | number | "(" expression ")"

The braces mean "zero or more repetitions". This grammar already encodes precedence: multiplication binds tighter than addition because a term is parsed before the plus sign is considered, and parentheses override the order. Left associativity falls out of the loops: 10 - 3 - 2 is parsed as (10 - 3) - 2, not as 10 - (3 - 2).

Turning text into tokens

The tokenizer skips spaces, groups digits and decimal points into a number, and maps each operator character to an enumeration value. It keeps the position of the token so an error can point at the offending character. The program below prints the tokens of a sample expression.

tokens.pas
program tokens;
{$mode objfpc}{$H+}

uses
  SysUtils;

type
  TKind = (tkNumber, tkPlus, tkMinus, tkStar, tkSlash,
    tkLParen, tkRParen, tkEnd);

const
  KindName: array[TKind] of string = ('number', 'plus', 'minus',
    'star', 'slash', 'lparen', 'rparen', 'end');

var
  S: string;
  I, Start: Integer;
  Kind: TKind;
  Number: Double;

begin
  S := '12 + 3.5 * (4 - 1)';
  I := 1;
  while I <= Length(S) do
  begin
    if S[I] = ' ' then
      Inc(I)
    else if S[I] in ['0'..'9', '.'] then
    begin
      Start := I;
      while (I <= Length(S)) and (S[I] in ['0'..'9', '.']) do
        Inc(I);
      Number := StrToFloat(Copy(S, Start, I - Start));
      WriteLn(KindName[tkNumber], ': ', Number:0:1);
    end
    else
    begin
      case S[I] of
        '+': Kind := tkPlus;
        '-': Kind := tkMinus;
        '*': Kind := tkStar;
        '/': Kind := tkSlash;
        '(': Kind := tkLParen;
        ')': Kind := tkRParen;
      else
        raise Exception.CreateFmt('unexpected %s at %d', [S[I], I]);
      end;
      WriteLn(KindName[Kind]);
      Inc(I);
    end;
  end;
  WriteLn(KindName[tkEnd]);
end.

The number loop accepts more than one decimal point, so 1.2.3 reaches StrToFloat and raises EConvertError; the full parser adds a stricter check. The KindName array uses the enumeration type as its index type, which keeps the names and the values in step. The tokenizer is a separate pass here for clarity; the calculator below produces tokens on demand.

$ fpc -gl tokens.pas
$ ./tokens
number: 12.0
plus
number: 3.5
star
lparen
number: 4.0
minus
number: 1.0
rparen
end

The parser

The calculator keeps three global values: the source text, a cursor into it, and the current token. NextToken advances the cursor and fills the token; each parsing function looks at the current token, consumes it, and calls the next level. The result of the whole expression is printed with four decimals.

calc.pas
program calc;
{$mode objfpc}{$H+}

uses
  SysUtils;

type
  TKind = (tkNumber, tkPlus, tkMinus, tkStar, tkSlash,
    tkLParen, tkRParen, tkEnd);
  TToken = record
    Kind: TKind;
    Value: Double;
    Position: Integer;
  end;

var
  Source: string;
  Cursor: Integer;
  Token: TToken;

procedure NextToken;
var
  Start: Integer;
begin
  while (Cursor <= Length(Source)) and (Source[Cursor] = ' ') do
    Inc(Cursor);
  Token.Position := Cursor;
  if Cursor > Length(Source) then
  begin
    Token.Kind := tkEnd;
    Exit;
  end;
  case Source[Cursor] of
    '+': begin Token.Kind := tkPlus; Inc(Cursor); end;
    '-': begin Token.Kind := tkMinus; Inc(Cursor); end;
    '*': begin Token.Kind := tkStar; Inc(Cursor); end;
    '/': begin Token.Kind := tkSlash; Inc(Cursor); end;
    '(': begin Token.Kind := tkLParen; Inc(Cursor); end;
    ')': begin Token.Kind := tkRParen; Inc(Cursor); end;
  else
    if Source[Cursor] in ['0'..'9', '.'] then
    begin
      Start := Cursor;
      while (Cursor <= Length(Source)) and
            (Source[Cursor] in ['0'..'9', '.']) do
        Inc(Cursor);
      Token.Kind := tkNumber;
      Token.Value := StrToFloat(Copy(Source, Start, Cursor - Start));
    end
    else
      raise Exception.CreateFmt('unexpected character "%s" at %d',
        [Source[Cursor], Cursor]);
  end;
end;

function ParseExpression: Double; forward;

function ParseFactor: Double;
begin
  Result := 0;
  if Token.Kind = tkMinus then
  begin
    NextToken;
    Result := -ParseFactor;
  end
  else if Token.Kind = tkNumber then
  begin
    Result := Token.Value;
    NextToken;
  end
  else if Token.Kind = tkLParen then
  begin
    NextToken;
    Result := ParseExpression;
    if Token.Kind <> tkRParen then
      raise Exception.CreateFmt('missing ")" at %d', [Token.Position]);
    NextToken;
  end
  else
    raise Exception.CreateFmt('expected a number at %d', [Token.Position]);
end;

function ParseTerm: Double;
var
  Op: TKind;
begin
  Result := ParseFactor;
  while Token.Kind in [tkStar, tkSlash] do
  begin
    Op := Token.Kind;
    NextToken;
    if Op = tkStar then
      Result := Result * ParseFactor
    else
      Result := Result / ParseFactor;
  end;
end;

function ParseExpression: Double;
var
  Op: TKind;
begin
  Result := ParseTerm;
  while Token.Kind in [tkPlus, tkMinus] do
  begin
    Op := Token.Kind;
    NextToken;
    if Op = tkPlus then
      Result := Result + ParseTerm
    else
      Result := Result - ParseTerm;
  end;
end;

begin
  if ParamCount > 0 then
    Source := ParamStr(1)
  else
    Source := '2 + 3 * 4';
  try
    Cursor := 1;
    NextToken;
    WriteLn(Source, ' = ', ParseExpression:0:4);
    if Token.Kind <> tkEnd then
      raise Exception.CreateFmt('unexpected input at %d', [Token.Position]);
  except
    on E: Exception do
    begin
      WriteLn('error: ', E.Message);
      ExitCode := 1;
    end;
  end;
end.

ParseFactor is declared before ParseTerm, but it calls ParseExpression, which is declared later; the forward declaration above ParseFactor breaks the cycle. The unary minus is handled in ParseFactor, so -2 * 3 negates the two and then multiplies. The expression is printed before it is evaluated, which is why the output line repeats the input.

$ fpc -gl calc.pas
$ ./calc
2 + 3 * 4 = 14.0000
$ ./calc "12 + 3.5 * (4 - 1)"
12 + 3.5 * (4 - 1) = 22.5000

Precedence and associativity

Each parsing function is one precedence level, and the loop in that function makes the operators left-associative. The table below shows how a few expressions are grouped. The parentheses are not part of the input; they show the tree the parser builds.

InputGroupingResult
2 + 3 * 42 + (3 * 4)14
(2 + 3) * 4(2 + 3) * 420
10 - 3 - 2(10 - 3) - 25
-2 * 3(-2) * 3-6
8 / 4 / 2(8 / 4) / 21

To add a right-associative operator, such as exponentiation, the recursive call must come before the loop consumes the operator, or the loop must call the same level again. The current structure deliberately keeps all binary operators on the left, which is what a calculator keypad does.

Errors

Every error is an exception with a position. The main block catches it, prints the message, and sets ExitCode to 1, so a shell can tell a successful calculation from a failed one. The parser stops at the first error; it does not try to recover and continue.

Division by zero is caught by the floating-point runtime, not by the parser, so its message names the arithmetic operation rather than a position. A missing parenthesis is reported at the position of the token that should have been ), which is the end of the input in the example. The final echo shows the exit status left by the last failed run.

$ ./calc "2 / 0"
2 / 0 = error: Floating point division by zero
$ ./calc "(2 + 3"
(2 + 3 = error: missing ")" at 7
$ ./calc "2 ## 3"
2 ## 3 = error: unexpected character "#" at 3
$ echo $?
1

Extending the calculator

Variables turn the evaluator into an interpreter: add a token kind for identifiers, keep a TDictionary<string, Double> for values, and handle = at the lowest precedence. Function calls need a lookahead token and a table of names, but the recursive structure stays the same. A history of previous expressions can be kept in a TStringList.

The procedural types article shows how to store the operators in a dispatch table instead of a case, and the string processing article covers the tokenizer routines in more detail.

Source

Recursive descent parser on Wikipedia

Free Pascal Reference guide

In this article we wrote a tokenizer, a recursive-descent parser with three precedence levels, a case statement for the operators, and an exception handler that reports the position of an error. The recursion article explains the call structure, and the strings article covers the text operations used by the tokenizer.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Pascal tutorials.