ZetCode

Modula-2 calculator

last modified November 27, 2026 Modula-2

This article writes a calculator for arithmetic expressions such as 2 * (3.5 + 4) / -5. It puts together much of the series: records with a variant part, procedures that call each other recursively, modules and exceptions. The method, recursive descent, turns each rule of a grammar into one procedure. Niklaus Wirth used it for his Pascal and Modula-2 compilers, and it fits the language well.

The calculator works in two layers. A scanner splits the text into tokens: numbers, operators and parentheses. A parser reads the tokens, checks that they form an expression and computes its value on the way. All programs are compiled with -fiso.

The grammar

A grammar describes which texts are valid expressions. Wirth wrote his grammars in EBNF, a notation he designed: braces mean "repeated zero or more times", brackets mean "optional", and | separates alternatives.

grammar
expression = term { ("+" | "-") term } .
term       = factor { ("*" | "/") factor } .
factor     = number | "(" expression ")" | "-" factor .
number     = digit { digit } [ "." digit { digit } ] .

An expression is a sum of terms, a term a product of factors, and a factor a number, an expression in parentheses or a negated factor. The layering gives the precedence: * and / bind tighter than + and - because a term is complete before the expression looks at the next operator. The rule for a factor refers back to the expression, which is where recursion comes in. The repetitions in braces make the operators left associative, so 10 - 4 - 3 is (10 - 4) - 3.

Reading a number

The smallest part of the calculator turns a sequence of digits into a value. The program walks through a string with a position and adds one digit at a time.

number.mod
MODULE number;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
FROM SRealIO IMPORT WriteFixed;
FROM Strings IMPORT Assign;

VAR
  text: ARRAY [0..80] OF CHAR;
  pos: CARDINAL;
  value: REAL;

PROCEDURE IsDigit(ch: CHAR): BOOLEAN;
BEGIN
  RETURN (ch >= '0') AND (ch <= '9')
END IsDigit;

BEGIN
  Assign("1275+3", text);
  pos := 0;
  value := 0.0;
  WHILE IsDigit(text[pos]) DO
    value := value * 10.0 + FLOAT(ORD(text[pos]) - ORD('0'));
    INC(pos)
  END;
  WriteFixed(value, 1, 0);
  WriteString(" ends at position "); WriteCard(pos, 0); WriteLn
END number.

Each step multiplies the value read so far by ten and adds the value of the next digit, ORD(ch) - ORD('0'). The loop stops at the first character that is not a digit, here +, and pos is left on it, so the next part of the program can continue from there. The text ends with 0C, which is not a digit either, so the loop never runs past the string. The library procedures WholeStr.StrToInt and RealStr.StrToReal are not used: they need the number cut out first, and in gm2 15.2 they accept or reject the wrong strings, as the reading input article shows.

$ gm2 -fiso number.mod -o number
$ ./number
1275.0 ends at position 4

Tokens

The scanner goes into its own module. A token is a record with a variant part: a number carries its value, a bad character carries the character, and the other kinds carry nothing besides their position. The definition module declares the token and two procedures.

Scanner.def
DEFINITION MODULE Scanner;

TYPE
  Kind = (Number, Plus, Minus, Times, Divide, LParen, RParen, End, Bad);
  Token = RECORD
    pos: CARDINAL;
    CASE kind: Kind OF
      Number: value: REAL |
      Bad: ch: CHAR
    ELSE
    END
  END;

PROCEDURE Start(line: ARRAY OF CHAR);
(* Sets the text to scan and goes back to its first character. *)

PROCEDURE Next(VAR tok: Token);
(* Reads the next token; at the end of the text tok.kind is End. *)

END Scanner.

The tag field kind selects the variant. The ELSE part of the record is empty: operators, parentheses and the end of the text need no extra fields. The records article covers variant records in detail.

Scanner.mod
IMPLEMENTATION MODULE Scanner;
FROM Strings IMPORT Assign;

CONST
  Size = 256;

VAR
  text: ARRAY [0..Size] OF CHAR;
  pos: CARDINAL;

PROCEDURE Start(line: ARRAY OF CHAR);
BEGIN
  Assign(line, text);
  text[Size] := 0C;
  pos := 0
END Start;

PROCEDURE IsDigit(ch: CHAR): BOOLEAN;
BEGIN
  RETURN (ch >= '0') AND (ch <= '9')
END IsDigit;

PROCEDURE Digit(): REAL;
BEGIN
  INC(pos);
  RETURN FLOAT(ORD(text[pos - 1]) - ORD('0'))
END Digit;

PROCEDURE ReadNumber(): REAL;
VAR
  value, scale: REAL;
BEGIN
  value := 0.0;
  WHILE IsDigit(text[pos]) DO
    value := value * 10.0 + Digit()
  END;
  IF text[pos] = '.' THEN
    INC(pos);
    scale := 1.0;
    WHILE IsDigit(text[pos]) DO
      scale := scale / 10.0;
      value := value + scale * Digit()
    END
  END;
  RETURN value
END ReadNumber;

PROCEDURE Next(VAR tok: Token);
BEGIN
  WHILE text[pos] = ' ' DO
    INC(pos)
  END;
  tok.pos := pos;
  IF IsDigit(text[pos]) THEN
    tok.kind := Number;
    tok.value := ReadNumber()
  ELSE
    CASE text[pos] OF
      '+': tok.kind := Plus |
      '-': tok.kind := Minus |
      '*': tok.kind := Times |
      '/': tok.kind := Divide |
      '(': tok.kind := LParen |
      ')': tok.kind := RParen |
      0C: tok.kind := End
    ELSE
      tok.kind := Bad;
      tok.ch := text[pos]
    END;
    IF tok.kind # End THEN
      INC(pos)
    END
  END
END Next;

END Scanner.

The module keeps the text and the current position in its own variables. Start copies the line and puts 0C in the last element, so even a truncated line has an end. ReadNumber is the loop of the previous program with a fraction added: after a point, every digit is worth a tenth of the previous one. Next skips spaces, remembers where the token starts and decides its kind from the first character. At the end of the text it stays on the 0C, so every further call returns End again.

tokens.mod
MODULE tokens;
FROM STextIO IMPORT WriteString, WriteChar, WriteLn;
FROM SWholeIO IMPORT WriteCard;
FROM SRealIO IMPORT WriteFixed;
FROM Scanner IMPORT Kind, Token, Start, Next;

VAR
  tok: Token;

PROCEDURE Show(t: Token);
BEGIN
  WriteCard(t.pos, 2); WriteString("  ");
  CASE t.kind OF
    Number: WriteString("number "); WriteFixed(t.value, 2, 0) |
    Plus, Minus, Times, Divide: WriteString("operator") |
    LParen, RParen: WriteString("parenthesis") |
    End: WriteString("end of text") |
    Bad: WriteString("bad character "); WriteChar(t.ch)
  END;
  WriteLn
END Show;

BEGIN
  Start("2 * (3.5 + 40) % 1");
  REPEAT
    Next(tok);
    Show(tok)
  UNTIL tok.kind = End
END tokens.

The test program prints every token of a line with its position. FROM Scanner IMPORT Kind also brings in the values of the enumeration, so Number and Plus can be used without qualification. The % is not part of the grammar; the scanner does not decide what to do about it and returns a Bad token for the parser to report.

$ gm2 -fiso -c Scanner.mod
$ gm2 -fiso tokens.mod Scanner.o -o tokens
$ ./tokens
 0  number 2.00
 2  operator
 4  parenthesis
 5  number 3.50
 9  operator
11  number 40.00
13  parenthesis
15  bad character %
17  number 1.00
18  end of text

Sums

The parser starts with the first rule only, for now with plain numbers as operands. It keeps the current token in a variable; each procedure looks at it, decides, and calls Next when it consumes it.

sums.mod
MODULE sums;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SRealIO IMPORT WriteFixed;
FROM Scanner IMPORT Kind, Token, Start, Next;

VAR
  tok: Token;

PROCEDURE Operand(): REAL;
VAR
  value: REAL;
BEGIN
  value := tok.value;
  Next(tok);
  RETURN value
END Operand;

PROCEDURE Expression(): REAL;
VAR
  value: REAL;
BEGIN
  value := Operand();
  LOOP
    IF tok.kind = Plus THEN
      Next(tok);
      value := value + Operand()
    ELSIF tok.kind = Minus THEN
      Next(tok);
      value := value - Operand()
    ELSE
      RETURN value
    END
  END
END Expression;

PROCEDURE Calculate(line: ARRAY OF CHAR);
BEGIN
  Start(line);
  Next(tok);
  WriteString(line); WriteString(" = ");
  WriteFixed(Expression(), 2, 0); WriteLn
END Calculate;

BEGIN
  Calculate("1 + 2 + 3");
  Calculate("10 - 4 - 3");
  Calculate("2.5 - 0.25 + 100")
END sums.

Operand returns the value of the current token and moves on. Expression reads one operand, then loops: as long as the current token is + or -, it consumes the operator, reads the next operand and adds or subtracts it. Any other token ends the expression. Because the running value is updated from the left, 10 - 4 - 3 gives 3, not 9. Calculate starts the scanner and reads the first token before the parser looks at it; this one-token look-ahead is all a recursive-descent parser needs.

$ gm2 -fiso sums.mod Scanner.o -o sums
$ ./sums
1 + 2 + 3 = 6.00
10 - 4 - 3 = 3.00
2.5 - 0.25 + 100 = 102.25

Precedence

Multiplication and division get a procedure of their own, one level below Expression. The operands of + and - are now terms.

precedence.mod
MODULE precedence;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SRealIO IMPORT WriteFixed;
FROM Scanner IMPORT Kind, Token, Start, Next;

VAR
  tok: Token;

PROCEDURE Operand(): REAL;
VAR
  value: REAL;
BEGIN
  value := tok.value;
  Next(tok);
  RETURN value
END Operand;

PROCEDURE Term(): REAL;
VAR
  value: REAL;
BEGIN
  value := Operand();
  LOOP
    IF tok.kind = Times THEN
      Next(tok);
      value := value * Operand()
    ELSIF tok.kind = Divide THEN
      Next(tok);
      value := value / Operand()
    ELSE
      RETURN value
    END
  END
END Term;

PROCEDURE Expression(): REAL;
VAR
  value: REAL;
BEGIN
  value := Term();
  LOOP
    IF tok.kind = Plus THEN
      Next(tok);
      value := value + Term()
    ELSIF tok.kind = Minus THEN
      Next(tok);
      value := value - Term()
    ELSE
      RETURN value
    END
  END
END Expression;

PROCEDURE Calculate(line: ARRAY OF CHAR);
BEGIN
  Start(line);
  Next(tok);
  WriteString(line); WriteString(" = ");
  WriteFixed(Expression(), 2, 0); WriteLn
END Calculate;

BEGIN
  Calculate("2 + 3 * 4");
  Calculate("2 * 3 + 4");
  Calculate("100 / 10 / 5");
  Calculate("1 + 7 / 2 - 0.5 * 4")
END precedence.

Term has the same shape as Expression, with * and / and with Operand below it. When Expression reads 2 + 3 * 4, it calls Term for the 2, sees the + and calls Term again; that call consumes 3 * 4 completely and returns 12. No precedence table is needed: the order in which the procedures call each other is the precedence. 100 / 10 / 5 is 2, so division is left associative too.

$ gm2 -fiso precedence.mod Scanner.o -o precedence
$ ./precedence
2 + 3 * 4 = 14.00
2 * 3 + 4 = 10.00
100 / 10 / 5 = 2.00
1 + 7 / 2 - 0.5 * 4 = 2.50

Parentheses and unary minus

The last rule replaces Operand with Factor, which also accepts an expression in parentheses and a minus sign in front of a factor. Both cases call back up the chain, so the procedures become recursive.

parens.mod
MODULE parens;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SRealIO IMPORT WriteFixed;
FROM Scanner IMPORT Kind, Token, Start, Next;

VAR
  tok: Token;

PROCEDURE Factor(): REAL;
VAR
  value: REAL;
BEGIN
  IF tok.kind = Minus THEN
    Next(tok);
    RETURN -Factor()
  ELSIF tok.kind = LParen THEN
    Next(tok);
    value := Expression();
    Next(tok)
  ELSE
    value := tok.value;
    Next(tok)
  END;
  RETURN value
END Factor;

PROCEDURE Term(): REAL;
VAR
  value: REAL;
BEGIN
  value := Factor();
  LOOP
    IF tok.kind = Times THEN
      Next(tok);
      value := value * Factor()
    ELSIF tok.kind = Divide THEN
      Next(tok);
      value := value / Factor()
    ELSE
      RETURN value
    END
  END
END Term;

PROCEDURE Expression(): REAL;
VAR
  value: REAL;
BEGIN
  value := Term();
  LOOP
    IF tok.kind = Plus THEN
      Next(tok);
      value := value + Term()
    ELSIF tok.kind = Minus THEN
      Next(tok);
      value := value - Term()
    ELSE
      RETURN value
    END
  END
END Expression;

PROCEDURE Calculate(line: ARRAY OF CHAR);
BEGIN
  Start(line);
  Next(tok);
  WriteString(line); WriteString(" = ");
  WriteFixed(Expression(), 2, 0); WriteLn
END Calculate;

BEGIN
  Calculate("(2 + 3) * 4");
  Calculate("2 * (3 + 4) * 5");
  Calculate("-(1 - 7) / -4");
  Calculate("((1.5))")
END parens.

A left parenthesis makes Factor call Expression, which may call Term and Factor again for nested parentheses; when it returns, the current token should be the closing parenthesis, which Next skips. A minus sign makes Factor call itself and negate the result, so -(1 - 7) and --2 work. Modula-2 lets a procedure call one that is declared further down, so Factor can call Expression without a forward declaration. The recursion article shows simpler recursive procedures.

$ gm2 -fiso parens.mod Scanner.o -o parens
$ ./parens
(2 + 3) * 4 = 20.00
2 * (3 + 4) * 5 = 70.00
-(1 - 7) / -4 = -1.50
((1.5)) = 1.50

A parser module

The three parsing procedures are complete, so they move into a module next to the scanner. Its definition module exports a single procedure.

Parser.def
DEFINITION MODULE Parser;

PROCEDURE Evaluate(line: ARRAY OF CHAR): REAL;
(* Returns the value of the arithmetic expression in line. *)

END Parser.

A client passes a line and gets its value; tokens and the scanner stay hidden.

Parser.mod
IMPLEMENTATION MODULE Parser;
FROM Scanner IMPORT Kind, Token, Start, Next;

VAR
  tok: Token;

PROCEDURE Factor(): REAL;
VAR
  value: REAL;
BEGIN
  IF tok.kind = Minus THEN
    Next(tok);
    RETURN -Factor()
  ELSIF tok.kind = LParen THEN
    Next(tok);
    value := Expression();
    Next(tok)
  ELSE
    value := tok.value;
    Next(tok)
  END;
  RETURN value
END Factor;

PROCEDURE Term(): REAL;
VAR
  value: REAL;
BEGIN
  value := Factor();
  LOOP
    IF tok.kind = Times THEN
      Next(tok);
      value := value * Factor()
    ELSIF tok.kind = Divide THEN
      Next(tok);
      value := value / Factor()
    ELSE
      RETURN value
    END
  END
END Term;

PROCEDURE Expression(): REAL;
VAR
  value: REAL;
BEGIN
  value := Term();
  LOOP
    IF tok.kind = Plus THEN
      Next(tok);
      value := value + Term()
    ELSIF tok.kind = Minus THEN
      Next(tok);
      value := value - Term()
    ELSE
      RETURN value
    END
  END
END Expression;

PROCEDURE Evaluate(line: ARRAY OF CHAR): REAL;
BEGIN
  Start(line);
  Next(tok);
  RETURN Expression()
END Evaluate;

END Parser.

The implementation module holds the procedures of the previous program and the current token. Evaluate does what Calculate did, without the output.

calc.mod
MODULE calc;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SRealIO IMPORT WriteFixed;
FROM Parser IMPORT Evaluate;

PROCEDURE Show(line: ARRAY OF CHAR);
BEGIN
  WriteString(line); WriteString(" = ");
  WriteFixed(Evaluate(line), 2, 0); WriteLn
END Show;

BEGIN
  Show("(2 + 3) * 4");
  Show("1 / 8 + 1 / 8");
  Show("-2 * -(3 - 10)")
END calc.

The client imports only Evaluate. Parser.o depends on Scanner.o, so both object files are linked, as the modules article explains.

$ gm2 -fiso -c Parser.mod
$ gm2 -fiso calc.mod Parser.o Scanner.o -o calc
$ ./calc
(2 + 3) * 4 = 20.00
1 / 8 + 1 / 8 = 0.25
-2 * -(3 - 10) = -14.00

Syntax errors

So far the parser trusts its input: a missing parenthesis or a stray operator gives a wrong value without a word. A syntax error is found deep in the recursion, but it has to be reported to the client that called Evaluate. An exception does that in one step. The definition module gets a type for the kinds of errors and a new Evaluate.

Parser.def
DEFINITION MODULE Parser;

TYPE
  Error = (None, NumberExpected, ParenExpected, BadCharacter,
           ExtraText);

PROCEDURE Evaluate(line: ARRAY OF CHAR; VAR value: REAL;
                   VAR error: Error; VAR pos: CARDINAL);
(* Computes the value of the expression in line. If the line is not
   a valid expression, error tells why and pos where. *)

END Parser.

Evaluate now returns the value and the error through VAR parameters; pos is meaningful only when error is not None. The implementation module changes in Factor and Evaluate and gets a Fail procedure.

Parser.mod
IMPLEMENTATION MODULE Parser;
FROM Scanner IMPORT Kind, Token, Start, Next;
FROM EXCEPTIONS IMPORT ExceptionSource, AllocateSource, RAISE,
  IsCurrentSource, CurrentNumber;

VAR
  tok: Token;
  syntax: ExceptionSource;
  errorPos: CARDINAL;

PROCEDURE Fail(error: Error; pos: CARDINAL);
BEGIN
  errorPos := pos;
  RAISE(syntax, ORD(error), "syntax error")
END Fail;

PROCEDURE Factor(): REAL;
VAR
  value: REAL;
BEGIN
  IF tok.kind = Minus THEN
    Next(tok);
    RETURN -Factor()
  ELSIF tok.kind = LParen THEN
    Next(tok);
    value := Expression();
    IF tok.kind # RParen THEN
      Fail(ParenExpected, tok.pos)
    END
  ELSIF tok.kind = Number THEN
    value := tok.value
  ELSIF tok.kind = Bad THEN
    Fail(BadCharacter, tok.pos)
  ELSE
    Fail(NumberExpected, tok.pos)
  END;
  Next(tok);
  RETURN value
END Factor;

(* Term and Expression are unchanged *)

PROCEDURE Evaluate(line: ARRAY OF CHAR; VAR value: REAL;
                   VAR error: Error; VAR pos: CARDINAL);
BEGIN
  Start(line);
  Next(tok);
  value := Expression();
  IF tok.kind = Bad THEN
    Fail(BadCharacter, tok.pos)
  ELSIF tok.kind # End THEN
    Fail(ExtraText, tok.pos)
  END;
  error := None
EXCEPT
  IF IsCurrentSource(syntax) THEN
    error := VAL(Error, CurrentNumber(syntax));
    pos := errorPos;
    RETURN
  END
END Evaluate;

BEGIN
  AllocateSource(syntax)
END Parser.

Fail stores the position and raises an exception of the module's own source, with the error as its number. Factor now checks what it finds: a number, an opening parenthesis followed later by a closing one, or a minus; anything else is an error. After the expression, Evaluate requires the end of the text, so 2 4 is not taken as 2. The EXCEPT part of Evaluate catches the exception wherever it was raised, however deep the recursion was, turns its number back into an Error with VAL and returns normally. The message of RAISE is not used, because GetMessage in gm2 15.2 adds a file position to it; the error handling article shows this.

errors.mod
MODULE errors;
FROM STextIO IMPORT WriteString, WriteChar, WriteLn;
FROM SRealIO IMPORT WriteFixed;
FROM Parser IMPORT Error, Evaluate;

PROCEDURE Show(line: ARRAY OF CHAR);
VAR
  value: REAL;
  error: Error;
  pos, i: CARDINAL;
BEGIN
  WriteString(line); WriteLn;
  Evaluate(line, value, error, pos);
  IF error = None THEN
    WriteString("= "); WriteFixed(value, 2, 0)
  ELSE
    FOR i := 1 TO pos DO
      WriteChar(' ')
    END;
    WriteString("^ ");
    CASE error OF
      NumberExpected: WriteString("number expected") |
      ParenExpected: WriteString("')' expected") |
      BadCharacter: WriteString("unknown character") |
      ExtraText: WriteString("operator expected")
    ELSE
    END
  END;
  WriteLn
END Show;

BEGIN
  Show("2 * (3 + 4)");
  Show("2 * (3 + 4");
  Show("2 * + 4");
  Show("2 % 4");
  Show("2 4");
  Show("1 / (3 - 3)")
END errors.

The client prints the line and, on an error, a caret under the offending token. The last line is not a syntax error and passes, but its value is wrong: 3 - 3 is 0, and dividing a real number by zero gives infinity instead of an error.

$ gm2 -fiso -c Parser.mod
$ gm2 -fiso errors.mod Parser.o Scanner.o -o errors
$ ./errors
2 * (3 + 4)
= 14.00
2 * (3 + 4
          ^ ')' expected
2 * + 4
    ^ number expected
2 % 4
  ^ unknown character
2 4
  ^ operator expected
1 / (3 - 3)
= INF

Division by zero

Division by zero is found while computing, not while parsing, but it is reported the same way. DivisionByZero is added at the end of the Error type in Parser.def, and Term checks the divisor before it divides.

Parser.mod
PROCEDURE Term(): REAL;
VAR
  value, divisor: REAL;
  at: CARDINAL;
BEGIN
  value := Factor();
  LOOP
    IF tok.kind = Times THEN
      Next(tok);
      value := value * Factor()
    ELSIF tok.kind = Divide THEN
      at := tok.pos;
      Next(tok);
      divisor := Factor();
      IF divisor = 0.0 THEN
        Fail(DivisionByZero, at)
      END;
      value := value / divisor
    ELSE
      RETURN value
    END
  END
END Term;

Term remembers the position of the / before it consumes it, so the error points at the operator. The divisor is compared with 0.0 exactly; any other value, however small, gives a finite result.

errors.mod
MODULE errors;
FROM STextIO IMPORT WriteString, WriteChar, WriteLn;
FROM SRealIO IMPORT WriteFixed;
FROM Parser IMPORT Error, Evaluate;

PROCEDURE Show(line: ARRAY OF CHAR);
VAR
  value: REAL;
  error: Error;
  pos, i: CARDINAL;
BEGIN
  WriteString(line); WriteLn;
  Evaluate(line, value, error, pos);
  IF error = None THEN
    WriteString("= "); WriteFixed(value, 2, 0)
  ELSE
    FOR i := 1 TO pos DO
      WriteChar(' ')
    END;
    WriteString("^ ");
    CASE error OF
      NumberExpected: WriteString("number expected") |
      ParenExpected: WriteString("')' expected") |
      BadCharacter: WriteString("unknown character") |
      ExtraText: WriteString("operator expected") |
      DivisionByZero: WriteString("division by zero")
    ELSE
    END
  END;
  WriteLn
END Show;

BEGIN
  Show("2 * (3 + 4)");
  Show("2 * (3 + 4");
  Show("2 * + 4");
  Show("2 % 4");
  Show("2 4");
  Show("1 / (3 - 3)")
END errors.

The client has one more label in its CASE. Since the Error type changed, every module that imports Parser must be compiled again.

$ gm2 -fiso -c Parser.mod
$ gm2 -fiso errors.mod Parser.o Scanner.o -o errors
$ ./errors
2 * (3 + 4)
= 14.00
2 * (3 + 4
          ^ ')' expected
2 * + 4
    ^ number expected
2 % 4
  ^ unknown character
2 4
  ^ operator expected
1 / (3 - 3)
  ^ division by zero

An interactive calculator

The last program reads expressions from the terminal, one per line, until the end of input, and prints whole results without decimals.

calc.mod
MODULE calc;
FROM STextIO IMPORT WriteString, WriteChar, WriteLn, ReadString, SkipLine;
FROM SWholeIO IMPORT WriteInt;
FROM SRealIO IMPORT WriteFixed;
FROM SIOResult IMPORT ReadResult, ReadResults;
FROM Strings IMPORT Length;
FROM Parser IMPORT Error, Evaluate;

CONST
  Prompt = "> ";

VAR
  line: ARRAY [0..255] OF CHAR;
  value: REAL;
  error: Error;
  pos, i: CARDINAL;

PROCEDURE WriteValue(x: REAL);
BEGIN
  IF (ABS(x) < 1.0E9) AND (x = FLOAT(INT(x))) THEN
    WriteInt(INT(x), 0)
  ELSE
    WriteFixed(x, 6, 0)
  END
END WriteValue;

PROCEDURE WriteError(e: Error);
BEGIN
  CASE e OF
    NumberExpected: WriteString("number expected") |
    ParenExpected: WriteString("')' expected") |
    BadCharacter: WriteString("unknown character") |
    ExtraText: WriteString("operator expected") |
    DivisionByZero: WriteString("division by zero")
  ELSE
  END
END WriteError;

BEGIN
  LOOP
    WriteString(Prompt);
    ReadString(line);
    IF (ReadResult() = endOfInput) AND (Length(line) = 0) THEN
      EXIT
    END;
    SkipLine;
    IF Length(line) > 0 THEN
      Evaluate(line, value, error, pos);
      IF error = None THEN
        WriteValue(value)
      ELSE
        FOR i := 1 TO Length(Prompt) + pos DO
          WriteChar(' ')
        END;
        WriteString("^ ");
        WriteError(error)
      END;
      WriteLn
    END
  END;
  WriteLn
END calc.

The read loop is the one from the reading input article: it stops when ReadString reports the end of input with an empty line, and SkipLine consumes the line mark. Empty lines are skipped. WriteValue prints a value with WriteInt when it has no fraction; the test ABS(x) < 1.0E9 comes first, so INT never gets a value too large for an INTEGER. Other values get six decimals. The caret is shifted by the length of the prompt so that it lands under the typed text. The session ends with Ctrl+D.

$ gm2 -fiso calc.mod Parser.o Scanner.o -o calc
$ ./calc
> 2 + 3 * 4
14
> (2 + 3) * 4
20
> 10 / 4
2.500000
> 1 / 3
0.333333
> -(8 - 2) * 1.5
-9
> 
> 2 * (3 + 4
            ^ ')' expected
> 7 / (2 - 2)
    ^ division by zero
> 

Source

The GNU Modula-2 manual

GNU Modula-2: exception handling

Niklaus Wirth: Compiler Construction

In this article we have written a calculator: a grammar in EBNF, a scanner module that returns tokens as variant records, a recursive-descent parser with precedence, parentheses and unary minus, syntax errors raised as exceptions and reported with their position, and an interactive loop. The calculator can grow in the same way: a new operator such as ^ for powers gets its own level between Term and Factor, and variables need a token for names and a table of values such as the one in the hash tables article. The string processing article covers more work on text.

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 Modula-2 tutorials.