~dheinemann/Replicalc

de037ae177f0933531b7c9ac3cb3d57459968d5f — David Heinemann 7 months ago e65e34f
Fix incorrect tokenization of negative numbers
2 files changed, 13 insertions(+), 4 deletions(-)

M src/calc.c
M tests/tests.c
M src/calc.c => src/calc.c +6 -4
@@ 74,7 74,8 @@ int assoc(char* token) {
 */
int is_negative(char expr[], int i) {
    int nextCharIsNum; /* Negative sign is to the immediate left of the number that follows. */
    int lastCharIsOp;
    int lastCharIsSymbol;
    int lastCharIsSpace;
    if (expr[i] != '-') {
        return 0;
    }


@@ 86,8 87,9 @@ int is_negative(char expr[], int i) {
    }

    /* Negative sign belongs to a number */
    lastCharIsOp = is_op(&expr[i-1]);
    if (nextCharIsNum && lastCharIsOp) {
    lastCharIsSymbol = is_symbol(expr[i-1]);
    lastCharIsSpace = expr[i-1] == ' ';
    if (nextCharIsNum && (lastCharIsSymbol || lastCharIsSpace)) {
        return 1;
    }



@@ 190,7 192,7 @@ int infixToPostfix(char** tokens, int length, char** output) {
 */
double evaluate(char** tokens, int numTokens, int* errorCode) {
    int i;
    double result = 0;
    double result;

    struct Double_Stack* stack = double_stack_new();
    for (i = 0; i < numTokens; i++) {

M tests/tests.c => tests/tests.c +7 -0
@@ 41,6 41,12 @@ void calculate_divideByZero_ReturnsError() {
    TEST_ASSERT_EQUAL(Error_DivideByZero, errorCode);
}

void calculate_divideByNegativeZero_ReturnsError() {
    int errorCode = 0;
    calculate("1 / -0", &errorCode);
    TEST_ASSERT_EQUAL(Error_DivideByZero, errorCode);
}

void calculate_complexExpressionWithoutSpaces_EvaluatesCorrectly() {
    int errorCode;
    int result;


@@ 77,6 83,7 @@ int main(void) {
    RUN_TEST(calculate_unbalancedOpenParen_ReturnsError);
    RUN_TEST(calculate_unbalancedCloseParen_ReturnsError);
    RUN_TEST(calculate_divideByZero_ReturnsError);
    RUN_TEST(calculate_divideByNegativeZero_ReturnsError);
    RUN_TEST(calculate_complexExpressionWithSpaces_EvaluatesCorrectly);
    RUN_TEST(calculate_complexExpressionWithoutSpaces_EvaluatesCorrectly);
    RUN_TEST(calculate_complexExpression_EvaluatesWithCorrectPrecedence);