Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add unlexing capability #11

Merged
merged 1 commit into from
Jun 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions src/lexer/lex.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
#include "lex.h"

#include <string.h> // memcpy

int lex(Lexer *l, Token *t) {
// If there are any tokens waiting in the putback buffer, read from there
// instead.
if (l->unlexed_count > 0) {
l->unlexed_count--;
memcpy(t, &l->unlexed[l->unlexed_count], sizeof(Token));
return 0;
}
// Now, do the actual lexing: TODO!
return 0;
}

int unlex(Lexer *l, Token *t) {
// First, make sure we can actually fit it in the buffer.
if (l->unlexed_count >= TOKEN_PUTBACKS) {
// TODO: error reporting
return -1; // Error return code
}
memcpy(&l->unlexed[l->unlexed_count], t, sizeof(Token));
l->unlexed_count++;
return 0;
}
13 changes: 10 additions & 3 deletions src/lexer/lex.h
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,20 @@

#include "token.h"

// The maximum number of tokens we can put back.
#define TOKEN_PUTBACKS 5

// This is a lexer structure, which will contain all of the information about
// the state of a lexer. For now all we need is the file pointer which actually
// has the data we need, but in the future we will need more.
// the state of a lexer.
typedef struct {
FILE * fp;
FILE * fp; // The file we are reading from.
Token unlexed[TOKEN_PUTBACKS];
unsigned unlexed_count;
} Lexer;

// Takes an open file pointer, and a token as input. It fills the token struct
// with the next available token from the file.
int lex(Lexer * l, Token * token);

// Put a token back to be lexed again in the future.
int unlex(Lexer * l, Token * token);
Loading