An expression calculator
How does a program understand "2 * (3 + 4)"? This lesson turns the text into tokens with a regular expression and reads them with a small recursive-descent parser that knows operator precedence and reports clear errors.
What you will learn#
- the two steps of every language tool: tokens, then grammar,
- how a parser respects precedence (
*before+) and parentheses, - writing a grammar as a few short rules and one function per rule,
- error messages that say what is wrong,
- using the .NET
Mathclass for functions likesqrt.
The grammar#
Each rule becomes one function. A rule only calls the rules below it, and that is how precedence works: the rule for + and - calls the rule for * and / to get its operands, so the multiplications are done first.
expression = term { ("+" | "-") term }
term = power { ("*" | "/") power }
power = unary [ "^" power ]
unary = "-" unary | primary
primary = number | "(" expression ")" | name "(" expression { "," expression } ")"{ ... } means "zero or more times", [ ... ] "optional". Parentheses return to the top rule, so (1 + 2) * 3 works. power calls itself on the right side, which makes 2 ^ 3 ^ 2 mean 2 ^ (3 ^ 2).
The program#
# an expression calculator - tokens, a recursive-descent parser, precedence and clear errors
load "dotnet.ring"
using {
"System"
"System.Text.RegularExpressions"
}
func main
aTests = ["1 + 2 * 3","(1 + 2) * 3","10 / 4 - 1","2 ^ 3 ^ 2","-(2 + 3) * 4","sqrt(16) + max(3, 9)","2 * (3 + ","4 $ 4","1 / 0"]
for cText in aTests
oCalc = new Evaluator()
? padRight(cText,24) + " = " + oCalc.calculate(cText)
next
func padRight cText, nWidth
while len(cText) < nWidth
cText += " "
end
return cText
# Step 1: the text becomes tokens (numbers, names, operators). Step 2: the parser reads the tokens following the grammar:
# expression = term { (+|-) term } term = power { (*|/) power }
# power = unary [ ^ power ] unary = - unary | primary
# primary = number | ( expression ) | name ( expression { , expression } )
class Evaluator
aTokens = []
nPos = 0
cError = ""
func init
return self
func calculate cText
cError = ""
aTokens = tokenize(cText)
if cError != ""
return "error: " + cError
ok
nPos = 1
nValue = expression()
if cError = "" and nPos <= len(aTokens)
cError = "unexpected '" + aTokens[nPos] + "'"
ok
if cError != ""
return "error: " + cError
ok
return nValue
# Regex.Matches finds every piece; anything that is not a number, a name, an operator or a space is an error
func tokenize cText
aList = []
oMatches = new Regex("\s*(\d+\.?\d*|[A-Za-z]+|[-+*/^(),]|\S)").Matches(cText)
for nIndex = 0 to oMatches.Count - 1
cToken = oMatches.Item(nIndex).Groups.Item(1).Value
if not new Regex("^(\d+\.?\d*|[A-Za-z]+|[-+*/^(),])$").IsMatch(cToken)
cError = "unknown character '" + cToken + "'"
return []
ok
aList + cToken
next
return aList
func peek
if nPos <= len(aTokens)
return aTokens[nPos]
ok
return ""
func expression
nLeft = term()
while cError = "" and (peek() = "+" or peek() = "-")
cOp = peek()
nPos++
nRight = term()
if cOp = "+"
nLeft += nRight
else
nLeft -= nRight
ok
end
return nLeft
func term
nLeft = power()
while cError = "" and (peek() = "*" or peek() = "/")
cOp = peek()
nPos++
nRight = power()
if cOp = "*"
nLeft *= nRight
else
if nRight = 0
cError = "division by zero"
return 0
ok
nLeft /= nRight
ok
end
return nLeft
# ^ goes to the right: 2^3^2 = 2^(3^2)
func power
nBase = unary()
if cError = "" and peek() = "^"
nPos++
return pow(nBase,power())
ok
return nBase
func unary
if peek() = "-"
nPos++
return -unary()
ok
return primary()
func primary
cToken = peek()
if cToken = ""
cError = "the expression ends too early"
return 0
ok
nPos++
if new Regex("^\d").IsMatch(cToken)
return number(cToken)
but cToken = "("
nValue = expression()
expect(")")
return nValue
but new Regex("^[A-Za-z]").IsMatch(cToken)
return callFunction(cToken)
ok
cError = "unexpected '" + cToken + "'"
return 0
func expect cToken
if cError != ""
return
but peek() != cToken
cError = "'" + cToken + "' expected"
return
ok
nPos++
# name ( arguments ): the functions come from the .NET Math class
func callFunction cName
expect("(")
aArgs = []
if peek() != ")"
aArgs + expression()
while cError = "" and peek() = ","
nPos++
aArgs + expression()
end
ok
expect(")")
if cError != ""
return 0
ok
oMath = new Math()
switch lower(cName)
on "sqrt"
return oMath.Sqrt(aArgs[1])
on "abs"
return oMath.Abs(aArgs[1])
on "max"
return oMath.Max(aArgs[1],aArgs[2])
on "min"
return oMath.Min(aArgs[1],aArgs[2])
on "round"
return oMath.Round(aArgs[1])
off
cError = "unknown function " + cName
return 01 + 2 * 3 = 7
(1 + 2) * 3 = 9
10 / 4 - 1 = 1.50
2 ^ 3 ^ 2 = 512
-(2 + 3) * 4 = -20
sqrt(16) + max(3, 9) = 13
2 * (3 + = error: the expression ends too early
4 $ 4 = error: unknown character '$'
1 / 0 = error: division by zeroHow it works#
Tokens#
tokenize uses one regular expression, \s*(\d+\.?\d*|[A-Za-z]+|[-+*/^(),]|\S): skip spaces, then take a number, a name, an operator — or any other character, which is reported as unknown character '$'. Regex.Matches gives all the pieces; Groups.Item(1).Value is the piece without the spaces.
The parser#
aTokens is the list and nPos the position. peek() looks at the next token without taking it; the functions expression, term, power, unary and primary follow the grammar one to one. expect(")") checks that the closing parenthesis is there.
Errors#
When something is wrong the parser stores a message in cError and the loops stop. Look at the three last lines of the output: 2 * (3 + ends too early, 4 $ 4 has a strange character, 1 / 0 is a division by zero. A calculator that answers what is wrong is much better than one that says "syntax error".
Functions#
sqrt(16) + max(3, 9) is a name followed by a list of expressions. callFunction collects the arguments and calls the matching method of Math (Sqrt, Max...). Adding sin or log is one more on line.
This technique is how real tools read formulas, configuration files, query languages and even programming languages. A grammar of ten lines and ten small functions can read most small languages.
What you learned#
- tokens and grammar,
- one function per grammar rule,
- precedence through the order of the rules,
- clear error messages,
Mathfunctions from a parser.
Exercises#
- Add
%(remainder) at the same level as*and/. - Add variables:
x = 5stores a value and later expressions can usex. - Show the position of the error (the number of the token) in each message.
Where to go next#
This was the last tutorial of the chapter Collections and algorithms. The next chapter is Files and streams: it starts with Paths and the environment. The Tutorials page lists all the chapters, and you can start any of them.