skopy/tests/lexer.h

124 lines
2.6 KiB
C
Raw Normal View History

2024-03-31 21:10:56 +00:00
#ifndef SK_TEST_LEXER_H
#define SK_TEST_LEXER_H
#include <CUnit/CUnit.h>
#include <lexer.h>
#include <token.h>
static void test_lexer(char const* source, int count, ...)
{
struct lexer lexer;
lexer_init(&lexer, source);
va_list lst;
va_start(lst, count);
for (int i=0; i<count; i++)
{
struct token* tok = lexer_try_new_next(&lexer);
2024-04-01 19:42:36 +00:00
if (tok == NULL)
{
fprintf(stderr, "%s == NULL\n", source);
}
2024-03-31 21:10:56 +00:00
CU_ASSERT_FATAL(tok != NULL);
struct str tok_str;
str_init(&tok_str);
token_str(tok, &tok_str);
char* oracle = va_arg(lst, char*);
if (strcmp(oracle, tok_str.value) != 0)
{
fprintf(stderr, "%s != %s\n", oracle, tok_str.value);
}
2024-04-01 12:00:06 +00:00
CU_ASSERT_STRING_EQUAL_FATAL(tok_str.value, oracle);
2024-03-31 21:10:56 +00:00
str_free(&tok_str);
token_free(tok);
free(tok);
}
va_end(lst);
lexer_free(&lexer);
}
static void test_lexer_int()
{
test_lexer(" 4 23 720 ", 3,
2024-03-31 21:10:56 +00:00
"INT[4]",
"INT[23]",
2024-03-31 21:10:56 +00:00
"INT[720]"
);
2024-03-31 23:32:47 +00:00
test_lexer("+-*/^%()", 8,
2024-03-31 23:32:47 +00:00
"ADD", "SUB", "MUL", "DIV",
"POW", "MOD", "OPAR", "CPAR"
);
2024-03-31 21:10:56 +00:00
}
static void test_lexer_assert()
{
test_lexer("assert 2 eq 1", 4,
"ASSERT",
"INT[2]",
"ASSERT_EQ",
"INT[1]"
);
}
2024-04-01 12:00:06 +00:00
static void test_lexer_bool()
{
test_lexer("true false and or not", 5,
"BOOL[true]",
"BOOL[false]",
"AND",
"OR",
"NOT"
);
}
2024-04-01 19:08:42 +00:00
static void test_lexer_float()
{
test_lexer(".4 7. 2.3 6.12", 4,
2024-04-01 19:08:42 +00:00
"FLOAT[.4]",
"FLOAT[7.]",
"FLOAT[2.3]",
"FLOAT[6.12]"
2024-04-01 19:08:42 +00:00
);
}
2024-04-01 19:42:36 +00:00
static void test_lexer_string()
{
test_lexer("\" hello \" \"\\\"world\\\"\"", 2,
"STRING[ hello ]",
"STRING[\"world\"]"
);
test_lexer("\"\\n\\r\\t\\e\"", 1,
"STRING[\n\r\t\e]"
);
}
2024-04-01 21:33:43 +00:00
static void test_lexer_cmp()
{
test_lexer("< <= > >= == <>", 6,
"LT",
"LE",
"GT",
"GE",
"EQUAL",
"NOT_EQUAL"
);
}
2024-03-31 21:10:56 +00:00
void register_lexer()
{
CU_pSuite suite = CU_add_suite("Lexer", 0, 0);
CU_add_test(suite, "Integers", test_lexer_int);
CU_add_test(suite, "Assertions", test_lexer_assert);
2024-04-01 12:00:06 +00:00
CU_add_test(suite, "Booleans", test_lexer_bool);
2024-04-01 19:08:42 +00:00
CU_add_test(suite, "Floats", test_lexer_float);
2024-04-01 19:42:36 +00:00
CU_add_test(suite, "Strings", test_lexer_string);
2024-04-01 21:33:43 +00:00
CU_add_test(suite, "Comparisons", test_lexer_cmp);
2024-03-31 21:10:56 +00:00
}
#endif