5 #include "script/parser.h"
7 static bool is_symbol_char(char x)
9 static const char forbidden_symbol_chars[] = {
10 '(', ')', '"', '\'', ';'
12 static const size_t n = sizeof(forbidden_symbol_chars) / sizeof(char);
14 for (size_t i = 0; i < n; ++i) {
15 if (x == forbidden_symbol_chars[i] || isspace(x)) {
23 static void skip_whitespaces(const char *str, size_t *cursor, size_t n)
28 while (*cursor < n && isspace(str[*cursor])) {
33 struct ParseResult parse_expr(const char *str,
40 /* TODO: parse_expr doesn't parse lists */
42 skip_whitespaces(str, cursor, n);
44 return parse_failure("EOF", *cursor);
47 switch (str[*cursor]) {
50 struct ParseResult car = parse_expr(str, cursor, n);
55 skip_whitespaces(str, cursor, n);
57 return parse_failure("EOF", *cursor);
60 if (str[*cursor] != '.') {
61 return parse_failure("Expected .", *cursor);
65 skip_whitespaces(str, cursor, n);
67 return parse_failure("EOF", *cursor);
70 struct ParseResult cdr = parse_expr(str, cursor, n);
75 skip_whitespaces(str, cursor, n);
77 return parse_failure("EOF", *cursor);
80 if (str[*cursor] != ')') {
81 return parse_failure("Expected )", *cursor);
86 return parse_success(cons_as_expr(create_cons(car.expr, cdr.expr)));
90 /* TODO(#292): parser does not support escaped string characters */
91 const size_t str_begin = *cursor + 1;
92 size_t str_end = str_begin;
94 while(str_end < n && str[str_end] != '"') {
99 return parse_failure("Unclosed string", str_begin);
102 *cursor = str_end + 1;
104 return parse_success(
106 create_string_atom(str + str_begin, str + str_end)));
110 if (isdigit(str[*cursor])) {
111 const char *nptr = str + *cursor;
113 const float x = strtof(nptr, &endptr);
115 if (nptr == endptr) {
116 return parse_failure("Number expected", *cursor);
119 *cursor += (size_t) (endptr - nptr);
121 return parse_success(atom_as_expr(create_number_atom(x)));
122 } else if (is_symbol_char(str[*cursor])) {
123 const size_t sym_begin = *cursor;
124 size_t sym_end = sym_begin;
126 while (sym_end < n && is_symbol_char(str[sym_end])) {
132 return parse_success(
134 create_symbol_atom(str + sym_begin, str + sym_end)));
139 return parse_failure("Unexpected sequence of characters", *cursor);
142 struct ParseResult parse_success(struct Expr expr)
144 struct ParseResult result = {
152 struct ParseResult parse_failure(const char *error_message,
155 struct ParseResult result = {
158 .error_message = error_message,
159 .error_cursor = error_cursor
166 void print_parse_error(FILE *stream,
168 struct ParseError error)
170 /* TODO(#293): print_parse_error doesn't support colors */
171 /* TODO(#294): print_parse_error doesn't support multiple lines */
173 fprintf(stream, "%s\n", str);
174 for (size_t i = 0; i < error.error_cursor; ++i) {
175 fprintf(stream, " ");
177 fprintf(stream, "^\n");
178 fprintf(stream, "%s\n", error.error_message);