scl/src/lexer.c

38 lines
816 B
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>
2024-10-19 09:09:37 -04: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
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)) {
2024-11-09 10:27:03 -05:00
int value = c - '0';
2024-11-23 10:21:34 -05:00
while (isdigit(*inp)) {
value = value * 10 + (*inp - '0'); // Accumulate value.
inp++;
2024-11-02 11:02:18 -04:00
}
2024-11-09 10:27:03 -05:00
yylval.intval = value; // Set the token value.
return NUM;
}
switch (c) {
case '+': return PLUS;
case '\n': return NL;
2024-11-09 10:27:03 -05:00
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-11-16 10:42:50 -05:00
void yyerror(char const* s) { fprintf(stderr, "Syntax error:\n%s\n", s); }