term.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053
  1. #include "tpl.h"
  2. #include "term.h"
  3. /** @brief tpl packing format for a term.
  4. *
  5. * The pack elements are: 1. term type (char); 2. data (string); 3. void* type
  6. * metadata, cast to 8-byte unsigned.
  7. */
  8. #define TERM_PACK_FMT "csU"
  9. #define MAX_VALID_TERM_TYPE LSUP_TERM_BNODE /* For type validation. */
  10. /*
  11. * Data structures.
  12. */
  13. /// Sub-match coordinates in IRI parsing results.
  14. typedef struct match_coord_t {
  15. size_t offset; ///< Offset of match from start of string.
  16. size_t size; ///< Length of match.
  17. } MatchCoord;
  18. /// Matching sub-patterns for IRI parts.
  19. struct iri_info_t {
  20. LSUP_NSMap * nsm; ///< NSM handle for prefixed IRI.
  21. MatchCoord prefix; ///< URI prefix (scheme + authority).
  22. MatchCoord path; ///< URI path (including fragment).
  23. MatchCoord frag; ///< URI fragment.
  24. };
  25. /// Key-term pair in term set.
  26. typedef struct keyed_term {
  27. LSUP_Key key; ///< Key (hash) of the term.
  28. LSUP_Term * term; ///< Term handle.
  29. } KeyedTerm;
  30. /** @brief Single link between a term and a term set.
  31. *
  32. * This link is not qualified and must not be used by itself. It belongs
  33. * in a #LSUP_LinkMap which qualifies all links of the same type.
  34. */
  35. typedef struct link {
  36. KeyedTerm * term; ///< Linked term.
  37. LSUP_TermSet * tset; ///< Term set linked to the term.
  38. } Link;
  39. /// Opaque link map iterator.
  40. struct link_map_iter {
  41. const LSUP_LinkMap *map; ///< Link map to iterate.
  42. size_t i; ///< Linking term loop cursor.
  43. size_t j; ///< Term set loop cursor.
  44. Link * link; ///< Current link being retrieved.
  45. };
  46. /*
  47. * A link map is thus nested:
  48. *
  49. * - A link map contains a hash map of Link instances (link).
  50. * - It also contains the single term that the other terms are related to
  51. * (linked_t).
  52. * - Each Link contains a KeyedTerm (term) and a TermSet (tset).
  53. * - Each term set is a hash map of KeyedTerm instances.
  54. * - Each KeyedTerm contains a Term and its hash.
  55. */
  56. typedef struct link_map {
  57. LSUP_LinkType type; ///< Link type.
  58. LSUP_Term *linked_t; ///< Linked term.
  59. struct hashmap *links; ///< Map of #Link instances.
  60. } LSUP_LinkMap;
  61. /*
  62. * External variables.
  63. */
  64. uint32_t LSUP_default_dtype_key = 0;
  65. LSUP_Term *LSUP_default_datatype = NULL;
  66. LSUP_TermSet *LSUP_term_cache = NULL;
  67. /*
  68. * Static variables.
  69. */
  70. // Characters not allowed in a URI string.
  71. static const char *invalid_uri_chars = "<>\" {}|\\^`";
  72. /// Minimum valid type code.
  73. static const LSUP_TermType MIN_VALID_TYPE = LSUP_TERM_IRIREF;
  74. /// Maximum valid type code. Change this if adding to enum LSUP_TermType.
  75. static const LSUP_TermType MAX_VALID_TYPE = LSUP_TERM_BNODE;
  76. /*
  77. * Static prototypes.
  78. */
  79. static LSUP_rc
  80. term_init (
  81. LSUP_Term *term, LSUP_TermType type, const char *data, void *metadata);
  82. /*
  83. * Term set callbacks.
  84. */
  85. static uint64_t
  86. tset_hash_fn (
  87. const void *item, uint64_t seed0, uint64_t seed1)
  88. { return ((const KeyedTerm *) item)->key; }
  89. static int
  90. tset_cmp_fn (const void *a, const void *b, void *udata)
  91. {
  92. return
  93. ((const KeyedTerm *) a)->key -
  94. ((const KeyedTerm *) b)->key;
  95. }
  96. static void
  97. tset_free_fn (void *item)
  98. { LSUP_term_free (((KeyedTerm *) item)->term); }
  99. /*
  100. * Link map callbacks.
  101. */
  102. static uint64_t
  103. link_map_hash_fn (
  104. const void *item, uint64_t seed0, uint64_t seed1)
  105. { return ((const Link *)item)->term->key; }
  106. static int
  107. link_map_cmp_fn (const void *a, const void *b, void *udata)
  108. {
  109. return
  110. ((const Link *)a)->term->key -
  111. ((const Link *)b)->term->key;
  112. }
  113. static void
  114. link_map_free_fn (void *item)
  115. {
  116. Link *link = item;
  117. LSUP_term_free (link->term->term);
  118. free (link->term);
  119. LSUP_term_set_free (link->tset);
  120. }
  121. static LSUP_rc parse_iri (char *iri, MatchCoord coords[]);
  122. /*
  123. * Term API.
  124. */
  125. LSUP_Term *
  126. LSUP_term_new (
  127. LSUP_TermType type, const char *data, void *metadata)
  128. {
  129. LSUP_Term *term;
  130. CALLOC_GUARD (term, NULL);
  131. if (UNLIKELY (term_init (
  132. term, type, data, metadata) != LSUP_OK)) {
  133. free (term);
  134. return NULL;
  135. }
  136. return term;
  137. }
  138. LSUP_Term *
  139. LSUP_term_copy (const LSUP_Term *src)
  140. {
  141. void *metadata = NULL;
  142. if (LSUP_IS_IRI (src))
  143. metadata = (void *) LSUP_iriref_nsm (src);
  144. else if (src->type == LSUP_TERM_LITERAL)
  145. metadata = (void *) src->datatype;
  146. else if (src->type == LSUP_TERM_LT_LITERAL) {
  147. metadata = (void *) src->lang;
  148. }
  149. return LSUP_term_new (src->type, src->data, metadata);
  150. }
  151. LSUP_Term *
  152. LSUP_term_new_from_buffer (const LSUP_Buffer *sterm)
  153. {
  154. if (UNLIKELY (!sterm)) return NULL;
  155. LSUP_Term *term = NULL;
  156. LSUP_TermType type = LSUP_TERM_UNDEFINED;
  157. char *data = NULL;
  158. void *metadata;
  159. tpl_node *tn;
  160. tn = tpl_map (TERM_PACK_FMT, &type, &data, &metadata);
  161. if (UNLIKELY (!tn)) goto finally;
  162. if (UNLIKELY (tpl_load (tn, TPL_MEM, sterm->addr, sterm->size) < 0)) {
  163. log_error ("Error loading serialized term.");
  164. goto finally;
  165. }
  166. if (UNLIKELY (tpl_unpack (tn, 0) < 0)) {
  167. log_error ("Error unpacking serialized term.");
  168. goto finally;
  169. }
  170. if (type == LSUP_TERM_LT_LITERAL)
  171. term = LSUP_lt_literal_new (data, (char *)&metadata);
  172. else term = LSUP_term_new (type, data, metadata);
  173. finally:
  174. tpl_free (tn);
  175. free (data);
  176. return term;
  177. }
  178. LSUP_Term *
  179. LSUP_iriref_absolute (const LSUP_Term *root, const LSUP_Term *iri)
  180. {
  181. if (! LSUP_IS_IRI (iri)) {
  182. log_error ("Provided path is not an IRI.");
  183. return NULL;
  184. }
  185. if (! LSUP_IS_IRI (root)) {
  186. log_error ("Provided root is not an IRI.");
  187. return NULL;
  188. }
  189. char
  190. *data,
  191. *pfx = LSUP_iriref_prefix (iri);
  192. if (strlen (pfx) > 0) data = iri->data;
  193. else if (iri->data[0] == '/') {
  194. free (pfx);
  195. pfx = LSUP_iriref_prefix (root);
  196. data = malloc (strlen (iri->data) + strlen (pfx) + 1);
  197. if (!data) return NULL;
  198. sprintf (data, "%s%s", pfx, iri->data);
  199. } else {
  200. data = malloc (strlen (iri->data) + strlen (root->data) + 1);
  201. if (!data) return NULL;
  202. sprintf (data, "%s%s", root->data, iri->data);
  203. }
  204. free (pfx);
  205. LSUP_Term *ret = LSUP_iriref_new (data, NULL);
  206. if (data != iri->data) free (data);
  207. return ret;
  208. }
  209. LSUP_Term *
  210. LSUP_iriref_relative (const LSUP_Term *root, const LSUP_Term *iri)
  211. {
  212. if (! LSUP_IS_IRI (iri)) {
  213. log_error ("Provided path is not an IRI.");
  214. return NULL;
  215. }
  216. if (! LSUP_IS_IRI (root)) {
  217. log_error ("Provided root is not an IRI.");
  218. return NULL;
  219. }
  220. size_t offset = (
  221. strstr (iri->data, root->data) == iri->data ?
  222. strlen (root->data) : 0);
  223. return LSUP_iriref_new (iri->data + offset, LSUP_iriref_nsm (iri));
  224. }
  225. LSUP_Buffer *
  226. LSUP_term_serialize (const LSUP_Term *term)
  227. {
  228. /*
  229. * In serializing a term, the fact that two terms of different types may
  230. * be semantically identical must be taken into account. Specifically, a
  231. * namespace-prefixed IRI ref is identical to its fully qualified version,
  232. * and a LSUP_TERM_LT_LITERAL with no language tag is identical to a
  233. * LSUP_TERM_LITERAL of xsd:string type, made up of the same string. Such
  234. * terms must have identical serializations.
  235. */
  236. if (UNLIKELY (!term)) return NULL;
  237. LSUP_Term *tmp_term;
  238. void *metadata = NULL;
  239. if (term->type == LSUP_TERM_NS_IRIREF) {
  240. // For IRI refs, simply serialize the FQ version of the term.
  241. char *fq_uri;
  242. if (LSUP_nsmap_normalize_uri (
  243. term->iri_info->nsm, term->data, &fq_uri
  244. ) < LSUP_OK) return NULL;
  245. tmp_term = LSUP_iriref_new (fq_uri, NULL);
  246. free (fq_uri);
  247. } else if (term->type == LSUP_TERM_LT_LITERAL) {
  248. // For LT literals with empty lang tag, convert to a normal xsd:string.
  249. if (strlen (term->lang) == 0)
  250. tmp_term = LSUP_literal_new (term->data, NULL);
  251. else tmp_term = LSUP_lt_literal_new (term->data, (char *) term->lang);
  252. } else tmp_term = LSUP_term_new (
  253. term->type, term->data, (void *) term->datatype);
  254. // "datatype" can be anything here since it's cast to void *.
  255. // metadata field is ignored for IRI ref.
  256. if (tmp_term->type == LSUP_TERM_LITERAL)
  257. metadata = tmp_term->datatype;
  258. else if (tmp_term->type == LSUP_TERM_LT_LITERAL)
  259. memcpy (&metadata, tmp_term->lang, sizeof (metadata));
  260. LSUP_Buffer *sterm;
  261. CALLOC_GUARD (sterm, NULL);
  262. //LOG_TRACE("Effective term being serialized: %s", tmp_term->data);
  263. int rc = tpl_jot (
  264. TPL_MEM, &sterm->addr, &sterm->size, TERM_PACK_FMT,
  265. &tmp_term->type, &tmp_term->data, &metadata);
  266. LSUP_term_free (tmp_term);
  267. if (rc != 0) {
  268. LSUP_buffer_free (sterm);
  269. return NULL;
  270. }
  271. return sterm;
  272. }
  273. LSUP_Key
  274. LSUP_term_hash (const LSUP_Term *term)
  275. {
  276. LSUP_Buffer *buf;
  277. if (UNLIKELY (!term)) buf = BUF_DUMMY;
  278. else buf = LSUP_term_serialize (term);
  279. LSUP_Key key = LSUP_buffer_hash (buf);
  280. LSUP_buffer_free (buf);
  281. return key;
  282. }
  283. void
  284. LSUP_term_free (LSUP_Term *term)
  285. {
  286. if (UNLIKELY (!term)) return;
  287. if (LSUP_IS_IRI (term)) free (term->iri_info);
  288. free (term->data);
  289. free (term);
  290. }
  291. LSUP_NSMap *
  292. LSUP_iriref_nsm (const LSUP_Term *iri)
  293. {
  294. if (iri->type != LSUP_TERM_IRIREF && iri->type != LSUP_TERM_NS_IRIREF) {
  295. log_error ("Term is not a IRI ref type.");
  296. return NULL;
  297. }
  298. return iri->iri_info->nsm;
  299. }
  300. char *
  301. LSUP_iriref_prefix (const LSUP_Term *iri)
  302. {
  303. if (iri->type != LSUP_TERM_IRIREF && iri->type != LSUP_TERM_NS_IRIREF) {
  304. log_error ("Term is not a IRI ref type.");
  305. return NULL;
  306. }
  307. // if (iri->iri_info->prefix.size == 0) return NULL;
  308. return strndup (
  309. iri->data + iri->iri_info->prefix.offset,
  310. iri->iri_info->prefix.size);
  311. }
  312. char *
  313. LSUP_iriref_path (const LSUP_Term *iri)
  314. {
  315. if (iri->type != LSUP_TERM_IRIREF && iri->type != LSUP_TERM_NS_IRIREF) {
  316. log_error ("Term is not a IRI ref type.");
  317. return NULL;
  318. }
  319. // if (iri->iri_info->path.size == 0) return NULL;
  320. return strndup (
  321. iri->data + iri->iri_info->path.offset,
  322. iri->iri_info->path.size);
  323. }
  324. char *
  325. LSUP_iriref_frag (const LSUP_Term *iri)
  326. {
  327. if (iri->type != LSUP_TERM_IRIREF && iri->type != LSUP_TERM_NS_IRIREF) {
  328. log_error ("Term is not a IRI ref type.");
  329. return NULL;
  330. }
  331. // if (iri->iri_info->frag.size == 0) return NULL;
  332. return strndup (
  333. iri->data + iri->iri_info->frag.offset,
  334. iri->iri_info->frag.size);
  335. }
  336. /*
  337. * Triple API.
  338. */
  339. LSUP_Triple *
  340. LSUP_triple_new(LSUP_Term *s, LSUP_Term *p, LSUP_Term *o)
  341. {
  342. LSUP_Triple *spo = malloc (sizeof (*spo));
  343. if (!spo) return NULL;
  344. if (UNLIKELY (LSUP_triple_init (spo, s, p, o))) {
  345. free (spo);
  346. return NULL;
  347. }
  348. return spo;
  349. }
  350. LSUP_Triple *
  351. LSUP_triple_new_from_btriple (const LSUP_BufferTriple *sspo)
  352. {
  353. LSUP_Triple *spo = malloc (sizeof (*spo));
  354. if (!spo) return NULL;
  355. spo->s = LSUP_term_new_from_buffer (sspo->s);
  356. spo->p = LSUP_term_new_from_buffer (sspo->p);
  357. spo->o = LSUP_term_new_from_buffer (sspo->o);
  358. return spo;
  359. }
  360. LSUP_BufferTriple *
  361. LSUP_triple_serialize (const LSUP_Triple *spo)
  362. {
  363. LSUP_BufferTriple *sspo = malloc (sizeof (*sspo));
  364. if (!sspo) return NULL;
  365. sspo->s = LSUP_term_serialize (spo->s);
  366. sspo->p = LSUP_term_serialize (spo->p);
  367. sspo->o = LSUP_term_serialize (spo->o);
  368. return sspo;
  369. }
  370. LSUP_rc
  371. LSUP_triple_init (LSUP_Triple *spo, LSUP_Term *s, LSUP_Term *p, LSUP_Term *o)
  372. {
  373. /* FIXME TRP_DUMMY is a problem here.
  374. if (! LSUP_IS_IRI (s) && s->type != LSUP_TERM_BNODE) {
  375. log_error ("Subject is not of a valid term type: %d", s->type);
  376. return LSUP_VALUE_ERR;
  377. }
  378. if (! LSUP_IS_IRI (p)) {
  379. log_error ("Predicate is not of a valid term type: %d", p->type);
  380. return LSUP_VALUE_ERR;
  381. }
  382. */
  383. spo->s = s;
  384. spo->p = p;
  385. spo->o = o;
  386. return LSUP_OK;
  387. }
  388. void
  389. LSUP_triple_done (LSUP_Triple *spo)
  390. {
  391. if (UNLIKELY (!spo)) return;
  392. LSUP_term_free (spo->s);
  393. LSUP_term_free (spo->p);
  394. LSUP_term_free (spo->o);
  395. }
  396. void
  397. LSUP_triple_free (LSUP_Triple *spo)
  398. {
  399. if (UNLIKELY (!spo)) return;
  400. LSUP_term_free (spo->s);
  401. LSUP_term_free (spo->p);
  402. LSUP_term_free (spo->o);
  403. free (spo);
  404. }
  405. /*
  406. * Multi-add functions.
  407. */
  408. LSUP_TermSet *
  409. LSUP_term_set_new ()
  410. {
  411. // Capacity of 4 is an arbitrary guess.
  412. LSUP_TermSet *ts = hashmap_new (
  413. sizeof (KeyedTerm), 4, LSUP_HASH_SEED, 0,
  414. tset_hash_fn, tset_cmp_fn, tset_free_fn, NULL);
  415. if (UNLIKELY (hashmap_oom (ts))) return NULL;
  416. return ts;
  417. }
  418. LSUP_rc
  419. LSUP_term_set_add (LSUP_TermSet *ts, LSUP_Term *term, LSUP_Term **existing)
  420. {
  421. LSUP_Hash key = LSUP_term_hash (term);
  422. KeyedTerm entry_s = {.key=key, .term=term};
  423. KeyedTerm *ex = hashmap_get (ts, &entry_s);
  424. if (ex) {
  425. if (existing) *existing = ex->term;
  426. return LSUP_NOACTION;
  427. }
  428. hashmap_set (ts, &entry_s);
  429. if (hashmap_oom (ts)) return LSUP_MEM_ERR;
  430. return LSUP_OK;
  431. }
  432. const LSUP_Term *
  433. LSUP_term_set_get (LSUP_TermSet *ts, LSUP_Key key)
  434. {
  435. KeyedTerm *entry = hashmap_get (ts, &(KeyedTerm){.key=key});
  436. if (entry) LOG_TRACE("ID found for key %lx: %s", key, entry->term->data);
  437. else LOG_TRACE("No ID found for key %lx.", key);
  438. return (entry) ? entry->term : NULL;
  439. }
  440. LSUP_rc
  441. LSUP_term_set_next (LSUP_TermSet *ts, size_t *i, LSUP_Term **term)
  442. {
  443. KeyedTerm *kt = NULL;
  444. if (!hashmap_iter (ts, i, (void **)&kt)) return LSUP_END;
  445. if (term) *term = kt->term;
  446. return LSUP_OK;
  447. }
  448. void
  449. LSUP_term_set_free (LSUP_TermSet *ts)
  450. { hashmap_free (ts); }
  451. LSUP_LinkMap *
  452. LSUP_link_map_new (const LSUP_Term *linked_term, LSUP_LinkType type)
  453. {
  454. LSUP_LinkMap *lm;
  455. MALLOC_GUARD (lm, NULL);
  456. lm->type = type;
  457. lm->links = hashmap_new (
  458. sizeof (Link), 0, LSUP_HASH_SEED, 0,
  459. link_map_hash_fn, link_map_cmp_fn, link_map_free_fn, NULL);
  460. if (!linked_term) {
  461. log_error ("term must not be NULL.");
  462. free (lm);
  463. return NULL;
  464. }
  465. lm->linked_t = LSUP_term_copy (linked_term);
  466. return lm;
  467. }
  468. void
  469. LSUP_link_map_free (LSUP_LinkMap *lm)
  470. {
  471. hashmap_free (lm->links);
  472. LSUP_term_free (lm->linked_t);
  473. free (lm);
  474. }
  475. LSUP_LinkType
  476. LSUP_link_map_type (const LSUP_LinkMap *map)
  477. { return map->type; }
  478. // TODO Memory error handling.
  479. LSUP_rc
  480. LSUP_link_map_add (
  481. LSUP_LinkMap *lmap, LSUP_Term *term, LSUP_TermSet *tset)
  482. {
  483. // Keyed term to look up the link term and insert it, if necessary.
  484. KeyedTerm entry_s = {.key=LSUP_term_hash (term), .term=term};
  485. Link *ex = hashmap_get (lmap->links, &(Link){.term=&entry_s});
  486. if (ex) {
  487. // Add terms one by one to the existing term set.
  488. LOG_TRACE(
  489. "Linking term %s exists. Adding individual terms.",
  490. ex->term->term->data);
  491. size_t i = 0;
  492. KeyedTerm *kt;
  493. while (hashmap_iter (tset, &i, (void **)&kt)) {
  494. LOG_TRACE(
  495. "Adding term %s to link %s",
  496. kt->term->data, ex->term->term->data);
  497. if (hashmap_get (ex->tset, kt))
  498. // Term already exist, free the new one and move on.
  499. LSUP_term_free (kt->term);
  500. else
  501. // Insert KeyedTerm, the term set now owns the underlying term.
  502. hashmap_set (ex->tset, kt);
  503. }
  504. // Free link term that hasn't been used.
  505. LSUP_term_free (term);
  506. } else {
  507. // Add the new term and the termset wholesale.
  508. LOG_TRACE("Adding new linking term %s.", term->data);
  509. // Allocate inserted member on heap, it will be owned by the map.
  510. KeyedTerm *ins;
  511. MALLOC_GUARD (ins, LSUP_MEM_ERR);
  512. memcpy (ins, &entry_s, sizeof (entry_s));
  513. Link link = {.term=ins, .tset=tset};
  514. hashmap_set (lmap->links, &link);
  515. }
  516. return LSUP_OK;
  517. }
  518. LSUP_LinkMapIterator *
  519. LSUP_link_map_iter_new (const LSUP_LinkMap *lmap)
  520. {
  521. LSUP_LinkMapIterator *it;
  522. CALLOC_GUARD (it, NULL);
  523. it->map = lmap;
  524. return it;
  525. }
  526. void
  527. LSUP_link_map_iter_free (LSUP_LinkMapIterator *it) { free (it); }
  528. LSUP_rc
  529. LSUP_link_map_next (
  530. LSUP_LinkMapIterator *it, LSUP_Term **lt, LSUP_TermSet **ts)
  531. {
  532. if (!hashmap_iter (it->map->links, &it->i, (void **)&it->link))
  533. return LSUP_END;
  534. *lt = it->link->term->term;
  535. *ts = it->link->tset;
  536. return LSUP_OK;
  537. }
  538. // TODO dismantle if the only triple generator is for the graph.
  539. LSUP_rc
  540. LSUP_link_map_triples (
  541. LSUP_LinkMapIterator *it, LSUP_Triple *spo)
  542. {
  543. // Assign external (related) term.
  544. if (it->map->type == LSUP_LINK_INBOUND)
  545. spo->o = it->map->linked_t;
  546. else if (it->map->type == LSUP_LINK_OUTBOUND)
  547. spo->s = it->map->linked_t;
  548. else spo->p = it->map->linked_t;
  549. KeyedTerm *kt;
  550. // If we are already handling a link, continue the internal loop.
  551. if (it->link) goto int_loop;
  552. ext_loop:
  553. // Advance external counter and start new internal loop.
  554. it->j = 0;
  555. if (!hashmap_iter (it->map->links, &it->i, (void **)&it->link))
  556. return LSUP_END;
  557. int_loop:
  558. // If end of the term set is reached, start with a new linking term.
  559. if (!hashmap_iter (it->link->tset, &it->j, (void **)&kt)) goto ext_loop;
  560. // Continue pulling from term set.
  561. // Assign linking term.
  562. if (it->map->type == LSUP_LINK_EDGE) spo->s = it->link->term->term;
  563. else spo->p = it->link->term->term;
  564. // Assign term in term set.
  565. if (it->map->type == LSUP_LINK_INBOUND) spo->s = kt->term;
  566. else spo->o = kt->term;
  567. return LSUP_OK;
  568. }
  569. /*
  570. * Static functions.
  571. */
  572. static LSUP_rc
  573. term_init (
  574. LSUP_Term *term, LSUP_TermType type,
  575. const char *data, void *metadata)
  576. {
  577. // Exit early if environment is not initialized.
  578. // EXCEPT for IRIRef which is used inside of LSUP_init().
  579. if (!LSUP_IS_INIT && type != LSUP_TERM_IRIREF)
  580. return LSUP_ENV_ERR;
  581. // Undefined type. Make quick work of it.
  582. if (type == LSUP_TERM_UNDEFINED) {
  583. term->type = type;
  584. if (data) {
  585. term->data = malloc (strlen (data) + 1);
  586. if (UNLIKELY (!term->data)) return LSUP_MEM_ERR;
  587. strcpy (term->data, data);
  588. }
  589. return LSUP_OK;
  590. }
  591. if (type < MIN_VALID_TYPE || type > MAX_VALID_TYPE) {
  592. log_error ("%d is not a valid term type.", type);
  593. return LSUP_VALUE_ERR;
  594. }
  595. term->type = type;
  596. if (data) {
  597. // Validate IRI.
  598. if (LSUP_IS_IRI (term)) {
  599. char *fquri;
  600. // Find fully qualified IRI to parse.
  601. if (term->type == LSUP_TERM_NS_IRIREF) {
  602. if (LSUP_nsmap_normalize_uri (metadata, data, &fquri) < 0) {
  603. log_error ("Error normalizing IRI data.");
  604. return LSUP_VALUE_ERR;
  605. }
  606. LOG_DEBUG("Fully qualified IRI: %s", fquri);
  607. } else fquri = (char *) data;
  608. if (strpbrk (fquri, invalid_uri_chars) != NULL) {
  609. log_warn (
  610. "Characters %s are not valid in a URI. Got: %s\n",
  611. invalid_uri_chars, fquri);
  612. #if 0
  613. // TODO This causes W3C TTL test #29 to fail. Remove?
  614. return LSUP_VALUE_ERR;
  615. #endif
  616. }
  617. // Capture interesting IRI parts.
  618. MatchCoord matches[7] = {}; // Initialize all to 0.
  619. if (UNLIKELY (parse_iri (fquri, matches) != LSUP_OK)) {
  620. log_error ("Error matching URI pattern.");
  621. return LSUP_VALUE_ERR;
  622. }
  623. if (term->type == LSUP_TERM_NS_IRIREF) free (fquri);
  624. MALLOC_GUARD (term->iri_info, LSUP_MEM_ERR);
  625. term->iri_info->prefix = matches[1];
  626. term->iri_info->path = matches[4];
  627. term->iri_info->frag = matches[6];
  628. term->iri_info->nsm = metadata;
  629. }
  630. term->data = strdup (data);
  631. } else {
  632. // No data. Make up a random UUID or URI if allowed.
  633. if (type == LSUP_TERM_IRIREF || type == LSUP_TERM_BNODE) {
  634. uuid_t uuid;
  635. uuid_generate_random (uuid);
  636. uuid_str_t uuid_str;
  637. uuid_unparse_lower (uuid, uuid_str);
  638. if (type == LSUP_TERM_IRIREF) {
  639. term->data = malloc (UUID4_URN_SIZE);
  640. snprintf (
  641. term->data, UUID4_URN_SIZE, "urn:uuid4:%s", uuid_str);
  642. MALLOC_GUARD (term->iri_info, LSUP_MEM_ERR);
  643. // Allocate IRI match patterns manually.
  644. term->iri_info->prefix.offset = 0;
  645. term->iri_info->prefix.size = 4;
  646. term->iri_info->path.offset = 4;
  647. term->iri_info->path.size = UUIDSTR_SIZE + 6;
  648. term->iri_info->frag.offset = 0;
  649. term->iri_info->frag.size = 0;
  650. term->iri_info->nsm = NULL;
  651. } else term->data = strdup (uuid_str);
  652. } else {
  653. log_error ("No data provided for term.");
  654. return LSUP_VALUE_ERR;
  655. }
  656. }
  657. if (term->type == LSUP_TERM_LT_LITERAL) {
  658. if (!metadata) {
  659. log_warn ("Lang tag is NULL. Creating a non-tagged literal.");
  660. term->type = LSUP_TERM_LITERAL;
  661. } else {
  662. // FIXME metadata should be const all across.
  663. char *lang_str = (char *) metadata;
  664. LOG_TRACE("Lang string: '%s'", lang_str);
  665. // Lang tags longer than 7 characters will be truncated.
  666. strncpy(term->lang, lang_str, sizeof (term->lang) - 1);
  667. if (strlen (term->lang) < 1) {
  668. log_error ("Lang tag cannot be an empty string.");
  669. return LSUP_VALUE_ERR;
  670. }
  671. term->lang[7] = '\0';
  672. }
  673. }
  674. if (term->type == LSUP_TERM_LITERAL) {
  675. term->datatype = metadata;
  676. if (! term->datatype) term->datatype = LSUP_default_datatype;
  677. LOG_TRACE("Storing data type: %s", term->datatype->data);
  678. if (! LSUP_IS_IRI (term->datatype)) {
  679. log_error (
  680. "Literal data type is not an IRI: %s",
  681. term->datatype->data);
  682. return LSUP_VALUE_ERR;
  683. }
  684. LSUP_Term *ex = NULL;
  685. LSUP_term_set_add (LSUP_term_cache, term->datatype, &ex);
  686. if (ex && ex != term->datatype) {
  687. // Replace datatype handle with the one in term cache, and free
  688. // the new one.
  689. if (term->datatype != LSUP_default_datatype)
  690. LSUP_term_free (term->datatype);
  691. term->datatype = ex;
  692. }
  693. //LOG_TRACE("Datatype address: %p", term->datatype);
  694. LOG_TRACE("Datatype hash: %lx", LSUP_term_hash (term->datatype));
  695. } else if (term->type == LSUP_TERM_BNODE) {
  696. // TODO This is not usable for global skolemization.
  697. term->bnode_id = LSUP_HASH (
  698. term->data, strlen (term->data) + 1, LSUP_HASH_SEED);
  699. }
  700. return LSUP_OK;
  701. }
  702. /**
  703. * @brief scan an IRI string and parse IRI parts.
  704. *
  705. * Experimental replacement of a regex engine for better performance.
  706. *
  707. * Slightly adapted from regex on
  708. * https://datatracker.ietf.org/doc/html/rfc3986#appendix-B to capture relevant
  709. * parts of the IRI.
  710. *
  711. * Reference regex and group numbering:
  712. * ^((?([^:/?#]+):)?(?//([^/?#]*))?)((?[^?#]*)(?\?([^#]*))?(?#(.*))?)
  713. * 1 2 3 4 5 6
  714. *
  715. * Capturing groups:
  716. *
  717. * #0: Full parsed URI (http://example.org/123/456/?query=blah#frag)
  718. * #1: Prefix (http://example.org)
  719. * #2: Scheme (http)
  720. * #3: Authority (example.org)
  721. * #4: Path, including query and fragment (/123/456/?query=blah#frag)
  722. * #5: Query (query=blah)
  723. * #6: Fragment (frag)
  724. *
  725. *
  726. * @param iri_str[in] IRI string to parse.
  727. *
  728. * @param match_coord_t[out] coord Coordinates to be stored. This must be a
  729. * pre-allocated array of at least 7 elements.
  730. *
  731. * The first size_t of each element stores the relative position of a match,
  732. * and the second one stores the length of the match. A length of 0 indicates
  733. * no match.
  734. */
  735. static LSUP_rc
  736. parse_iri (char *iri_str, MatchCoord coord[]) {
  737. char *cur = iri_str;
  738. size_t iri_len = strlen (iri_str);
  739. MatchCoord tmp = {}; // Temporary storage for capture groups
  740. // Redundant if only called by term_init.
  741. // memset (coord, 0, sizeof(*coord));
  742. //LOG_DEBUG("Parsing IRI: %s", iri_str);
  743. // #2: ([^:/?#]+)
  744. while (
  745. *cur != ':' && *cur != '/' && *cur != '?'
  746. && *cur != '#' && *cur != '\0') {
  747. tmp.size++;
  748. cur++;
  749. }
  750. // Non-capturing: (?([^:/?#]+):)?
  751. if (tmp.size > 0 && *cur == ':') {
  752. // Got capture groups #2 and #3. Store them.
  753. coord[2].offset = 0;
  754. coord[2].size = tmp.size;
  755. cur++;
  756. //LOG_DEBUG("Group #2: %lu, %lu", coord[2].offset, coord[2].size);
  757. } else cur = iri_str; // Backtrack if no match.
  758. // Non-capturing: (?//([^/?#]*))?
  759. if (*cur == '/' && *(cur + 1) == '/') {
  760. cur += 2;
  761. tmp.offset = cur - iri_str;
  762. tmp.size = 0;
  763. // #3: ([^/?#]*)
  764. while (*cur != '/' && *cur != '?' && *cur != '#' && *cur != '\0') {
  765. tmp.size++;
  766. cur++;
  767. }
  768. coord[3].offset = tmp.offset;
  769. coord[3].size = tmp.size;
  770. //LOG_DEBUG("Group #3: %lu, %lu", coord[3].offset, coord[3].size);
  771. }
  772. // Capture group 1.
  773. coord[1].offset = 0;
  774. coord[1].size = cur - iri_str;
  775. //LOG_DEBUG("Group #1: %lu, %lu", coord[1].offset, coord[1].size);
  776. tmp.offset = cur - iri_str;
  777. tmp.size = 0;
  778. coord[4].offset = tmp.offset;
  779. coord[4].size = iri_len - tmp.offset;
  780. //LOG_DEBUG("Group #4: %lu, %lu", coord[4].offset, coord[4].size);
  781. // Non-capturing: (?[^?#]*)
  782. while (*cur != '?' && *cur != '#' && *cur != '\0') {
  783. tmp.size++;
  784. cur++;
  785. }
  786. // Non-capturing: (?\?([^#]*))
  787. if (*cur == '?') {
  788. // 5: ([^#]*)
  789. tmp.offset = ++cur - iri_str;
  790. tmp.size = 0;
  791. while (*cur != '#' && *cur != '\0') {
  792. tmp.size++;
  793. cur++;
  794. }
  795. if (tmp.size > 0) {
  796. // Got capture group #5.
  797. coord[5].offset = tmp.offset;
  798. coord[5].size = tmp.size;
  799. //LOG_DEBUG("Group #5: %lu, %lu", coord[5].offset, coord[5].size);
  800. }
  801. }
  802. // Non-capturing: (?#(.*))?
  803. if (*cur == '#') {
  804. // #6: (.*)
  805. coord[6].offset = ++cur - iri_str;
  806. coord[6].size = iri_str + iri_len - cur;
  807. //LOG_DEBUG("Group #6: %lu, %lu", coord[6].offset, coord[6].size);
  808. }
  809. coord[0].offset = 0;
  810. coord[0].size = iri_len;
  811. //LOG_DEBUG("Full match: %lu, %lu", coord[0].offset, coord[0].size);
  812. return LSUP_OK;
  813. }
  814. /*
  815. * Extern inline functions.
  816. */
  817. LSUP_Key LSUP_term_hash (const LSUP_Term *term);
  818. LSUP_Term *LSUP_iriref_new (const char *data, LSUP_NSMap *nsm);
  819. LSUP_Term *LSUP_literal_new (const char *data, LSUP_Term *datatype);
  820. LSUP_Term *LSUP_lt_literal_new (const char *data, char *lang);
  821. LSUP_Term *LSUP_bnode_new (const char *data);
  822. bool LSUP_term_equals (const LSUP_Term *term1, const LSUP_Term *term2);
  823. LSUP_Term *LSUP_triple_pos (const LSUP_Triple *trp, LSUP_TriplePos n);
  824. LSUP_Key LSUP_triple_hash (const LSUP_Triple *trp);