json.peg 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. # json language lexer+parser to use with packcc parser generator
  2. %prefix "json"
  3. %source{
  4. #include <stdio.h>
  5. static const char *dbg_str[] = { "Evaluating rule", "Matched rule", "Abandoning rule" };
  6. #define PCC_DEBUG(event, rule, level, pos, buffer, length) \
  7. fprintf(stdout, "%*s%s %s @%d [%.*s]\n", (int)(level * 2), "", dbg_str[event], rule, (int)pos, (int)length, buffer); fflush(stdout)
  8. /* NOTE: To guarantee the output order, stderr, which can lead a race condition with stdout, is not used. */
  9. }
  10. JSON <- JSONObject !.
  11. JSONObject <- _ '{' _ (Pair _ (_ ',' _ Pair)*)* _ '}' _
  12. Pair <- String _ ':' _ Value
  13. Array <- _ '[' _ (Value (_ ',' _ Value)* )? _ ']' _
  14. Value <-
  15. String
  16. / Number
  17. / JSONObject
  18. / Array
  19. / True
  20. / False
  21. / Null
  22. True <- "true" _
  23. False <- "false" _
  24. Null <- "null" _
  25. String <- '"' Char* '"' _
  26. Char <-
  27. '\\' "\""
  28. / '\\' '\\'
  29. / '\\' '/'
  30. / '\\' 'b'
  31. / '\\' 'f'
  32. / '\\' 'n'
  33. / '\\' 'r'
  34. / '\\' 't'
  35. / '\\' 'u' Hex Hex Hex Hex
  36. / (!"\"" .)
  37. Number <- minus? int frac? exp?
  38. decimal_point <- '.'
  39. digit1_9 <- [1-9]
  40. e <- ['e''E']
  41. exp <- e (minus / plus)? Digit+
  42. frac <- decimal_point Digit+
  43. int <- zero / (digit1_9 Digit*)
  44. minus <- '-'
  45. plus <- '+'
  46. zero <- '0'
  47. Digit <- [0-9]
  48. Hex <- [0-9A-Fa-f] _
  49. _ <- (space / comment)*
  50. space <- (' ' / '\t' / endofline)
  51. comment <- '#' (!endofline .)*
  52. endofline <- ( '\r\n' / '\n' / '\r' / '\n\r' ) { }
  53. %%
  54. int main() {
  55. json_context_t *ctx = json_create(NULL);
  56. while (json_parse(ctx, NULL)){;}
  57. json_destroy(ctx);
  58. return 0;
  59. }