source: mainline/uspace/app/bithenge/script.c@ 978ccaf1

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 978ccaf1 was 978ccaf1, checked in by Sean Bartell <wingedtachikoma@…>, 13 years ago

Bithenge: various cleanup and tweaks

  • Property mode set to 100644
File size: 12.2 KB
Line 
1/*
2 * Copyright (c) 2012 Sean Bartell
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
9 * - Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * - The name of the author may not be used to endorse or promote products
15 * derived from this software without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29/** @addtogroup bithenge
30 * @{
31 */
32/**
33 * @file
34 * Script parsing.
35 */
36
37#include <ctype.h>
38#include <stdio.h>
39#include <stdlib.h>
40#include "os.h"
41#include "script.h"
42#include "transform.h"
43#include "tree.h"
44
45/** Tokens with more characters than this may be read incorrectly. */
46#define MAX_TOKEN_SIZE 256
47#define BUFFER_SIZE 4096
48
49/** Single-character symbols are represented by the character itself. Every
50 * other token uses one of these values: */
51typedef enum {
52 TOKEN_ERROR = -128,
53 TOKEN_EOF,
54 TOKEN_IDENTIFIER,
55 TOKEN_LEFT_ARROW,
56
57 /* Keywords */
58 TOKEN_STRUCT,
59 TOKEN_TRANSFORM,
60} token_type_t;
61
62/** Singly-linked list of named transforms. */
63typedef struct transform_list {
64 char *name;
65 bithenge_transform_t *transform;
66 struct transform_list *next;
67} transform_list_t;
68
69/** State kept by the parser. */
70typedef struct {
71 /** Rather than constantly checking return values, the parser uses this
72 * to indicate whether an error has occurred. */
73 int error;
74 /** The list of named transforms. */
75 transform_list_t *transform_list;
76 /** The name of the script file. */
77 const char *filename;
78 /** The script file being read from. */
79 FILE *file;
80 /** The buffer that holds script code. There is always a '\0' after the
81 * current position to prevent reading too far. */
82 char buffer[BUFFER_SIZE];
83 /** The start position within the buffer of the next unread token. */
84 size_t buffer_pos;
85 /** The start position within the buffer of the current token. */
86 size_t old_buffer_pos;
87 /** The line number of the current token. */
88 int lineno;
89 /** Added to a buffer position to find the column number. */
90 int line_offset;
91 /** The type of the current token. */
92 token_type_t token;
93 union {
94 /** The value of a TOKEN_IDENTIFIER token. Unless changed to
95 * NULL, it will be freed when the next token is read. */
96 char *token_string;
97 };
98} state_t;
99
100/** Free the previous token's data. This must be called before changing
101 * state->token. */
102static void done_with_token(state_t *state)
103{
104 if (state->token == TOKEN_IDENTIFIER)
105 free(state->token_string);
106 state->token = TOKEN_ERROR;
107}
108
109/** Note that an error has occurred. */
110static void error_errno(state_t *state, int error)
111{
112 // Don't overwrite a previous error.
113 if (state->error == EOK) {
114 done_with_token(state);
115 state->token = TOKEN_ERROR;
116 state->error = error;
117 }
118}
119
120/** Note that a syntax error has occurred and print an error message. */
121static void syntax_error(state_t *state, const char *message)
122{
123 // Printing multiple errors is confusing.
124 if (state->error == EOK) {
125 size_t start_char = state->old_buffer_pos + state->line_offset;
126 size_t end_char = state->buffer_pos + state->line_offset;
127 size_t size = end_char - start_char;
128 fprintf(stderr, "%s:%d:", state->filename, state->lineno);
129 if (size <= 1)
130 fprintf(stderr, "%zd: ", start_char);
131 else
132 fprintf(stderr, "%zd-%zd: ", start_char, end_char - 1);
133 fprintf(stderr, "%s: \"%.*s\"\n", message, (int)size,
134 state->buffer + state->old_buffer_pos);
135 error_errno(state, EINVAL);
136 }
137}
138
139/** Ensure the buffer contains enough characters to read a token. */
140static void fill_buffer(state_t *state)
141{
142 if (state->buffer_pos + MAX_TOKEN_SIZE < BUFFER_SIZE)
143 return;
144
145 size_t empty_size = state->buffer_pos;
146 size_t used_size = BUFFER_SIZE - 1 - state->buffer_pos;
147 memmove(state->buffer, state->buffer + state->buffer_pos, used_size);
148 state->line_offset += state->buffer_pos;
149 state->buffer_pos = 0;
150
151 size_t read_size = fread(state->buffer + used_size, 1, empty_size,
152 state->file);
153 if (ferror(state->file))
154 error_errno(state, EIO);
155 state->buffer[used_size + read_size] = '\0';
156}
157
158/** Read the next token. */
159static void next_token(state_t *state)
160{
161 fill_buffer(state);
162 done_with_token(state);
163 state->old_buffer_pos = state->buffer_pos;
164 char ch = state->buffer[state->buffer_pos];
165 if (ch == '\0') {
166 state->token = TOKEN_EOF;
167 } else if (isspace(ch)) {
168 // Will eventually reach the '\0' at the end
169 while (isspace(state->buffer[state->buffer_pos])) {
170 if (state->buffer[state->buffer_pos] == '\n') {
171 state->lineno++;
172 state->line_offset = -state->buffer_pos;
173 }
174 state->buffer_pos++;
175 }
176 next_token(state);
177 return;
178 } else if (isalpha(ch)) {
179 while (isalnum(state->buffer[state->buffer_pos]))
180 state->buffer_pos++;
181 char *value = str_ndup(state->buffer + state->old_buffer_pos,
182 state->buffer_pos - state->old_buffer_pos);
183 if (!value) {
184 error_errno(state, ENOMEM);
185 } else if (!str_cmp(value, "struct")) {
186 state->token = TOKEN_STRUCT;
187 free(value);
188 } else if (!str_cmp(value, "transform")) {
189 state->token = TOKEN_TRANSFORM;
190 free(value);
191 } else {
192 state->token = TOKEN_IDENTIFIER;
193 state->token_string = value;
194 }
195 } else if (ch == '<') {
196 state->token = ch;
197 state->buffer_pos++;
198 if (state->buffer[state->buffer_pos] == '-') {
199 state->buffer_pos++;
200 state->token = TOKEN_LEFT_ARROW;
201 }
202 } else {
203 state->token = ch;
204 state->buffer_pos++;
205 }
206}
207
208/** Allocate memory and handle failure by setting the error in the state. The
209 * caller must check the state for errors before using the return value of this
210 * function. */
211static void *state_malloc(state_t *state, size_t size)
212{
213 if (state->error != EOK)
214 return NULL;
215 void *result = malloc(size);
216 if (result == NULL)
217 error_errno(state, ENOMEM);
218 return result;
219}
220
221/** Reallocate memory and handle failure by setting the error in the state. If
222 * an error occurs, the existing pointer will be returned. */
223static void *state_realloc(state_t *state, void *ptr, size_t size)
224{
225 if (state->error != EOK)
226 return ptr;
227 void *result = realloc(ptr, size);
228 if (result == NULL) {
229 error_errno(state, ENOMEM);
230 return ptr;
231 }
232 return result;
233}
234
235/** Expect and consume a certain token. If the next token is of the wrong type,
236 * an error is caused. */
237static void expect(state_t *state, token_type_t type)
238{
239 if (state->token != type) {
240 syntax_error(state, "unexpected");
241 return;
242 }
243 next_token(state);
244}
245
246/** Expect and consume an identifier token. If the next token is not an
247 * identifier, an error is caused and this function returns null. */
248static char *expect_identifier(state_t *state)
249{
250 if (state->token != TOKEN_IDENTIFIER) {
251 syntax_error(state, "unexpected (identifier expected)");
252 return NULL;
253 }
254 char *val = state->token_string;
255 state->token_string = NULL;
256 next_token(state);
257 return val;
258}
259
260/** Find a transform by name. A reference will be added to the transform.
261 * @return The found transform, or NULL if none was found. */
262static bithenge_transform_t *get_named_transform(state_t *state,
263 const char *name)
264{
265 for (transform_list_t *e = state->transform_list; e; e = e->next) {
266 if (!str_cmp(e->name, name)) {
267 bithenge_transform_inc_ref(e->transform);
268 return e->transform;
269 }
270 }
271 for (int i = 0; bithenge_primitive_transforms[i].name; i++) {
272 if (!str_cmp(bithenge_primitive_transforms[i].name, name)) {
273 bithenge_transform_t *xform =
274 bithenge_primitive_transforms[i].transform;
275 bithenge_transform_inc_ref(xform);
276 return xform;
277 }
278 }
279 return NULL;
280}
281
282/** Add a named transform. This function takes ownership of the name and a
283 * reference to the transform. If an error has occurred, either may be null. */
284static void add_named_transform(state_t *state, bithenge_transform_t *xform, char *name)
285{
286 transform_list_t *entry = state_malloc(state, sizeof(*entry));
287 if (state->error != EOK) {
288 free(name);
289 bithenge_transform_dec_ref(xform);
290 free(entry);
291 return;
292 }
293 entry->name = name;
294 entry->transform = xform;
295 entry->next = state->transform_list;
296 state->transform_list = entry;
297}
298
299static bithenge_transform_t *parse_transform(state_t *state);
300
301static bithenge_transform_t *parse_struct(state_t *state)
302{
303 size_t num = 0;
304 bithenge_named_transform_t *subxforms;
305 /* We keep an extra space for the {NULL, NULL} terminator. */
306 subxforms = state_malloc(state, sizeof(*subxforms));
307 expect(state, TOKEN_STRUCT);
308 expect(state, '{');
309 while (state->error == EOK && state->token != '}') {
310 expect(state, '.');
311 subxforms[num].name = expect_identifier(state);
312 expect(state, TOKEN_LEFT_ARROW);
313 subxforms[num].transform = parse_transform(state);
314 expect(state, ';');
315 num++;
316 subxforms = state_realloc(state, subxforms,
317 (num + 1)*sizeof(*subxforms));
318 }
319 expect(state, '}');
320
321 if (state->error != EOK) {
322 while (num--) {
323 free((void *)subxforms[num].name);
324 bithenge_transform_dec_ref(subxforms[num].transform);
325 }
326 free(subxforms);
327 return NULL;
328 }
329
330 subxforms[num].name = NULL;
331 subxforms[num].transform = NULL;
332 bithenge_transform_t *result;
333 int rc = bithenge_new_struct(&result, subxforms);
334 if (rc != EOK) {
335 error_errno(state, rc);
336 return NULL;
337 }
338 return result;
339}
340
341/** Parse a transform.
342 * @return The parsed transform, or NULL if an error occurred. */
343static bithenge_transform_t *parse_transform(state_t *state)
344{
345 if (state->token == TOKEN_IDENTIFIER) {
346 bithenge_transform_t *result = get_named_transform(state,
347 state->token_string);
348 if (!result)
349 syntax_error(state, "transform not found");
350 next_token(state);
351 return result;
352 } else if (state->token == TOKEN_STRUCT) {
353 return parse_struct(state);
354 } else {
355 syntax_error(state, "unexpected (transform expected)");
356 return NULL;
357 }
358}
359
360/** Parse a definition. */
361static void parse_definition(state_t *state)
362{
363 expect(state, TOKEN_TRANSFORM);
364 char *name = expect_identifier(state);
365 expect(state, '=');
366 bithenge_transform_t *xform = parse_transform(state);
367 expect(state, ';');
368 add_named_transform(state, xform, name);
369}
370
371/** Initialize the state. */
372static void state_init(state_t *state, const char *filename)
373{
374 state->error = EOK;
375 state->transform_list = NULL;
376 state->token = TOKEN_ERROR;
377 state->old_buffer_pos = state->buffer_pos = BUFFER_SIZE - 1;
378 state->lineno = 1;
379 state->line_offset = (int)-state->buffer_pos + 1;
380 state->filename = filename;
381 state->file = fopen(filename, "r");
382 if (!state->file) {
383 error_errno(state, errno);
384 } else {
385 next_token(state);
386 }
387}
388
389/** Destroy the state. */
390static void state_destroy(state_t *state)
391{
392 done_with_token(state);
393 state->token = TOKEN_ERROR;
394 fclose(state->file);
395 transform_list_t *entry = state->transform_list;
396 while (entry) {
397 transform_list_t *next = entry->next;
398 free(entry->name);
399 bithenge_transform_dec_ref(entry->transform);
400 free(entry);
401 entry = next;
402 }
403}
404
405/** Parse a script file.
406 * @param filename The name of the script file.
407 * @param[out] out Stores the "main" transform.
408 * @return EOK on success, EINVAL on syntax error, or an error code from
409 * errno.h. */
410int bithenge_parse_script(const char *filename, bithenge_transform_t **out)
411{
412 state_t state;
413 state_init(&state, filename);
414 while (state.error == EOK && state.token != TOKEN_EOF)
415 parse_definition(&state);
416 *out = get_named_transform(&state, "main");
417 int rc = state.error;
418 state_destroy(&state);
419 if (rc == EOK && !*out) {
420 fprintf(stderr, "no \"main\" transform\n");
421 rc = EINVAL;
422 }
423 return rc;
424}
425
426/** @}
427 */
Note: See TracBrowser for help on using the repository browser.