Skip to content

Instantly share code, notes, and snippets.

@pastagatsan
Created October 13, 2014 17:41
Show Gist options
  • Save pastagatsan/19073d4e8e9b2e946d54 to your computer and use it in GitHub Desktop.
Save pastagatsan/19073d4e8e9b2e946d54 to your computer and use it in GitHub Desktop.
/* Compilation Process:
*
* - Label Seeking (Look for labels and add them to the list)
* - Producing bytecode (The output which can be run by spank)
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define starts(a, b) !memcmp(a, b, strlen(b))
#define ends(a, b) !memcmp(a + strlen(a) - (strlen(b)), b, strlen(b))
const char* help = "Usage: spankc <input>\n";
typedef struct {
char* name;
int position;
} Label;
struct LabelList {
Label* labels;
size_t sz;
} label_list;
void label_seeking(FILE* input);
int main(int argc, char* argv[])
{
FILE* input, output;
/* Print usage if they don't have the
* correct amount of arguments.
*/
if (argc < 2) {
printf("%s", help);
exit(1);
}
/* Open our input file for reading. */
input = fopen(argv[1], "r");
/* Make sure we didn't fail to open it. */
if (input == NULL) {
printf("Failed to open file %s for reading", argv[1]);
exit(1);
}
printf("Label seeking...\n");
label_seeking(input);
printf("Done.\n");
return 0;
}
void label_seeking(FILE* input)
{
char token[100];
/* Whether or not we are inside a string. */
bool in_string = false;
/* Look through all the tokens in the file. */
while (fscanf(input, "%s", token) != EOF) {
/* Check if the token ends in a colon. */
/* This will set in_string to true or false based on if
* on if we are in a string.
*/
if (starts(token, "\"")) {
in_string = !in_string;
} else if (ends(token, "\"")) {
in_string = false;
}
if (ends(token, ":") && !in_string) {
printf("Found label '%s'\n", token);
if (label_list.sz < 1) {
label_list = malloc(sizeof(LabelList));
} else {
label_list->labels = realloc(label_list->labels,
label_sz++;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment