Capstone B: the REPL

A calculator that takes one expression per run is a demonstration; a calculator that keeps reading is a tool. The difference is a loop, and the loop needs three answers: what ends it, what a bad line does to it, and what the program prints when the input is over. This lesson is the last part of the capstone before the tests, and it is the program a reader can use.

The read loop

Console.ReadLine() returns the next line without its line break, or null when the input is over. The loop is written as an infinite loop with two exits: a null from ReadLine, and the :quit command. A blank line is skipped and does not count as an expression. The whole program is one listing:

Console.WriteLine("calc 1.0, :quit to stop"); var total = 0.0; var count = 0; while (true) { Console.Write("> "); var line = Console.ReadLine(); if (line is null || line == ":quit") { break; } if (line.Trim().Length == 0) { continue; } try { var value = Eval(Parse(Lex(line))); total += value; count++; Console.WriteLine($"{value} (total {total})"); } catch (SyntaxException ex) { Console.WriteLine($"error at {ex.Position}: {ex.Message}"); } } Console.WriteLine($"bye, expressions {count}, total {total}"); static double Eval(Node node) => node switch { Number number => number.Value, Unary unary => -Eval(unary.Operand), Binary binary => binary.Op switch { '+' => Eval(binary.Left) + Eval(binary.Right), '-' => Eval(binary.Left) - Eval(binary.Right), '*' => Eval(binary.Left) * Eval(binary.Right), _ => Eval(binary.Left) / Eval(binary.Right), }, _ => throw new SyntaxException(0, "unknown node"), }; static List<Token> Lex(string text) { var tokens = new List<Token>(); var i = 0; while (i < text.Length) { var c = text[i]; if (char.IsWhiteSpace(c)) { i++; continue; } if (char.IsDigit(c) || c == '.') { var start = i; while (i < text.Length && (char.IsDigit(text[i]) || text[i] == '.')) { i++; } var number = text[start..i]; var value = double.Parse(number, System.Globalization.CultureInfo.InvariantCulture); tokens.Add(new Token(TokenKind.Number, value, start, number)); continue; } if (c is '+' or '-' or '*' or '/' or '(' or ')') { tokens.Add(new Token(TokenKind.Operator, 0, i, c.ToString())); i++; continue; } throw new SyntaxException(i, $"unexpected '{c}'"); } tokens.Add(new Token(TokenKind.End, 0, text.Length, "end")); return tokens; } static Node Parse(List<Token> tokens) => Parser.Parse(tokens); enum TokenKind { Number, Operator, End, } record Token(TokenKind Kind, double Value, int Position, string Text); sealed class SyntaxException(int position, string message) : FormatException(message) { public int Position { get; } = position; } abstract record Node; sealed record Number(double Value) : Node; sealed record Unary(char Op, Node Operand) : Node; sealed record Binary(char Op, Node Left, Node Right) : Node; sealed class Parser { private readonly List<Token> _tokens; private int _index; private Parser(List<Token> tokens) => _tokens = tokens; public static Node Parse(List<Token> tokens) => new Parser(tokens).Expression(); private Token Current => _tokens[_index]; private Node Expression() { var left = Term(); while (Current.Kind == TokenKind.Operator && Current.Text is "+" or "-") { var op = Current.Text[0]; _index++; left = new Binary(op, left, Term()); } return left; } private Node Term() { var left = Factor(); while (Current.Kind == TokenKind.Operator && Current.Text is "*" or "/") { var op = Current.Text[0]; _index++; left = new Binary(op, left, Factor()); } return left; } private Node Factor() { var token = Current; switch (token.Kind) { case TokenKind.Number: _index++; return new Number(token.Value); case TokenKind.Operator when token.Text == "-": _index++; return new Unary('-', Factor()); case TokenKind.Operator when token.Text == "(": _index++; var inner = Expression(); Expect(")"); return inner; default: throw new SyntaxException(token.Position, "expected a number"); } } private void Expect(string text) { if (Current.Kind != TokenKind.Operator || Current.Text != text) { throw new SyntaxException(Current.Position, $"expected '{text}'"); } _index++; } }

:quit and the total

The prompt is Console.Write("> "), which is WriteLine without the line break, so the answer appears on the same line as the prompt. Every value is added to a running total, and the last line of the program reports both counts: the number of expressions that were evaluated and the sum of their values. A bad line prints its message, does not change the total and does not end the loop, which is the whole difference between a REPL and a batch run:

printf '1 + 2\n2 * (3 + 4)\n1 + $\n:quit\n' | dotnet run
echo "status: $?"

calc 1.0, :quit to stop
> 3 (total 3)
> 14 (total 17)
> error at 4: unexpected '$'
> bye, expressions 2, total 17
status: 0

The third line of input, 1 + $, is the lexer error of lesson 124 and arrives here as a message and a caret position that the loop prints without the caret. The fourth line is the command, and the loop ends after it.

A run with a pipe

The input above came from printf through a pipe, not from a keyboard, and that changes what the screen shows. A terminal echoes what a person types; a pipe does not, so the output has the prompt and the answer on one line and no copy of the input. The second run has no :quit at all and ends at the end of the input, which is the null of ReadLine:

printf '2 + 3\n' | dotnet run
echo "status: $?"

calc 1.0, :quit to stop
> 5 (total 5)
> bye, expressions 1, total 5
status: 0

A person at a terminal ends the loop with :quit or with the end-of-file key of the terminal, which is Control-D on Linux and Control-Z and then Return in the Windows console. Both give null from ReadLine or the command, and both leave the program on the same last line.

The next lesson is the table of expressions and values, the same shape as the one that closed capstone A, plus the extension the last part of the capstone asks for: names with values.

Exercises

  1. Add a :clear command that sets the total back to zero.
  2. Print the number of the expression with every answer, so a long session can be read back.
  3. Accept :quit in any case and see which comparison method does it without a culture.
  4. Write the session to a file with a StreamWriter as it runs, and read it back with File.ReadLines.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does Console.ReadLine return at the end of the input?

    Answer

    null

    The loop ends at the null, which is why the second run stops without :quit.

  2. Why is the prompt written with Console.Write and not WriteLine?

    Answer

    So the answer appears on the same line as the prompt

    Write adds no line break.

  3. What does this program print? Console.Write("n: "); Console.WriteLine(3);

    Answer

    n: 3

    The prompt has no line break, so the number follows it.

  4. What happens to the total when a line has a syntax error?

    Answer

    It does not change, and the loop continues

    The measured run prints the error and then evaluates 14 more.

  5. What does this program print? var total = 0.0; foreach (var value in new[] { 3.0, 14.0 }) { total += value; } Console.WriteLine(total);

    Answer

    17

    The running total of the measured session ends at 17.

  6. Why does the piped output have no copy of the input lines?

    Answer

    A terminal echoes what is typed, and a pipe does not

    The prompt stays, because the program writes it; the echo is the terminal.

  7. What does this program print? Console.WriteLine(":quit" == ":QUIT");

    Answer

    False

    String equality is case-sensitive by default.

  8. How does a person at a terminal end the loop without :quit?

    Answer

    With the end-of-file key of the terminal, Control-D on Linux

    End of file gives ReadLine a null, the same exit as :quit.

  9. What does this program print? var line = "1 + 2"; Console.WriteLine(line.Split(' ').Length);

    Answer

    3

    Two operators around one number make three parts.

  10. What does the last line of the program report?

    Answer

    The number of expressions evaluated and the running total

    The measured last line reads bye, expressions 2, total 17.

The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev