84 lines
2.0 KiB
C
84 lines
2.0 KiB
C
/*
|
|
* Simple REPL for the calc evaluator.
|
|
* Build: clang main.c -o calc -lm
|
|
* @author Abner Coimbre <abner@terminal.click>
|
|
*/
|
|
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <math.h>
|
|
#include <assert.h>
|
|
#include <ctype.h>
|
|
|
|
/* Macros expected by tc_calc.h / tc_calc.c */
|
|
#define function static
|
|
#define global static
|
|
#define cast(T) (T)
|
|
|
|
#ifndef TC_CALC_FORMAT_BUFFER_SIZE
|
|
#define TC_CALC_FORMAT_BUFFER_SIZE 256
|
|
#endif
|
|
|
|
#include "tc_calc.h"
|
|
#include "tc_calc.c"
|
|
|
|
#define INPUT_MAX 1024
|
|
|
|
int main(int argc, char **argv)
|
|
{
|
|
char buf[INPUT_MAX];
|
|
calc_FormatKind fmt = CALC_FORMAT_DECIMAL;
|
|
|
|
// -e "expr": evaluate a single expression and exit
|
|
if (argc == 3 && strcmp(argv[1], "-e") == 0) {
|
|
double result = calc_eval(argv[2]);
|
|
if (isnan(result)) {
|
|
fprintf(stderr, "error: invalid expression\n");
|
|
return 1;
|
|
}
|
|
printf("%s\n", calc_format_result(result, fmt));
|
|
return 0;
|
|
}
|
|
|
|
printf("calc> ");
|
|
fflush(stdout);
|
|
|
|
while (fgets(buf, sizeof buf, stdin)) {
|
|
/* strip trailing newline */
|
|
buf[strcspn(buf, "\n")] = '\0';
|
|
|
|
/* skip blank lines */
|
|
if (buf[0] == '\0') {
|
|
printf("calc> ");
|
|
fflush(stdout);
|
|
continue;
|
|
}
|
|
|
|
/* format switching commands */
|
|
if (strcmp(buf, ":dec") == 0) {
|
|
fmt = CALC_FORMAT_DECIMAL;
|
|
printf(" format: decimal\n");
|
|
} else if (strcmp(buf, ":hex") == 0) {
|
|
fmt = CALC_FORMAT_HEX;
|
|
printf(" format: hex\n");
|
|
} else if (strcmp(buf, ":bin") == 0) {
|
|
fmt = CALC_FORMAT_BINARY;
|
|
printf(" format: binary\n");
|
|
} else {
|
|
double result = calc_eval(buf);
|
|
|
|
if (isnan(result))
|
|
printf(" error: invalid expression\n");
|
|
else
|
|
printf(" %s\n", calc_format_result(result, fmt));
|
|
}
|
|
|
|
printf("calc> ");
|
|
fflush(stdout);
|
|
}
|
|
|
|
putchar('\n');
|
|
return 0;
|
|
}
|