Skip to content

Instantly share code, notes, and snippets.

@depp
Created October 2, 2022 04:21
Show Gist options
  • Save depp/c212cd9780c4e28187a8d2cb89228a32 to your computer and use it in GitHub Desktop.
Save depp/c212cd9780c4e28187a8d2cb89228a32 to your computer and use it in GitHub Desktop.
Simple scanner
%{
#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