4 * (c) 2007 Martin Mares <mj@ucw.cz>
14 #define DEFAULT_MAX_TOKEN (32 << 20)
16 void tok_init(struct tokenizer *t, struct stream *s)
18 memset(t, 0, sizeof(*t));
21 t->token = xmalloc(t->bufsize);
22 t->maxsize = DEFAULT_MAX_TOKEN;
26 void tok_cleanup(struct tokenizer *t)
31 void tok_err(struct tokenizer *t, char *msg)
33 die("%s:%d: %s", t->stream->name, t->line, msg);
36 static inline int is_white(int c)
38 return (c == ' ' || c == '\t' || c == '\r' || c == '\n');
41 char *get_token(struct tokenizer *t)
55 if (t->flags & TF_REPORT_LINES)
65 // This is the token itself
69 if (len >= t->bufsize)
71 if (len >= t->maxsize)
72 tok_err(t, "Token too long");
74 if (t->bufsize > t->maxsize)
75 t->bufsize = t->maxsize;
76 t->token = xrealloc(t->token, t->bufsize);
80 while (c >= 0 && !is_white(c));
90 * Parsing functions. They return 1 if successfully parsed, 0 otherwise.
93 #define PARSE(f, ...) \
96 *x = f(t->token, &end, ##__VA_ARGS__); \
97 return !(errno || (unsigned char *) end != t->token + t->toksize)
99 int to_long(struct tokenizer *t, long int *x)
104 int to_ulong(struct tokenizer *t, unsigned long int *x)
106 if (t->token[0] == '-') // strtoul accepts negative numbers, but we don't
111 int to_double(struct tokenizer *t, double *x)
116 int to_long_double(struct tokenizer *t, long double *x)
121 int to_int(struct tokenizer *t, int *x)
124 if (!to_long(t, &y) || y > LONG_MAX || y < LONG_MIN)
130 int to_uint(struct tokenizer *t, unsigned int *x)
133 if (!to_ulong(t, &y) || y > ULONG_MAX)
139 #define GET(fn, type) \
140 type get_##fn(struct tokenizer *t) \
144 tok_err(t, "Unexpected end of file"); \
145 if (!to_##fn(t, &x)) \
146 tok_err(t, "Expected " #fn); \
151 GET(uint, unsigned int)
153 GET(ulong, unsigned long int)
155 GET(long_double, long double)