nt_lexer.re 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. #include "nt_grammar.h"
  2. #include "nt_parser.h"
  3. #define YYCTYPE unsigned char
  4. #define YYCURSOR it->cur
  5. #define YYMARKER it->mar
  6. #define YYLIMIT it->lim
  7. #define YYFILL fill(it) == 0
  8. /**
  9. * Max chunk size passed to scanner at each iteration.
  10. */
  11. #ifdef LSUP_RDF_STREAM_CHUNK_SIZE
  12. #define CHUNK_SIZE LSUP_RDF_STREAM_CHUNK_SIZE
  13. #else
  14. #define CHUNK_SIZE 8192
  15. #endif
  16. typedef struct {
  17. FILE * fh; // Input file handle.
  18. YYCTYPE buf[CHUNK_SIZE + 1],// Start of buffer.
  19. * lim, // Position after the last available
  20. // input character (YYLIMIT).
  21. * cur, // Next input character to be read
  22. // (YYCURSOR)
  23. * mar, // Most recent match (YYMARKER)
  24. * tok, // Start of current token.
  25. * bol; // Address of the beginning of the
  26. // current line (for debugging).
  27. unsigned line; // Current line no. (for debugging).
  28. unsigned ct; // Number of parsed triples.
  29. bool eof; // if we have reached EOF.
  30. /*!stags:re2c format = "YYCTYPE *@@;"; */
  31. } ParseIterator;
  32. // TODO The opposite of this is in codec_nt.c. Find a better place for both.
  33. static inline char unescape_char(const char c) {
  34. switch (c) {
  35. case 't': return '\t';
  36. case 'b': return '\b';
  37. case 'n': return '\n';
  38. case 'r': return '\r';
  39. case 'f': return '\f';
  40. default: return c;
  41. }
  42. }
  43. static int fill(ParseIterator *it)
  44. {
  45. if (it->eof) {
  46. return 1;
  47. }
  48. const size_t shift = it->tok - it->buf;
  49. if (shift < 1) {
  50. return 2;
  51. }
  52. log_debug ("Shifting bytes: %lu", shift);
  53. memmove(it->buf, it->tok, it->lim - it->tok);
  54. it->lim -= shift;
  55. it->cur -= shift;
  56. it->mar -= shift;
  57. it->tok -= shift;
  58. it->lim += fread(it->lim, 1, shift, it->fh);
  59. /*!stags:re2c format = "if (it->@@) it->@@ -= shift; "; */
  60. it->lim[0] = 0;
  61. it->eof |= it->lim < it->buf + CHUNK_SIZE;
  62. return 0;
  63. }
  64. static void parse_init(ParseIterator *it, FILE *fh)
  65. {
  66. it->fh = fh;
  67. it->cur = it->mar = it->tok = it->lim = it->buf + CHUNK_SIZE;
  68. it->line = 1;
  69. it->bol = it->buf;
  70. it->ct = 0;
  71. it->eof = 0;
  72. /*!stags:re2c format = "it->@@ = NULL; "; */
  73. fill (it);
  74. }
  75. /** @brief Replace \uxxxx and \Uxxxxxxxx with Unicode bytes.
  76. */
  77. static YYCTYPE *unescape_unicode (const YYCTYPE *esc_str, size_t size)
  78. {
  79. YYCTYPE *uc_str = malloc (size + 1);
  80. size_t j = 0;
  81. YYCTYPE tmp_chr[5];
  82. for (size_t i = 0; i < size;) {
  83. if (esc_str[i] == '\\') {
  84. i++; // Skip over '\\'
  85. // 4-hex sequence.
  86. if (esc_str[i] == 'u') {
  87. i ++; // Skip over 'u'
  88. // Use tmp_chr to hold the hex string for the code point.
  89. memcpy(tmp_chr, esc_str + i, sizeof (tmp_chr) - 1);
  90. tmp_chr[4] = '\0';
  91. uint32_t tmp_val = strtol ((char*)tmp_chr, NULL, 16);
  92. log_debug ("tmp_val: %d", tmp_val);
  93. // Reuse tmp_chr to hold the byte values for the code point.
  94. int nbytes = utf8_encode (tmp_val, tmp_chr);
  95. // Copy bytes into destination.
  96. memcpy (uc_str + j, tmp_chr, nbytes);
  97. log_debug ("UC byte value: %x %x", uc_str[j], uc_str[j + 1]);
  98. j += nbytes;
  99. i += 4;
  100. // 8-hex sequence.
  101. } else if (esc_str[i] == 'U') {
  102. i ++; // Skip over 'U'
  103. log_error ("UTF-16 sequence unescaping not yet implemented.");
  104. return NULL; // TODO encode UTF-16
  105. // Unescape other escaped characters.
  106. } else uc_str[j++] = unescape_char(esc_str[i++]);
  107. } else {
  108. // Copy ASCII char verbatim.
  109. uc_str[j++] = esc_str[i++];
  110. }
  111. }
  112. YYCTYPE *tmp = realloc (uc_str, j + 1);
  113. if (UNLIKELY (!tmp)) return NULL;
  114. uc_str = tmp;
  115. uc_str[j] = '\0';
  116. return uc_str;
  117. }
  118. // Parser interface.
  119. void *ParseAlloc();
  120. void Parse();
  121. void ParseFree();
  122. // Lexer.
  123. static int lex (ParseIterator *it, LSUP_Term **term)
  124. {
  125. const YYCTYPE *lit_data_e, *dtype_s, *lang_s;
  126. loop:
  127. it->tok = it->cur;
  128. *term = NULL;
  129. /*!re2c
  130. re2c:eof = 0;
  131. re2c:flags:8 = 1;
  132. re2c:flags:tags = 1;
  133. re2c:tags:expression = "it->@@";
  134. re2c:api:style = functions;
  135. re2c:define:YYFILL:naked = 1;
  136. // For unresolved and partially resolved inconsistencies of the spec, see
  137. // https://lists.w3.org/Archives/Public/public-rdf-comments/2017Jun/0000.html
  138. _WS = [\x09\x20];
  139. WS = _WS+;
  140. EOL = [\x0D\x0A] (_WS | [\x0D\x0A])*;
  141. DOT = [.];
  142. HEX = [0-9A-Fa-f];
  143. ECHAR = [\\] [tbnrf"'\\];
  144. UCHAR = "\\u" HEX{4} | "\\U" HEX{8};
  145. PN_CHARS_BASE = [A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\U00010000-\U000EFFFF];
  146. PN_CHARS_U = PN_CHARS_BASE | '_' | ':';
  147. PN_CHARS = PN_CHARS_U | '-' | [0-9\u00B7\u0300-\u036F\u203F-\u2040];
  148. IRI_CHARS = ([^\x00-\x20<>"{}|^`\\] | UCHAR)*;
  149. LITERAL_QUOTE = ["] ([^\x22\x5C\x0A\x0D] | ECHAR|UCHAR)* ["];
  150. LANGTAG = [@] [a-zA-Z]+ ("-" [a-zA-Z0-9]+)*;
  151. IRIREF = [<] IRI_CHARS [>];
  152. LITERAL = LITERAL_QUOTE @lit_data_e _WS* ("^^" _WS* @dtype_s IRIREF | @lang_s LANGTAG)?;
  153. BNODE = "_:" ((PN_CHARS_U | [0-9]) ((PN_CHARS | ".")* PN_CHARS)?);
  154. COMMENT = "#" .*;
  155. EOL {
  156. it->line ++;
  157. it->bol = YYCURSOR;
  158. log_debug ("New line: #%u.", it->line);
  159. return T_EOL;
  160. }
  161. $ {
  162. log_debug ("End of buffer.");
  163. return T_EOF;
  164. }
  165. IRIREF {
  166. YYCTYPE *data = unescape_unicode (it->tok + 1, YYCURSOR - it->tok - 2);
  167. log_debug ("URI data: %s", data);
  168. *term = LSUP_iriref_new ((char*)data, NULL);
  169. free (data);
  170. return T_IRIREF;
  171. }
  172. LITERAL {
  173. // Only unescape Unicode from data.
  174. size_t size = lit_data_e - it->tok - 2;
  175. YYCTYPE *data = unescape_unicode (it->tok + 1, size);
  176. log_trace ("Literal data: %s", data);
  177. char *metadata = NULL;
  178. const YYCTYPE *md_marker;
  179. LSUP_TermType type = LSUP_TERM_LITERAL;
  180. if (dtype_s) {
  181. md_marker = dtype_s;
  182. size = YYCURSOR - md_marker - 1;
  183. } else if (lang_s) {
  184. type = LSUP_TERM_LT_LITERAL;
  185. md_marker = lang_s;
  186. size = YYCURSOR - md_marker;
  187. } else md_marker = NULL;
  188. if (md_marker) {
  189. metadata = malloc (size);
  190. memcpy (metadata, md_marker + 1, size);
  191. metadata [size - 1] = '\0';
  192. log_trace ("metadata: %s", metadata);
  193. }
  194. if (type == LSUP_TERM_LITERAL) {
  195. LSUP_Term *dtype;
  196. dtype = (
  197. metadata ? LSUP_iriref_new ((char *) metadata, NULL) : NULL);
  198. *term = LSUP_literal_new ((char *) data, dtype);
  199. } else *term = LSUP_lt_literal_new ((char *) data, (char *) metadata);
  200. free (data);
  201. free (metadata);
  202. return T_LITERAL;
  203. }
  204. BNODE {
  205. YYCTYPE *data = unescape_unicode (it->tok + 2, YYCURSOR - it->tok - 2);
  206. log_debug ("BNode data: %s", data);
  207. *term = LSUP_term_new (LSUP_TERM_BNODE, (char*)data, NULL);
  208. free (data);
  209. return T_BNODE;
  210. }
  211. DOT {
  212. log_debug ("End of triple.");
  213. it->ct ++;
  214. return T_DOT;
  215. }
  216. WS {
  217. log_debug ("Separator.");
  218. return T_WS;
  219. }
  220. COMMENT {
  221. size_t size = YYCURSOR - it->tok + 1;
  222. YYCTYPE *data = malloc (size);
  223. memcpy (data, it->tok, size);
  224. data [size - 1] = '\0';
  225. log_debug ("Comment: `%s`", data);
  226. free (data);
  227. goto loop;
  228. }
  229. * {
  230. log_debug (
  231. "Invalid token @ %lu: %s (\\x%x)",
  232. YYCURSOR - it->buf - 1, it->tok, *it->tok);
  233. return -1;
  234. }
  235. */
  236. }
  237. LSUP_rc
  238. LSUP_nt_parse_term (const char *rep, const LSUP_NSMap *map, LSUP_Term **term)
  239. {
  240. FILE *fh = fmemopen ((void *)rep, strlen (rep), "r");
  241. ParseIterator it;
  242. parse_init (&it, fh);
  243. int ttype = lex (&it, term);
  244. fclose (fh);
  245. switch (ttype) {
  246. case T_IRIREF:
  247. case T_LITERAL:
  248. case T_BNODE:
  249. return LSUP_OK;
  250. default:
  251. return LSUP_VALUE_ERR;
  252. }
  253. }
  254. LSUP_rc
  255. LSUP_nt_parse_doc (FILE *fh, LSUP_Graph **gr_p, size_t *ct, char **err_p)
  256. {
  257. *err_p = NULL;
  258. *gr_p = NULL;
  259. ParseIterator parse_it;
  260. parse_init (&parse_it, fh);
  261. void *parser = ParseAlloc (malloc);
  262. LSUP_rc rc;
  263. LSUP_Graph *gr = LSUP_graph_new (
  264. LSUP_iriref_new (NULL, NULL), LSUP_STORE_HTABLE, NULL, NULL, 0);
  265. if (UNLIKELY (!gr)) return LSUP_MEM_ERR;
  266. LSUP_GraphIterator *it = LSUP_graph_add_init (gr);
  267. if (UNLIKELY (!it)) {
  268. LSUP_graph_free (gr);
  269. return LSUP_MEM_ERR;
  270. }
  271. LSUP_Term *term = NULL;
  272. for (;;) {
  273. int ttype = lex (&parse_it, &term);
  274. if (ttype == -1) {
  275. char token[16] = {'\0'};
  276. strncpy (token, (const char *)parse_it.tok, 15);
  277. char *err_start = "Parse error near token `";
  278. char err_info [64];
  279. sprintf(
  280. err_info, "[...]' at line %u, character %ld.\n",
  281. parse_it.line, parse_it.cur - parse_it.bol);
  282. size_t err_size = strlen (err_start) + 16 + strlen(err_info);
  283. char *err_str = malloc (err_size);
  284. sprintf (err_str, "%s%s%s", err_start, token, err_info);
  285. rc = LSUP_VALUE_ERR;
  286. *err_p = err_str;
  287. goto finally;
  288. }
  289. Parse (parser, ttype, term, it);
  290. if (ttype == T_EOF) break;
  291. };
  292. if (ct) *ct = parse_it.ct;
  293. log_info ("Parsed %u triples.", parse_it.ct);
  294. log_debug ("Graph size: %lu", LSUP_graph_size (gr));
  295. rc = parse_it.ct > 0 ? LSUP_OK : LSUP_NORESULT;
  296. *gr_p = gr;
  297. finally:
  298. Parse (parser, 0, NULL, it);
  299. ParseFree (parser, free);
  300. LSUP_graph_add_done (it);
  301. LSUP_term_free (term);
  302. if (rc < 0) LSUP_graph_free (gr);
  303. return rc;
  304. }