Created
October 2, 2022 04:21
-
-
Save depp/c212cd9780c4e28187a8d2cb89228a32 to your computer and use it in GitHub Desktop.
Simple scanner
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%{ | |
#include <stdio.h> | |
#include <stdlib.h> | |
enum { | |
End, | |
Comma, | |
Equals, | |
Semicolon, | |
Number, | |
Identifier, | |
}; | |
%} | |
digit [0-9] | |
idstart [a-zA-Z_] | |
idcont [a-zA-Z_0-9] | |
%option noyywrap | |
%option yylineno | |
%% | |
[ \t\n\r]+ { } | |
"//".* { } | |
"," { return Comma; } | |
"=" { return Equals; } | |
";" { return Semicolon; } | |
[-+]?{digit}+ { return Number; } | |
{idstart}{idcont}* { return Identifier; } | |
. { printf("line %d: unexpected character: '%s'\n", yylineno, yytext); exit(1); } | |
%% | |
const char *const TokNames[] = { | |
[Comma] = "Comma", | |
[Equals] = "Equals", | |
[Semicolon] = "Semicolon", | |
[Number] = "Number", | |
[Identifier] = "Identifier", | |
}; | |
int main(int argc, char **argv) { | |
while (1) { | |
int tok = yylex(); | |
if (tok == 0) { | |
break; | |
} | |
printf("%s '%s'\n", TokNames[tok], yytext); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment