/* * Copyright (C) 2018 Nick Downing * SPDX-License-Identifier: GPL-2.0-only * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; version 2. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 51 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ %{ import t_def import sys %} %locations %token NUM %left '+' '-' %left '*' '/' %right UMINUS %% S : S E '\n' { sys.stdout.write('Answer: {0:g}\nEnter an expression:\n'.format($2)) } | S '\n' | | error '\n' { yyerror('Error, please try again:\n') yyerrok() } ; E : %space (?E{t_def.AST.Add}E '+' E) { $$ = $1 + $3 } | %space (?E{t_def.AST.Sub}E '-' E) { $$ = $1 - $3 } | %space (?E{t_def.AST.Mul}E '*' E) { $$ = $1 * $3 } | %space (?E{t_def.AST.Div}E '/' E) { $$ = $1 / $3 } | '(' E ')' { $$ = $2 } | %space (?E{t_def.AST.Neg}'-' E) %prec UMINUS { $$ = -$2 } | NUM ; %% def yyerror(s): sys.stdout.write('{0:s}\n'.format(s)) sys.exit(1)