scl/src/lexer.c

76 lines
1.6 KiB
C
Raw Normal View History

2024-10-13 23:46:03 -04:00
#include <ctype.h>
2024-11-09 04:37:56 -05:00
#include <limits.h>
#include <math.h>
2024-12-14 20:35:36 -05:00
#include <stdio.h>
2024-10-13 23:46:03 -04:00
2024-11-09 04:37:56 -05:00
#include "include/lexer.h"
2024-11-02 10:31:55 -04:00
int acc_int(int c) {
int value = c - '0';
while (isdigit(*inp)) {
value = value * 10 + (*inp - '0'); // Accumulate value.
inp++;
}
return value;
}
double acc_float(int c) {
2024-12-07 10:33:16 -05:00
int dplaces = 0;
double value = (double)(c - '0');
// Grab everything prior to '.'.
while (isdigit(*inp)) {
value = value * 10 + (*inp - '0'); // Accumulate value.
inp++;
}
2024-12-14 20:35:36 -05:00
if (*inp == '.') {
2024-12-07 10:33:16 -05:00
inp++;
while (isdigit(*inp)) {
2024-12-07 09:16:17 -05:00
// TODO:
// Accumulate as int, divide once at end.
2024-12-14 20:35:36 -05:00
// value = value + (((double)(*inp - '0'))/pow(10.0l,
// (double)(inp-oinp))); // Accumulate value.
2024-12-07 10:33:16 -05:00
value = value * 10 + (*inp - '0'); // Accumulate value.
dplaces++;
inp++;
}
2024-12-07 10:33:16 -05:00
value = value / pow(10, dplaces);
}
// > 1.20000
// = 1.0 + 2/10
// > 1.23
// = 1.2 + 3/100
return value;
}
2024-11-09 10:27:03 -05:00
int yylex() {
2024-11-23 10:21:34 -05:00
if (*inp == '\0') return YYEOF;
2024-11-02 11:02:18 -04:00
2024-11-09 10:27:03 -05:00
// Skip all whitespace.
2024-11-23 10:21:34 -05:00
while (*inp == ' ' || *inp == '\t') { inp++; }
2024-11-02 11:02:18 -04:00
// Assign & consume current character.
2024-11-23 10:21:34 -05:00
int c = *inp++;
2024-11-02 11:02:18 -04:00
2024-11-09 10:27:03 -05:00
// Check for NUM.
2024-11-02 11:02:18 -04:00
if (isdigit(c)) {
yylval.fval = acc_float(c); // Set the token value.
2024-11-09 10:27:03 -05:00
return NUM;
}
switch (c) {
2024-12-14 20:35:36 -05:00
case '+': return PLUS;
case '\n': return NL;
default: return CALL;
2024-11-02 11:02:18 -04:00
}
fprintf(stderr, "Unexpected character: %c\n", c);
return 0;
2024-11-02 10:31:55 -04:00
}
2024-12-07 10:33:16 -05:00
void yyerror(char const* s) { fprintf(stderr, "Parse error: %s\n", s); }