5093e8b5167b61f19473e7536ab80d530ff36536
[project/jsonpath.git] / ast.c
1 /*
2 * Copyright (C) 2013-2014 Jo-Philipp Wich <jow@openwrt.org>
3 *
4 * Permission to use, copy, modify, and/or distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
16
17 #include "ast.h"
18 #include "lexer.h"
19
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <stdarg.h>
23 #include <string.h>
24 #include <libubox/utils.h>
25
26 struct jp_opcode *
27 jp_alloc_op(struct jp_state *s, int type, int num, char *str, ...)
28 {
29 va_list ap;
30 char *ptr;
31 struct jp_opcode *newop, *child;
32
33 newop = calloc_a(sizeof(*newop),
34 str ? &ptr : NULL, str ? strlen(str) + 1 : 0);
35
36 if (!newop)
37 {
38 fprintf(stderr, "Out of memory\n");
39 exit(127);
40 }
41
42 newop->type = type;
43 newop->num = num;
44
45 if (str)
46 newop->str = strcpy(ptr, str);
47
48 va_start(ap, str);
49
50 while ((child = va_arg(ap, void *)) != NULL)
51 if (!newop->down)
52 newop->down = child;
53 else
54 append_op(newop->down, child);
55
56 va_end(ap);
57
58 newop->next = s->pool;
59 s->pool = newop;
60
61 return newop;
62 }
63
64 void
65 jp_free(struct jp_state *s)
66 {
67 struct jp_opcode *op, *tmp;
68
69 for (op = s->pool; op;)
70 {
71 tmp = op->next;
72 free(op);
73 op = tmp;
74 }
75
76 if (s->error)
77 free(s->error);
78
79 free(s);
80 }
81
82 struct jp_state *
83 jp_parse(const char *expr)
84 {
85 struct jp_state *s;
86 struct jp_opcode *op;
87 const char *ptr = expr;
88 void *pParser;
89 int len = strlen(expr);
90 int mlen = 0;
91
92 s = calloc(1, sizeof(*s));
93
94 if (!s)
95 return NULL;
96
97 pParser = ParseAlloc(malloc);
98
99 if (!pParser)
100 return NULL;
101
102 while (len > 0)
103 {
104 s->off = (ptr - expr);
105
106 op = jp_get_token(s, ptr, &mlen);
107
108 if (mlen < 0)
109 {
110 s->erroff = s->off;
111 s->error = strdup((mlen == -3) ? "String too long" :
112 (mlen == -2) ? "Invalid escape sequence" :
113 (mlen == -1) ? "Unterminated string" :
114 "Unknown error");
115
116 goto out;
117 }
118
119 if (op)
120 Parse(pParser, op->type, op, s);
121
122 len -= mlen;
123 ptr += mlen;
124 }
125
126 Parse(pParser, 0, NULL, s);
127
128 out:
129 ParseFree(pParser, free);
130
131 return s;
132 }