I thought it would be fun to construct a mini
parser for generating acronyms while I was waiting for one of my coworkers. So using my other parser "studies" as a basis, I generated this (However, I only spent 15 minutes on this so beware):
enum Token
{
tok_eof = -1,
// end of file
tok_identifier = -2
};
static std::string IdentifierString;
static int CurTok;
// oops; globals
static int gettok()
{
static int LastChar = ' ';
// skip whitespace
while (isspace(LastChar))
LastChar = getchar();
if (isalpha(LastChar)) {
IdentifierString = LastChar;
while (isalpha(LastChar))
LastChar = getchar();
return tok_identifier;
}
// Check for end of file. Don't eat the EOF.
if (LastChar == EOF)
return tok_eof;
// Otherwise, just return the character as its ascii value.
int ThisChar = LastChar;
LastChar = getchar();
return ThisChar;
}
static int getNextToken()
{
return CurTok = gettok();
}
static void HandleIdentifier()
{
std::cout << IdentifierString;
getNextToken();
// prime the next token
return;
}
static void MainLoop()
{
while (1)
{
switch (CurTok)
{
case tok_eof: return;
case tok_identifier: HandleIdentifier(); break;
default: getNextToken(); break;
}
}
}
int main(int argc, char *argv[])
{
std::cout << "\nPress \"CTRL-Z\" when finished.\n";
MainLoop();
return 0;
}
Of course this is grossly over doing it but I wanted this to represent a mini model of my LispParser trial (it not really an accurate model, but it's kind of in the same spirit).
Now, watch this. We can eliminate quite a bit of code by making two minor changes to the gettok() function.
static int gettok()
{
static int LastChar = ' ';
// skip whitespace
while (isspace(LastChar))
LastChar = getchar();
if (isalpha(LastChar))
{
IdentifierString += LastChar; // changed
while (isalpha(LastChar))
LastChar = getchar();
return gettok(); // changed
}
// Check for end of file. Don't eat the EOF.
if (LastChar == EOF)
return 0;
}
int main(int argc, char *argv[])
{
std::cout << "\nPress \"CTRL-Z\" when finished.\n";
gettok();
std::cout << IdentifierString << '\n';
return 1;
}
Same functionality (almost).
With the first example you can generate a GIANT acronym from a file full of text like:
[COMPILEDEXENAME].exe < [FILENAME]