2
* Copyright 2006-2008 Ondrej Jirman <ondrej.jirman@zonio.net>
4
* This file is part of libxr.
6
* Libxr is free software: you can redistribute it and/or modify it under the
7
* terms of the GNU Lesser General Public License as published by the Free
8
* Software Foundation, either version 2 of the License, or (at your option) any
11
* Libxr is distributed in the hope that it will be useful, but WITHOUT ANY
12
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
13
* A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
16
* You should have received a copy of the GNU Lesser General Public License
17
* along with libxr. If not, see <http://www.gnu.org/licenses/>.
20
#include "parser-lib.h"
24
stream* stream_new_from_string(const char* str)
28
stream* s = g_new0(stream, 1);
29
s->buffer = g_strdup(str);
30
s->length = strlen(str);
34
void stream_advance(stream* s, int length)
38
for (i = 0; i < length && s->index < s->length; i++, s->index++)
41
if (s->buffer[s->index] == '\n')
51
token *token_new(stream* s, int type, int length)
54
token *t = g_new0(token, 1);
57
t->text = g_strndup(s->buffer + s->index, length);
59
t->sline = t->eline = s->line;
60
t->scol = t->ecol = s->col;
61
for (i = 0; i < length; i++)
64
if (t->text[i] == '\n')
70
stream_advance(s, length);
74
void token_free(token * t)
84
static int __parse(parser_context* ctx,
86
parser_alloc parser_alloc_cb,
87
parser_free parser_free_cb,
92
stream* s = ctx->stream;
95
if (ctx == NULL || ctx->error != NULL || ctx->stream == NULL)
98
parser = parser_alloc_cb((void *(*)(size_t))g_malloc);
99
while ((t = lexer_cb(s)) != NULL)
101
if (t->type == TK_UNKNOWN)
103
ctx->error = g_strdup_printf("Unknown token '%s' at line %d char %d\n", t->text, t->sline, t->scol);
107
else if (t->type == TK_EOF)
110
parser_cb(parser, 0, NULL, ctx);
114
parser_cb(parser, t->type, t, ctx);
121
parser_free_cb(parser, g_free);
125
void* __parse_string(const char* str,
128
parser_alloc parser_alloc_cb,
129
parser_free parser_free_cb,
132
parser_context* ctx = g_new0(parser_context, 1);
134
ctx->stream = stream_new_from_string(str);
135
if (ctx->stream == NULL)
138
g_set_error(err, 0, 1, "Stream can't be created!");
142
__parse(ctx, parser_cb, parser_alloc_cb, parser_free_cb, lexer_cb);
145
g_set_error(err, 0, 1, "%s", ctx->error);
149
void* data = ctx->data;
154
void* __parse_file(const char* path,
157
parser_alloc parser_alloc_cb,
158
parser_free parser_free_cb,
162
if (!g_file_get_contents(path, &buffer, NULL, err))
164
return __parse_string(buffer, err, parser_cb, parser_alloc_cb, parser_free_cb, lexer_cb);