#!/bin/bash

[ -f testing.sh ] && . testing.sh

testing "integer" "expr 5" "5\n" "" ""
testing "integer negative" "expr -5" "-5\n" "" ""
testing "string" "expr astring" "astring\n" "" ""
testing "addition" "expr 1 + 3" "4\n" "" ""
testing "5 + 6 * 3" "expr 5 + 6 \* 3" "23\n" "" ""
testing "( 5 + 6 ) * 3" "expr \( 5 + 6 \) \* 3" "33\n" "" ""
testing ">" "expr 3 \> 2" "1\n" "" ""
testing "* / same priority" "expr 4 \* 3 / 2"  "6\n" "" ""
testing "/ * same priority" "expr 3 / 2 \* 4" "4\n" "" ""
testing "& before |" "expr 0 \| 1 \& 0" "0\n" "" ""
testing "| after &" "expr 1 \| 0 \& 0" "1\n" "" ""
testing "| & same priority" "expr 0 \& 0 \| 1" "1\n" "" ""
testing "% * same priority" "expr 3 % 2 \* 4" "4\n" "" ""
testing "* % same priority" "expr 3 \* 2 % 4" "2\n" "" ""
testing "= > same priority" "expr 0 = 2 \> 3" "0\n" "" ""
testing "> = same priority" "expr 3 \> 2 = 1" "1\n" "" ""
testing "64 bit comparison" "expr 100000000000 \> 1" "1\n" "" ""

testing "00 | 1" "expr 00 \| 1" "1\n" "" ""
testing "-0 | 1" "expr -0 \| 2" "2\n" "" ""
testing '"" | 1' 'expr "" \| 3' "3\n" "" ""
testing "/ by zero" "expr 1 / 0 2>/dev/null; echo \$?" "2\n" "" ""
testing "% by zero" "expr 1 % 0 2>/dev/null; echo \$?" "2\n" "" ""

testing "regex position" "expr ab21xx : '[^0-9]*[0-9]*'" "4\n" "" ""
testing "regex extraction" "expr ab21xx : '[^0-9]*\([0-9]*\).*'" "21\n" "" ""
testing "regex no match" "expr ab21xx : x" "0\n" "" ""
testing "long str" "expr abcdefghijklmnopqrstuvwxyz : '\(.*\)' = a" "0\n" "" ""

# result of ':' regex match can subsequently be used for arithmetic
testing "str becomes int" "expr ab21xx : '[^0-9]*\([0-9]*\)' + 3" "24\n" "" ""

testing "integer comparison" "expr -3 \< -2" "1\n" "" ""
testing "string comparison" "expr -3 \< -2s" "0\n" "" ""
testing "integer expression comparison" "expr 2 - 5 \< -2" "1\n" "" ""
# result of arithmetic can subsequently be compared as a string
testing "string expr comparison" "expr 2 - 5 \< -2s" "0\n" "" ""

testing "parens around literal" "expr \( a \)" "a\n" "" ""

testing "exit code when true" "expr a; echo \$?" "a\n0\n" "" ""
testing "exit code when false" "expr 0; echo \$?" "0\n1\n" "" ""
testing "exit code with syntax err" "expr \( 2>/dev/null; echo \$?" "2\n" "" ""
testing "exit code when evaluating to 0" "expr -1 + 1; echo \$?" "0\n1\n" "" ""

# BUG: segfaults because '3' is coerced to integer and regexc gets NULL
testing "regex segfault" "expr 3 : '\(.\)'" "3\n" "" ""

# syntax errors
testing "no expression" "expr 2>/dev/null; echo \$?" "2\n" "" ""
testing "empty ()" "expr \( \) 2>/dev/null; echo \$?" "2\n" "" ""
testing "missing )" "expr \( 1 2>/dev/null; echo \$?" "2\n" "" ""
testing "missing outer )" "expr \( 1 + \( 2 \* 3 \) 2>/dev/null; echo \$?" \
	"2\n" "" ""
testing "bad operator" "expr 1 @ 2 2>/dev/null; echo \$?" "2\n" "" ""
testing "adjacent literals" "expr 1 2 2>/dev/null; echo \$?" "2\n" "" ""
testing "non-integer argument" "expr 1 + a 2>/dev/null; echo \$?" "2\n" "" ""
