vety-language/test/test.c

93 lines
2.4 KiB
C

#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include "../parser/parser.h"
#include "../parser/ast_printer.h"
#include "../utils/file.h"
#define DEMO_DIR "../demo/"
#define VT_EXT ".vt"
#define PASS_SYMBOL "✓" // Unicode checkmark
// Function to test a single .vt file
void test_single_file(const char* filename, int isPT) {
printf("Testing file: %s \n", filename);
// 初始化词法分析器和语法分析器
FILE* file = fopen(filename, "r");
if (!file) {
printf("Error opening file: %s\n", filename);
return;
}
char* source = read_file(filename);
Lexer lexer;
lexer_init(&lexer, source);
Parser parser;
parser_init(&parser, &lexer, (char*)filename);
// 解析整个文件
ASTNode* ast = parse_program(&parser);
printf(" => ");
if (parser.had_error) {
printf("\n");
} else {
printf("%s\n", PASS_SYMBOL);
if (isPT) ast_pretty_print(ast);
}
// 清理资源
fclose(file);
}
// Function to test all .vt files in demo directory
void test_all_demo_files() {
DIR *dir;
struct dirent *entry;
dir = opendir(DEMO_DIR);
if (dir == NULL) {
perror("Error opening demo directory");
return;
}
printf("Testing all .vt files in demo directory:\n");
while ((entry = readdir(dir)) != NULL) {
char path[256];
snprintf(path, sizeof(path), "%s%s", DEMO_DIR, entry->d_name);
struct stat file_stat;
if (stat(path, &file_stat) == 0 && S_ISREG(file_stat.st_mode)) {
char *ext = strrchr(entry->d_name, '.');
if (ext && strcmp(ext, VT_EXT) == 0) {
char* filepath = malloc(strlen(DEMO_DIR) + strlen(entry->d_name) + 1);
if (filepath == NULL) {
perror("Memory allocation failed");
continue;
}
strcpy(filepath, DEMO_DIR);
strcat(filepath, entry->d_name);
test_single_file(filepath, 0);
}
}
}
closedir(dir);
}
int main() {
system("chcp 65001");
test_all_demo_files();
test_single_file("main.vt", 1);
//test_single_file("../demo/operators.vt", 1);
// Example of testing single file
// test_single_file("example.vt");
return 0;
}