1 /* Copyright (c) 2013, Vsevolod Stakhov
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are met:
6 * * Redistributions of source code must retain the above copyright
7 * notice, this list of conditions and the following disclaimer.
8 * * Redistributions in binary form must reproduce the above copyright
9 * notice, this list of conditions and the following disclaimer in the
10 * documentation and/or other materials provided with the distribution.
12 * THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY
13 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
14 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
15 * DISCLAIMED. IN NO EVENT SHALL AUTHOR BE LIABLE FOR ANY
16 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
17 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
18 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
19 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
20 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
21 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 #include "ucl_internal.h"
26 #include "ucl_chartable.h"
30 * The implementation of rcl parser
33 struct ucl_parser_saved_state {
37 const unsigned char *pos;
41 * Move up to len characters
45 * @return new position in chunk
47 #define ucl_chunk_skipc(chunk, p) do{ \
50 (chunk)->column = 0; \
52 else (chunk)->column ++; \
59 ucl_set_err (struct ucl_chunk *chunk, int code, const char *str, UT_string **err)
61 if (chunk->pos < chunk->end) {
62 if (isgraph (*chunk->pos)) {
63 ucl_create_err (err, "error on line %d at column %d: '%s', character: '%c'",
64 chunk->line, chunk->column, str, *chunk->pos);
67 ucl_create_err (err, "error on line %d at column %d: '%s', character: '0x%02x'",
68 chunk->line, chunk->column, str, (int)*chunk->pos);
72 ucl_create_err (err, "error at the end of chunk: %s", str);
77 * Skip all comments from the current pos resolving nested and multiline comments
82 ucl_skip_comments (struct ucl_parser *parser)
84 struct ucl_chunk *chunk = parser->chunks;
85 const unsigned char *p;
86 int comments_nested = 0;
92 if (parser->state != UCL_STATE_SCOMMENT &&
93 parser->state != UCL_STATE_MCOMMENT) {
94 while (p < chunk->end) {
96 ucl_chunk_skipc (chunk, p);
99 ucl_chunk_skipc (chunk, p);
103 else if (*p == '/' && chunk->remain >= 2) {
105 ucl_chunk_skipc (chunk, p);
107 ucl_chunk_skipc (chunk, p);
109 while (p < chunk->end) {
111 ucl_chunk_skipc (chunk, p);
114 if (comments_nested == 0) {
115 ucl_chunk_skipc (chunk, p);
119 ucl_chunk_skipc (chunk, p);
121 else if (p[0] == '/' && chunk->remain >= 2 && p[1] == '*') {
123 ucl_chunk_skipc (chunk, p);
124 ucl_chunk_skipc (chunk, p);
127 ucl_chunk_skipc (chunk, p);
129 if (comments_nested != 0) {
130 ucl_set_err (chunk, UCL_ENESTED, "unfinished multiline comment", &parser->err);
140 * Return multiplier for a character
141 * @param c multiplier character
142 * @param is_bytes if true use 1024 multiplier
145 static inline unsigned long
146 ucl_lex_num_multiplier (const unsigned char c, bool is_bytes) {
152 {'m', 1000 * 1000, 1024 * 1024},
154 {'g', 1000 * 1000 * 1000, 1024 * 1024 * 1024}
158 for (i = 0; i < 3; i ++) {
159 if (tolower (c) == multipliers[i].c) {
161 return multipliers[i].mult_bytes;
163 return multipliers[i].mult_normal;
172 * Return multiplier for time scaling
177 ucl_lex_time_multiplier (const unsigned char c) {
185 {'w', 60 * 60 * 24 * 7},
186 {'y', 60 * 60 * 24 * 7 * 365}
190 for (i = 0; i < 5; i ++) {
191 if (tolower (c) == multipliers[i].c) {
192 return multipliers[i].mult;
200 * Return true if a character is a end of an atom
205 ucl_lex_is_atom_end (const unsigned char c)
207 return ucl_test_character (c, UCL_CHARACTER_VALUE_END);
211 ucl_lex_is_comment (const unsigned char c1, const unsigned char c2)
218 else if (c1 == '#') {
225 * Check variable found
234 static inline const char *
235 ucl_check_variable_safe (struct ucl_parser *parser, const char *ptr, size_t remain,
236 size_t *out_len, bool strict, bool *found)
238 struct ucl_variable *var;
241 bool need_free = false;
243 LL_FOREACH (parser->variables, var) {
245 if (remain == var->var_len) {
246 if (memcmp (ptr, var->var, var->var_len) == 0) {
247 *out_len += var->value_len;
249 return (ptr + var->var_len);
254 if (remain >= var->var_len) {
255 if (memcmp (ptr, var->var, var->var_len) == 0) {
256 *out_len += var->value_len;
258 return (ptr + var->var_len);
264 /* XXX: can only handle ${VAR} */
265 if (!(*found) && parser->var_handler != NULL && strict) {
266 /* Call generic handler */
267 if (parser->var_handler (ptr, remain, &dst, &dstlen, &need_free,
273 return (ptr + remain);
281 * Check for a variable in a given string
290 ucl_check_variable (struct ucl_parser *parser, const char *ptr,
291 size_t remain, size_t *out_len, bool *vars_found)
293 const char *p, *end, *ret = ptr;
297 /* We need to match the variable enclosed in braces */
302 ret = ucl_check_variable_safe (parser, ptr + 1, p - ptr - 1,
303 out_len, true, &found);
305 /* {} must be excluded actually */
319 else if (*ptr != '$') {
320 /* Not count escaped dollar sign */
321 ret = ucl_check_variable_safe (parser, ptr, remain, out_len, false, &found);
322 if (found && !*vars_found) {
338 * Expand a single variable
346 ucl_expand_single_variable (struct ucl_parser *parser, const char *ptr,
347 size_t remain, unsigned char **dest)
349 unsigned char *d = *dest, *dst;
350 const char *p = ptr + 1, *ret;
351 struct ucl_variable *var;
353 bool need_free = false;
365 else if (*p == '{') {
372 LL_FOREACH (parser->variables, var) {
373 if (remain >= var->var_len) {
374 if (memcmp (p, var->var, var->var_len) == 0) {
375 memcpy (d, var->value, var->value_len);
384 if (strict && parser->var_handler != NULL) {
385 if (parser->var_handler (ptr, remain, &dst, &dstlen, &need_free,
387 memcpy (d, dst, dstlen);
394 /* Leave variable as is */
407 * Expand variables in string
415 ucl_expand_variable (struct ucl_parser *parser, unsigned char **dst,
416 const char *src, size_t in_len)
418 const char *p, *end = src + in_len;
421 bool vars_found = false;
426 p = ucl_check_variable (parser, p + 1, end - p - 1, &out_len, &vars_found);
440 *dst = UCL_ALLOC (out_len + 1);
449 p = ucl_expand_single_variable (parser, p, end - p, &d);
462 * Store or copy pointer to the trash stack
463 * @param parser parser object
464 * @param src src string
465 * @param dst destination buffer (trash stack pointer)
466 * @param dst_const const destination pointer (e.g. value of object)
467 * @param in_len input length
468 * @param need_unescape need to unescape source (and copy it)
469 * @param need_lowercase need to lowercase value (and copy)
470 * @param need_expand need to expand variables (and copy as well)
471 * @return output length (excluding \0 symbol)
473 static inline ssize_t
474 ucl_copy_or_store_ptr (struct ucl_parser *parser,
475 const unsigned char *src, unsigned char **dst,
476 const char **dst_const, size_t in_len,
477 bool need_unescape, bool need_lowercase, bool need_expand)
479 ssize_t ret = -1, tret;
482 if (need_unescape || need_lowercase ||
483 (need_expand && parser->variables != NULL) ||
484 !(parser->flags & UCL_PARSER_ZEROCOPY)) {
486 *dst = UCL_ALLOC (in_len + 1);
488 ucl_set_err (parser->chunks, 0, "cannot allocate memory for a string", &parser->err);
491 if (need_lowercase) {
492 ret = ucl_strlcpy_tolower (*dst, src, in_len + 1);
495 ret = ucl_strlcpy_unsafe (*dst, src, in_len + 1);
499 ret = ucl_unescape_json_string (*dst, ret);
504 ret = ucl_expand_variable (parser, dst, tmp, ret);
506 /* Nothing to expand */
522 * Create and append an object at the specified level
528 static inline ucl_object_t *
529 ucl_add_parser_stack (ucl_object_t *obj, struct ucl_parser *parser, bool is_array, int level)
531 struct ucl_stack *st;
535 obj = ucl_object_typed_new (UCL_OBJECT);
538 obj->type = UCL_OBJECT;
540 obj->value.ov = ucl_hash_create ();
541 parser->state = UCL_STATE_KEY;
545 obj = ucl_object_typed_new (UCL_ARRAY);
548 obj->type = UCL_ARRAY;
550 parser->state = UCL_STATE_VALUE;
553 st = UCL_ALLOC (sizeof (struct ucl_stack));
555 ucl_set_err (parser->chunks, 0, "cannot allocate memory for an object", &parser->err);
560 LL_PREPEND (parser->stack, st);
561 parser->cur_obj = obj;
567 ucl_maybe_parse_number (ucl_object_t *obj,
568 const char *start, const char *end, const char **pos,
569 bool allow_double, bool number_bytes, bool allow_time)
571 const char *p = start, *c = start;
573 bool got_dot = false, got_exp = false, need_double = false,
574 is_time = false, valid_start = false, is_hex = false,
585 if (is_hex && isxdigit (*p)) {
588 else if (isdigit (*p)) {
592 else if (!is_hex && (*p == 'x' || *p == 'X')) {
594 allow_double = false;
597 else if (allow_double) {
599 /* Empty digits sequence, not a number */
603 else if (*p == '.') {
605 /* Double dots, not a number */
615 else if (*p == 'e' || *p == 'E') {
617 /* Double exp, not a number */
629 if (!isdigit (*p) && *p != '+' && *p != '-') {
630 /* Wrong exponent sign */
640 /* Got the end of the number, need to check */
656 dv = strtod (c, &endptr);
660 lv = strtoimax (c, &endptr, 16);
663 lv = strtoimax (c, &endptr, 10);
666 if (errno == ERANGE) {
671 /* Now check endptr */
672 if (endptr == NULL || ucl_lex_is_atom_end (*endptr) || *endptr == '\0' ||
673 ucl_test_character (*endptr, UCL_CHARACTER_WHITESPACE_UNSAFE)) {
678 if (endptr < end && endptr != start) {
688 if (p[1] == 's' || p[1] == 'S') {
695 if (p[0] == 'm' || p[0] == 'M') {
699 dv *= ucl_lex_num_multiplier (*p, false);
704 else if (number_bytes || (p[1] == 'b' || p[1] == 'B')) {
710 lv *= ucl_lex_num_multiplier (*p, true);
714 else if (ucl_lex_is_atom_end (p[1])) {
716 dv *= ucl_lex_num_multiplier (*p, false);
719 lv *= ucl_lex_num_multiplier (*p, number_bytes);
724 else if (allow_time && end - p >= 3) {
725 if (tolower (p[0]) == 'm' &&
726 tolower (p[1]) == 'i' &&
727 tolower (p[2]) == 'n') {
742 dv *= ucl_lex_num_multiplier (*p, false);
745 lv *= ucl_lex_num_multiplier (*p, number_bytes);
754 (p == end - 1 || ucl_lex_is_atom_end (p[1]))) {
773 (p == end - 1 || ucl_lex_is_atom_end (p[1]))) {
779 dv *= ucl_lex_time_multiplier (*p);
791 if (allow_double && (need_double || is_time)) {
793 obj->type = UCL_FLOAT;
796 obj->type = UCL_TIME;
798 obj->value.dv = is_neg ? (-dv) : dv;
802 obj->value.iv = is_neg ? (-lv) : lv;
809 * Parse possible number
812 * @return true if a number has been parsed
815 ucl_lex_number (struct ucl_parser *parser,
816 struct ucl_chunk *chunk, ucl_object_t *obj)
818 const unsigned char *pos;
821 ret = ucl_maybe_parse_number (obj, chunk->pos, chunk->end, (const char **)&pos,
822 true, false, ((parser->flags & UCL_PARSER_NO_TIME) == 0));
825 chunk->remain -= pos - chunk->pos;
826 chunk->column += pos - chunk->pos;
830 else if (ret == ERANGE) {
831 ucl_set_err (chunk, ERANGE, "numeric value out of range", &parser->err);
838 * Parse quoted string with possible escapes
841 * @return true if a string has been parsed
844 ucl_lex_json_string (struct ucl_parser *parser,
845 struct ucl_chunk *chunk, bool *need_unescape, bool *ucl_escape, bool *var_expand)
847 const unsigned char *p = chunk->pos;
851 while (p < chunk->end) {
854 /* Unmasked control character */
856 ucl_set_err (chunk, UCL_ESYNTAX, "unexpected newline", &parser->err);
859 ucl_set_err (chunk, UCL_ESYNTAX, "unexpected control character", &parser->err);
863 else if (c == '\\') {
864 ucl_chunk_skipc (chunk, p);
866 if (p >= chunk->end) {
867 ucl_set_err (chunk, UCL_ESYNTAX, "unfinished escape character", &parser->err);
870 else if (ucl_test_character (c, UCL_CHARACTER_ESCAPE)) {
872 ucl_chunk_skipc (chunk, p);
873 for (i = 0; i < 4 && p < chunk->end; i ++) {
874 if (!isxdigit (*p)) {
875 ucl_set_err (chunk, UCL_ESYNTAX, "invalid utf escape", &parser->err);
878 ucl_chunk_skipc (chunk, p);
880 if (p >= chunk->end) {
881 ucl_set_err (chunk, UCL_ESYNTAX, "unfinished escape character", &parser->err);
886 ucl_chunk_skipc (chunk, p);
889 *need_unescape = true;
894 ucl_chunk_skipc (chunk, p);
897 else if (ucl_test_character (c, UCL_CHARACTER_UCL_UNSAFE)) {
903 ucl_chunk_skipc (chunk, p);
906 ucl_set_err (chunk, UCL_ESYNTAX, "no quote at the end of json string", &parser->err);
911 * Parse a key in an object
914 * @return true if a key has been parsed
917 ucl_parse_key (struct ucl_parser *parser, struct ucl_chunk *chunk, bool *next_key, bool *end_of_object)
919 const unsigned char *p, *c = NULL, *end, *t;
920 const char *key = NULL;
921 bool got_quote = false, got_eq = false, got_semicolon = false,
922 need_unescape = false, ucl_escape = false, var_expand = false,
923 got_content = false, got_sep = false;
924 ucl_object_t *nobj, *tobj;
925 ucl_hash_t *container;
931 /* It is macro actually */
932 ucl_chunk_skipc (chunk, p);
933 parser->prev_state = parser->state;
934 parser->state = UCL_STATE_MACRO_NAME;
937 while (p < chunk->end) {
939 * A key must start with alpha, number, '/' or '_' and end with space character
942 if (chunk->remain >= 2 && ucl_lex_is_comment (p[0], p[1])) {
943 if (!ucl_skip_comments (parser)) {
948 else if (ucl_test_character (*p, UCL_CHARACTER_WHITESPACE_UNSAFE)) {
949 ucl_chunk_skipc (chunk, p);
951 else if (ucl_test_character (*p, UCL_CHARACTER_KEY_START)) {
952 /* The first symbol */
954 ucl_chunk_skipc (chunk, p);
957 else if (*p == '"') {
962 ucl_chunk_skipc (chunk, p);
964 else if (*p == '}') {
965 /* We have actually end of an object */
966 *end_of_object = true;
969 else if (*p == '.') {
970 ucl_chunk_skipc (chunk, p);
971 parser->prev_state = parser->state;
972 parser->state = UCL_STATE_MACRO_NAME;
976 /* Invalid identifier */
977 ucl_set_err (chunk, UCL_ESYNTAX, "key must begin with a letter", &parser->err);
982 /* Parse the body of a key */
984 if (ucl_test_character (*p, UCL_CHARACTER_KEY)) {
986 ucl_chunk_skipc (chunk, p);
988 else if (ucl_test_character (*p, UCL_CHARACTER_KEY_SEP)) {
993 ucl_set_err (chunk, UCL_ESYNTAX, "invalid character in a key", &parser->err);
998 /* We need to parse json like quoted string */
999 if (!ucl_lex_json_string (parser, chunk, &need_unescape, &ucl_escape, &var_expand)) {
1002 /* Always escape keys obtained via json */
1003 end = chunk->pos - 1;
1010 if (p >= chunk->end && got_content) {
1011 ucl_set_err (chunk, UCL_ESYNTAX, "unfinished key", &parser->err);
1014 else if (!got_content) {
1017 *end_of_object = false;
1018 /* We are now at the end of the key, need to parse the rest */
1019 while (p < chunk->end) {
1020 if (ucl_test_character (*p, UCL_CHARACTER_WHITESPACE)) {
1021 ucl_chunk_skipc (chunk, p);
1023 else if (*p == '=') {
1024 if (!got_eq && !got_semicolon) {
1025 ucl_chunk_skipc (chunk, p);
1029 ucl_set_err (chunk, UCL_ESYNTAX, "unexpected '=' character", &parser->err);
1033 else if (*p == ':') {
1034 if (!got_eq && !got_semicolon) {
1035 ucl_chunk_skipc (chunk, p);
1036 got_semicolon = true;
1039 ucl_set_err (chunk, UCL_ESYNTAX, "unexpected ':' character", &parser->err);
1043 else if (chunk->remain >= 2 && ucl_lex_is_comment (p[0], p[1])) {
1044 /* Check for comment */
1045 if (!ucl_skip_comments (parser)) {
1056 if (p >= chunk->end && got_content) {
1057 ucl_set_err (chunk, UCL_ESYNTAX, "unfinished key", &parser->err);
1061 got_sep = got_semicolon || got_eq;
1065 * Maybe we have more keys nested, so search for termination character.
1067 * 1) key1 key2 ... keyN [:=] value <- we treat that as error
1068 * 2) key1 ... keyN {} or [] <- we treat that as nested objects
1069 * 3) key1 value[;,\n] <- we treat that as linear object
1073 while (ucl_test_character (*t, UCL_CHARACTER_WHITESPACE)) {
1076 /* Check first non-space character after a key */
1077 if (*t != '{' && *t != '[') {
1078 while (t < chunk->end) {
1079 if (*t == ',' || *t == ';' || *t == '\n' || *t == '\r') {
1082 else if (*t == '{' || *t == '[') {
1091 /* Create a new object */
1092 nobj = ucl_object_new ();
1093 keylen = ucl_copy_or_store_ptr (parser, c, &nobj->trash_stack[UCL_TRASH_KEY],
1094 &key, end - c, need_unescape, parser->flags & UCL_PARSER_KEY_LOWERCASE, false);
1096 ucl_object_unref (nobj);
1099 else if (keylen == 0) {
1100 ucl_set_err (chunk, UCL_ESYNTAX, "empty keys are not allowed", &parser->err);
1101 ucl_object_unref (nobj);
1105 container = parser->stack->obj->value.ov;
1107 nobj->keylen = keylen;
1108 tobj = __DECONST (ucl_object_t *, ucl_hash_search_obj (container, nobj));
1110 container = ucl_hash_insert_object (container, nobj);
1113 parser->stack->obj->len ++;
1116 DL_APPEND (tobj, nobj);
1120 nobj->flags |= UCL_OBJECT_NEED_KEY_ESCAPE;
1122 parser->stack->obj->value.ov = container;
1124 parser->cur_obj = nobj;
1133 * @return true if a key has been parsed
1136 ucl_parse_string_value (struct ucl_parser *parser,
1137 struct ucl_chunk *chunk, bool *var_expand, bool *need_unescape)
1139 const unsigned char *p;
1141 UCL_BRACE_ROUND = 0,
1145 int braces[3][2] = {{0, 0}, {0, 0}, {0, 0}};
1149 while (p < chunk->end) {
1151 /* Skip pairs of figure braces */
1153 braces[UCL_BRACE_FIGURE][0] ++;
1155 else if (*p == '}') {
1156 braces[UCL_BRACE_FIGURE][1] ++;
1157 if (braces[UCL_BRACE_FIGURE][1] <= braces[UCL_BRACE_FIGURE][0]) {
1158 /* This is not a termination symbol, continue */
1159 ucl_chunk_skipc (chunk, p);
1163 /* Skip pairs of square braces */
1164 else if (*p == '[') {
1165 braces[UCL_BRACE_SQUARE][0] ++;
1167 else if (*p == ']') {
1168 braces[UCL_BRACE_SQUARE][1] ++;
1169 if (braces[UCL_BRACE_SQUARE][1] <= braces[UCL_BRACE_SQUARE][0]) {
1170 /* This is not a termination symbol, continue */
1171 ucl_chunk_skipc (chunk, p);
1175 else if (*p == '$') {
1178 else if (*p == '\\') {
1179 *need_unescape = true;
1180 ucl_chunk_skipc (chunk, p);
1181 if (p < chunk->end) {
1182 ucl_chunk_skipc (chunk, p);
1187 if (ucl_lex_is_atom_end (*p) || (chunk->remain >= 2 && ucl_lex_is_comment (p[0], p[1]))) {
1190 ucl_chunk_skipc (chunk, p);
1193 if (p >= chunk->end) {
1194 ucl_set_err (chunk, UCL_ESYNTAX, "unfinished value", &parser->err);
1202 * Parse multiline string ending with \n{term}\n
1207 * @return size of multiline string or 0 in case of error
1210 ucl_parse_multiline_string (struct ucl_parser *parser,
1211 struct ucl_chunk *chunk, const unsigned char *term,
1212 int term_len, unsigned char const **beg,
1215 const unsigned char *p, *c;
1216 bool newline = false;
1223 while (p < chunk->end) {
1225 if (chunk->end - p < term_len) {
1228 else if (memcmp (p, term, term_len) == 0 && (p[term_len] == '\n' || p[term_len] == '\r')) {
1230 chunk->remain -= term_len;
1231 chunk->pos = p + term_len;
1232 chunk->column = term_len;
1246 ucl_chunk_skipc (chunk, p);
1252 static ucl_object_t*
1253 ucl_get_value_object (struct ucl_parser *parser)
1255 ucl_object_t *t, *obj = NULL;
1257 if (parser->stack->obj->type == UCL_ARRAY) {
1258 /* Object must be allocated */
1259 obj = ucl_object_new ();
1260 t = parser->stack->obj->value.av;
1262 parser->cur_obj = obj;
1263 parser->stack->obj->value.av = t;
1264 parser->stack->obj->len ++;
1267 /* Object has been already allocated */
1268 obj = parser->cur_obj;
1281 ucl_parse_value (struct ucl_parser *parser, struct ucl_chunk *chunk)
1283 const unsigned char *p, *c;
1284 ucl_object_t *obj = NULL;
1285 unsigned int stripped_spaces;
1287 bool need_unescape = false, ucl_escape = false, var_expand = false;
1291 /* Skip any spaces and comments */
1292 if (ucl_test_character (*p, UCL_CHARACTER_WHITESPACE_UNSAFE) ||
1293 (chunk->remain >= 2 && ucl_lex_is_comment (p[0], p[1]))) {
1294 while (p < chunk->end && ucl_test_character (*p, UCL_CHARACTER_WHITESPACE_UNSAFE)) {
1295 ucl_chunk_skipc (chunk, p);
1297 if (!ucl_skip_comments (parser)) {
1303 while (p < chunk->end) {
1307 obj = ucl_get_value_object (parser);
1308 ucl_chunk_skipc (chunk, p);
1309 if (!ucl_lex_json_string (parser, chunk, &need_unescape, &ucl_escape, &var_expand)) {
1312 str_len = chunk->pos - c - 2;
1313 obj->type = UCL_STRING;
1314 if ((str_len = ucl_copy_or_store_ptr (parser, c + 1, &obj->trash_stack[UCL_TRASH_VALUE],
1315 &obj->value.sv, str_len, need_unescape, false, var_expand)) == -1) {
1319 parser->state = UCL_STATE_AFTER_VALUE;
1324 obj = ucl_get_value_object (parser);
1325 /* We have a new object */
1326 obj = ucl_add_parser_stack (obj, parser, false, parser->stack->level);
1331 ucl_chunk_skipc (chunk, p);
1335 obj = ucl_get_value_object (parser);
1336 /* We have a new array */
1337 obj = ucl_add_parser_stack (obj, parser, true, parser->stack->level);
1342 ucl_chunk_skipc (chunk, p);
1346 /* We have the array ending */
1347 if (parser->stack && parser->stack->obj->type == UCL_ARRAY) {
1348 parser->state = UCL_STATE_AFTER_VALUE;
1356 obj = ucl_get_value_object (parser);
1357 /* We have something like multiline value, which must be <<[A-Z]+\n */
1358 if (chunk->end - p > 3) {
1359 if (memcmp (p, "<<", 2) == 0) {
1361 /* We allow only uppercase characters in multiline definitions */
1362 while (p < chunk->end && *p >= 'A' && *p <= 'Z') {
1366 /* Set chunk positions and start multiline parsing */
1368 chunk->remain -= p - c;
1372 if ((str_len = ucl_parse_multiline_string (parser, chunk, c,
1373 p - c, &c, &var_expand)) == 0) {
1374 ucl_set_err (chunk, UCL_ESYNTAX, "unterminated multiline value", &parser->err);
1377 obj->type = UCL_STRING;
1378 if ((str_len = ucl_copy_or_store_ptr (parser, c, &obj->trash_stack[UCL_TRASH_VALUE],
1379 &obj->value.sv, str_len - 1, false, false, var_expand)) == -1) {
1383 parser->state = UCL_STATE_AFTER_VALUE;
1388 /* Fallback to ordinary strings */
1392 obj = ucl_get_value_object (parser);
1395 if (ucl_test_character (*p, UCL_CHARACTER_VALUE_DIGIT_START)) {
1396 if (!ucl_lex_number (parser, chunk, obj)) {
1397 if (parser->state == UCL_STATE_ERROR) {
1402 parser->state = UCL_STATE_AFTER_VALUE;
1405 /* Fallback to normal string */
1408 if (!ucl_parse_string_value (parser, chunk, &var_expand, &need_unescape)) {
1411 /* Cut trailing spaces */
1412 stripped_spaces = 0;
1413 while (ucl_test_character (*(chunk->pos - 1 - stripped_spaces),
1414 UCL_CHARACTER_WHITESPACE)) {
1417 str_len = chunk->pos - c - stripped_spaces;
1419 ucl_set_err (chunk, 0, "string value must not be empty", &parser->err);
1422 else if (str_len == 4 && memcmp (c, "null", 4) == 0) {
1424 obj->type = UCL_NULL;
1426 else if (!ucl_maybe_parse_boolean (obj, c, str_len)) {
1427 obj->type = UCL_STRING;
1428 if ((str_len = ucl_copy_or_store_ptr (parser, c, &obj->trash_stack[UCL_TRASH_VALUE],
1429 &obj->value.sv, str_len, need_unescape,
1430 false, var_expand)) == -1) {
1435 parser->state = UCL_STATE_AFTER_VALUE;
1447 * Handle after value data
1453 ucl_parse_after_value (struct ucl_parser *parser, struct ucl_chunk *chunk)
1455 const unsigned char *p;
1456 bool got_sep = false;
1457 struct ucl_stack *st;
1461 while (p < chunk->end) {
1462 if (ucl_test_character (*p, UCL_CHARACTER_WHITESPACE)) {
1463 /* Skip whitespaces */
1464 ucl_chunk_skipc (chunk, p);
1466 else if (chunk->remain >= 2 && ucl_lex_is_comment (p[0], p[1])) {
1468 if (!ucl_skip_comments (parser)) {
1471 /* Treat comment as a separator */
1475 else if (ucl_test_character (*p, UCL_CHARACTER_VALUE_END)) {
1476 if (*p == '}' || *p == ']') {
1477 if (parser->stack == NULL) {
1478 ucl_set_err (chunk, UCL_ESYNTAX, "end of array or object detected without corresponding start", &parser->err);
1481 if ((*p == '}' && parser->stack->obj->type == UCL_OBJECT) ||
1482 (*p == ']' && parser->stack->obj->type == UCL_ARRAY)) {
1484 /* Pop all nested objects from a stack */
1486 parser->stack = st->next;
1487 UCL_FREE (sizeof (struct ucl_stack), st);
1489 while (parser->stack != NULL) {
1491 if (st->next == NULL || st->next->level == st->level) {
1494 parser->stack = st->next;
1495 UCL_FREE (sizeof (struct ucl_stack), st);
1499 ucl_set_err (chunk, UCL_ESYNTAX, "unexpected terminating symbol detected", &parser->err);
1503 if (parser->stack == NULL) {
1504 /* Ignore everything after a top object */
1508 ucl_chunk_skipc (chunk, p);
1513 /* Got a separator */
1515 ucl_chunk_skipc (chunk, p);
1521 ucl_set_err (chunk, UCL_ESYNTAX, "delimiter is missing", &parser->err);
1538 ucl_parse_macro_value (struct ucl_parser *parser,
1539 struct ucl_chunk *chunk, struct ucl_macro *macro,
1540 unsigned char const **macro_start, size_t *macro_len)
1542 const unsigned char *p, *c;
1543 bool need_unescape = false, ucl_escape = false, var_expand = false;
1549 /* We have macro value encoded in quotes */
1551 ucl_chunk_skipc (chunk, p);
1552 if (!ucl_lex_json_string (parser, chunk, &need_unescape, &ucl_escape, &var_expand)) {
1556 *macro_start = c + 1;
1557 *macro_len = chunk->pos - c - 2;
1561 /* We got a multiline macro body */
1562 ucl_chunk_skipc (chunk, p);
1563 /* Skip spaces at the beginning */
1564 while (p < chunk->end) {
1565 if (ucl_test_character (*p, UCL_CHARACTER_WHITESPACE_UNSAFE)) {
1566 ucl_chunk_skipc (chunk, p);
1573 while (p < chunk->end) {
1577 ucl_chunk_skipc (chunk, p);
1581 ucl_chunk_skipc (chunk, p);
1584 /* Macro is not enclosed in quotes or braces */
1586 while (p < chunk->end) {
1587 if (ucl_lex_is_atom_end (*p)) {
1590 ucl_chunk_skipc (chunk, p);
1597 /* We are at the end of a macro */
1598 /* Skip ';' and space characters and return to previous state */
1599 while (p < chunk->end) {
1600 if (!ucl_test_character (*p, UCL_CHARACTER_WHITESPACE_UNSAFE) && *p != ';') {
1603 ucl_chunk_skipc (chunk, p);
1609 * Handle the main states of rcl parser
1610 * @param parser parser structure
1611 * @param data the pointer to the beginning of a chunk
1612 * @param len the length of a chunk
1613 * @return true if chunk has been parsed and false in case of error
1616 ucl_state_machine (struct ucl_parser *parser)
1619 struct ucl_chunk *chunk = parser->chunks;
1620 const unsigned char *p, *c = NULL, *macro_start = NULL;
1621 unsigned char *macro_escaped;
1622 size_t macro_len = 0;
1623 struct ucl_macro *macro = NULL;
1624 bool next_key = false, end_of_object = false;
1626 if (parser->top_obj == NULL) {
1627 if (*chunk->pos == '[') {
1628 obj = ucl_add_parser_stack (NULL, parser, true, 0);
1631 obj = ucl_add_parser_stack (NULL, parser, false, 0);
1636 parser->top_obj = obj;
1637 parser->cur_obj = obj;
1638 parser->state = UCL_STATE_INIT;
1642 while (chunk->pos < chunk->end) {
1643 switch (parser->state) {
1644 case UCL_STATE_INIT:
1646 * At the init state we can either go to the parse array or object
1647 * if we got [ or { correspondingly or can just treat new data as
1648 * a key of newly created object
1650 obj = parser->cur_obj;
1651 if (!ucl_skip_comments (parser)) {
1652 parser->prev_state = parser->state;
1653 parser->state = UCL_STATE_ERROR;
1659 parser->state = UCL_STATE_VALUE;
1660 ucl_chunk_skipc (chunk, p);
1663 parser->state = UCL_STATE_KEY;
1665 ucl_chunk_skipc (chunk, p);
1671 /* Skip any spaces */
1672 while (p < chunk->end && ucl_test_character (*p, UCL_CHARACTER_WHITESPACE_UNSAFE)) {
1673 ucl_chunk_skipc (chunk, p);
1676 /* We have the end of an object */
1677 parser->state = UCL_STATE_AFTER_VALUE;
1680 if (parser->stack == NULL) {
1681 /* No objects are on stack, but we want to parse a key */
1682 ucl_set_err (chunk, UCL_ESYNTAX, "top object is finished but the parser "
1683 "expects a key", &parser->err);
1684 parser->prev_state = parser->state;
1685 parser->state = UCL_STATE_ERROR;
1688 if (!ucl_parse_key (parser, chunk, &next_key, &end_of_object)) {
1689 parser->prev_state = parser->state;
1690 parser->state = UCL_STATE_ERROR;
1693 if (end_of_object) {
1695 parser->state = UCL_STATE_AFTER_VALUE;
1698 else if (parser->state != UCL_STATE_MACRO_NAME) {
1699 if (next_key && parser->stack->obj->type == UCL_OBJECT) {
1700 /* Parse more keys and nest objects accordingly */
1701 obj = ucl_add_parser_stack (parser->cur_obj, parser, false,
1702 parser->stack->level + 1);
1708 parser->state = UCL_STATE_VALUE;
1716 case UCL_STATE_VALUE:
1717 /* We need to check what we do have */
1718 if (!ucl_parse_value (parser, chunk)) {
1719 parser->prev_state = parser->state;
1720 parser->state = UCL_STATE_ERROR;
1723 /* State is set in ucl_parse_value call */
1726 case UCL_STATE_AFTER_VALUE:
1727 if (!ucl_parse_after_value (parser, chunk)) {
1728 parser->prev_state = parser->state;
1729 parser->state = UCL_STATE_ERROR;
1732 if (parser->stack != NULL) {
1733 if (parser->stack->obj->type == UCL_OBJECT) {
1734 parser->state = UCL_STATE_KEY;
1738 parser->state = UCL_STATE_VALUE;
1742 /* Skip everything at the end */
1747 case UCL_STATE_MACRO_NAME:
1748 if (!ucl_test_character (*p, UCL_CHARACTER_WHITESPACE_UNSAFE)) {
1749 ucl_chunk_skipc (chunk, p);
1751 else if (p - c > 0) {
1752 /* We got macro name */
1753 macro_len = (size_t)(p - c);
1754 HASH_FIND (hh, parser->macroes, c, macro_len, macro);
1755 if (macro == NULL) {
1756 ucl_create_err (&parser->err, "error on line %d at column %d: "
1757 "unknown macro: '%.*s', character: '%c'",
1758 chunk->line, chunk->column, (int)(p - c), c, *chunk->pos);
1759 parser->state = UCL_STATE_ERROR;
1762 /* Now we need to skip all spaces */
1763 while (p < chunk->end) {
1764 if (!ucl_test_character (*p, UCL_CHARACTER_WHITESPACE_UNSAFE)) {
1765 if (chunk->remain >= 2 && ucl_lex_is_comment (p[0], p[1])) {
1767 if (!ucl_skip_comments (parser)) {
1774 ucl_chunk_skipc (chunk, p);
1776 parser->state = UCL_STATE_MACRO;
1779 case UCL_STATE_MACRO:
1780 if (!ucl_parse_macro_value (parser, chunk, macro,
1781 ¯o_start, ¯o_len)) {
1782 parser->prev_state = parser->state;
1783 parser->state = UCL_STATE_ERROR;
1786 macro_len = ucl_expand_variable (parser, ¯o_escaped, macro_start, macro_len);
1787 parser->state = parser->prev_state;
1788 if (macro_escaped == NULL) {
1789 if (!macro->handler (macro_start, macro_len, macro->ud)) {
1794 if (!macro->handler (macro_escaped, macro_len, macro->ud)) {
1795 UCL_FREE (macro_len + 1, macro_escaped);
1798 UCL_FREE (macro_len + 1, macro_escaped);
1803 /* TODO: add all states */
1804 ucl_set_err (chunk, UCL_EINTERNAL, "internal error: parser is in an unknown state", &parser->err);
1805 parser->state = UCL_STATE_ERROR;
1814 ucl_parser_new (int flags)
1816 struct ucl_parser *new;
1818 new = UCL_ALLOC (sizeof (struct ucl_parser));
1822 memset (new, 0, sizeof (struct ucl_parser));
1824 ucl_parser_register_macro (new, "include", ucl_include_handler, new);
1825 ucl_parser_register_macro (new, "try_include", ucl_try_include_handler, new);
1826 ucl_parser_register_macro (new, "includes", ucl_includes_handler, new);
1830 /* Initial assumption about filevars */
1831 ucl_parser_set_filevars (new, NULL, false);
1838 ucl_parser_register_macro (struct ucl_parser *parser, const char *macro,
1839 ucl_macro_handler handler, void* ud)
1841 struct ucl_macro *new;
1843 if (macro == NULL || handler == NULL) {
1846 new = UCL_ALLOC (sizeof (struct ucl_macro));
1850 memset (new, 0, sizeof (struct ucl_macro));
1851 new->handler = handler;
1852 new->name = strdup (macro);
1854 HASH_ADD_KEYPTR (hh, parser->macroes, new->name, strlen (new->name), new);
1858 ucl_parser_register_variable (struct ucl_parser *parser, const char *var,
1861 struct ucl_variable *new = NULL, *cur;
1867 /* Find whether a variable already exists */
1868 LL_FOREACH (parser->variables, cur) {
1869 if (strcmp (cur->var, var) == 0) {
1875 if (value == NULL) {
1878 /* Remove variable */
1879 LL_DELETE (parser->variables, new);
1882 UCL_FREE (sizeof (struct ucl_variable), new);
1891 new = UCL_ALLOC (sizeof (struct ucl_variable));
1895 memset (new, 0, sizeof (struct ucl_variable));
1896 new->var = strdup (var);
1897 new->var_len = strlen (var);
1898 new->value = strdup (value);
1899 new->value_len = strlen (value);
1901 LL_PREPEND (parser->variables, new);
1905 new->value = strdup (value);
1906 new->value_len = strlen (value);
1912 ucl_parser_set_variables_handler (struct ucl_parser *parser,
1913 ucl_variable_handler handler, void *ud)
1915 parser->var_handler = handler;
1916 parser->var_data = ud;
1920 ucl_parser_add_chunk (struct ucl_parser *parser, const unsigned char *data,
1923 struct ucl_chunk *chunk;
1925 if (data == NULL || len == 0) {
1926 ucl_create_err (&parser->err, "invalid chunk added");
1929 if (parser->state != UCL_STATE_ERROR) {
1930 chunk = UCL_ALLOC (sizeof (struct ucl_chunk));
1931 if (chunk == NULL) {
1932 ucl_create_err (&parser->err, "cannot allocate chunk structure");
1935 chunk->begin = data;
1936 chunk->remain = len;
1937 chunk->pos = chunk->begin;
1938 chunk->end = chunk->begin + len;
1941 LL_PREPEND (parser->chunks, chunk);
1942 parser->recursion ++;
1943 if (parser->recursion > UCL_MAX_RECURSION) {
1944 ucl_create_err (&parser->err, "maximum include nesting limit is reached: %d",
1948 return ucl_state_machine (parser);
1951 ucl_create_err (&parser->err, "a parser is in an invalid state");
1957 ucl_parser_add_string (struct ucl_parser *parser, const char *data,
1961 ucl_create_err (&parser->err, "invalid string added");
1965 len = strlen (data);
1968 return ucl_parser_add_chunk (parser, (const unsigned char *)data, len);