Files
Toy/test/test_parser.c
2022-08-29 15:33:58 +10:00

121 lines
2.3 KiB
C

#include "parser.h"
#include "console_colors.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//IO functions
char* readFile(char* path, size_t* fileSize) {
FILE* file = fopen(path, "rb");
if (file == NULL) {
fprintf(stderr, ERROR "Could not open file \"%s\"\n" RESET, path);
exit(-1);
}
fseek(file, 0L, SEEK_END);
*fileSize = ftell(file);
rewind(file);
char* buffer = (char*)malloc(*fileSize + 1);
if (buffer == NULL) {
fprintf(stderr, ERROR "Not enough memory to read \"%s\"\n" RESET, path);
exit(-1);
}
size_t bytesRead = fread(buffer, sizeof(char), *fileSize, file);
buffer[*fileSize] = '\0'; //NOTE: fread doesn't append this
if (bytesRead < *fileSize) {
fprintf(stderr, ERROR "Could not read file \"%s\"\n" RESET, path);
exit(-1);
}
fclose(file);
return buffer;
}
int main() {
{
//source
char* source = "print null;";
//test init & quit
Lexer lexer;
Parser parser;
initLexer(&lexer, source);
initParser(&parser, &lexer);
freeParser(&parser);
}
{
//source
char* source = "print null;";
//test parsing
Lexer lexer;
Parser parser;
initLexer(&lexer, source);
initParser(&parser, &lexer);
Node* node = scanParser(&parser);
//inspect the node
if (node == NULL) {
fprintf(stderr, ERROR "ERROR: Node is null" RESET);
return -1;
}
if (node->type != NODE_UNARY || node->unary.opcode != OP_PRINT) {
fprintf(stderr, ERROR "ERROR: Node is not a print instruction" RESET);
return -1;
}
if (node->unary.child->type != NODE_LITERAL || !IS_NULL(node->unary.child->atomic.literal)) {
fprintf(stderr, ERROR "ERROR: Node to be printed is not a null value" RESET);
return -1;
}
//cleanup
freeNode(node);
freeParser(&parser);
}
{
//get the source file
size_t size = 0;
char* source = readFile("sample_code.toy", &size);
//test parsing a chunk of junk (valgrind will find leaks)
Lexer lexer;
Parser parser;
initLexer(&lexer, source);
initParser(&parser, &lexer);
Node* node = scanParser(&parser);
while (node != NULL) {
if (node->type == NODE_ERROR) {
fprintf(stderr, ERROR "ERROR: Error node detected" RESET);
return -1;
}
freeNode(node);
node = scanParser(&parser);
}
//cleanup
freeParser(&parser);
free((void*)source);
}
printf(NOTICE "All good\n" RESET);
return 0;
}