term.c 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  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. const 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. // This leaves the link and link map references intact.
  527. void
  528. LSUP_link_map_iter_free (LSUP_LinkMapIterator *it) { free (it); }
  529. LSUP_rc
  530. LSUP_link_map_next (
  531. LSUP_LinkMapIterator *it, LSUP_Term **lt, LSUP_TermSet **ts)
  532. {
  533. if (!hashmap_iter (it->map->links, &it->i, (void **)&it->link))
  534. return LSUP_END;
  535. *lt = it->link->term->term;
  536. *ts = it->link->tset;
  537. return LSUP_OK;
  538. }
  539. // TODO dismantle if the only triple generator is for the graph.
  540. LSUP_rc
  541. LSUP_link_map_triples (
  542. LSUP_LinkMapIterator *it, LSUP_Triple *spo)
  543. {
  544. // Assign external (related) term.
  545. if (it->map->type == LSUP_LINK_INBOUND)
  546. spo->o = it->map->linked_t;
  547. else if (it->map->type == LSUP_LINK_OUTBOUND)
  548. spo->s = it->map->linked_t;
  549. else spo->p = it->map->linked_t;
  550. KeyedTerm *kt;
  551. // If we are already handling a link, continue the internal loop.
  552. if (it->link) goto int_loop;
  553. ext_loop:
  554. // Advance external counter and start new internal loop.
  555. it->j = 0;
  556. if (!hashmap_iter (it->map->links, &it->i, (void **)&it->link))
  557. return LSUP_END;
  558. int_loop:
  559. // If end of the term set is reached, start with a new linking term.
  560. if (!hashmap_iter (it->link->tset, &it->j, (void **)&kt)) goto ext_loop;
  561. // Continue pulling from term set.
  562. // Assign linking term.
  563. if (it->map->type == LSUP_LINK_EDGE) spo->s = it->link->term->term;
  564. else spo->p = it->link->term->term;
  565. // Assign term in term set.
  566. if (it->map->type == LSUP_LINK_INBOUND) spo->s = kt->term;
  567. else spo->o = kt->term;
  568. return LSUP_OK;
  569. }
  570. /*
  571. * Static functions.
  572. */
  573. static LSUP_rc
  574. term_init (
  575. LSUP_Term *term, LSUP_TermType type,
  576. const char *data, void *metadata)
  577. {
  578. // Exit early if environment is not initialized.
  579. // EXCEPT for IRIRef which is used inside of LSUP_init().
  580. if (!LSUP_IS_INIT && type != LSUP_TERM_IRIREF)
  581. return LSUP_ENV_ERR;
  582. // Undefined type. Make quick work of it.
  583. if (type == LSUP_TERM_UNDEFINED) {
  584. term->type = type;
  585. if (data) {
  586. term->data = malloc (strlen (data) + 1);
  587. if (UNLIKELY (!term->data)) return LSUP_MEM_ERR;
  588. strcpy (term->data, data);
  589. }
  590. return LSUP_OK;
  591. }
  592. if (type < MIN_VALID_TYPE || type > MAX_VALID_TYPE) {
  593. log_error ("%d is not a valid term type.", type);
  594. return LSUP_VALUE_ERR;
  595. }
  596. term->type = type;
  597. if (data) {
  598. // Validate IRI.
  599. if (LSUP_IS_IRI (term)) {
  600. char *fquri;
  601. // Find fully qualified IRI to parse.
  602. if (term->type == LSUP_TERM_NS_IRIREF) {
  603. if (LSUP_nsmap_normalize_uri (metadata, data, &fquri) < 0) {
  604. log_error ("Error normalizing IRI data.");
  605. return LSUP_VALUE_ERR;
  606. }
  607. LOG_DEBUG("Fully qualified IRI: %s", fquri);
  608. } else fquri = (char *) data;
  609. if (strpbrk (fquri, invalid_uri_chars) != NULL) {
  610. log_warn (
  611. "Characters %s are not valid in a URI. Got: %s\n",
  612. invalid_uri_chars, fquri);
  613. #if 0
  614. // TODO This causes W3C TTL test #29 to fail. Remove?
  615. return LSUP_VALUE_ERR;
  616. #endif
  617. }
  618. // Capture interesting IRI parts.
  619. MatchCoord matches[7] = {}; // Initialize all to 0.
  620. if (UNLIKELY (parse_iri (fquri, matches) != LSUP_OK)) {
  621. log_error ("Error matching URI pattern.");
  622. return LSUP_VALUE_ERR;
  623. }
  624. if (term->type == LSUP_TERM_NS_IRIREF) free (fquri);
  625. MALLOC_GUARD (term->iri_info, LSUP_MEM_ERR);
  626. term->iri_info->prefix = matches[1];
  627. term->iri_info->path = matches[4];
  628. term->iri_info->frag = matches[6];
  629. term->iri_info->nsm = metadata;
  630. }
  631. term->data = strdup (data);
  632. } else {
  633. // No data. Make up a random UUID or URI if allowed.
  634. if (type == LSUP_TERM_IRIREF || type == LSUP_TERM_BNODE) {
  635. uuid_t uuid;
  636. uuid_generate_random (uuid);
  637. uuid_str_t uuid_str;
  638. uuid_unparse_lower (uuid, uuid_str);
  639. if (type == LSUP_TERM_IRIREF) {
  640. term->data = malloc (UUID4_URN_SIZE);
  641. snprintf (
  642. term->data, UUID4_URN_SIZE, "urn:uuid4:%s", uuid_str);
  643. MALLOC_GUARD (term->iri_info, LSUP_MEM_ERR);
  644. // Allocate IRI match patterns manually.
  645. term->iri_info->prefix.offset = 0;
  646. term->iri_info->prefix.size = 4;
  647. term->iri_info->path.offset = 4;
  648. term->iri_info->path.size = UUIDSTR_SIZE + 6;
  649. term->iri_info->frag.offset = 0;
  650. term->iri_info->frag.size = 0;
  651. term->iri_info->nsm = NULL;
  652. } else term->data = strdup (uuid_str);
  653. } else {
  654. log_error ("No data provided for term.");
  655. return LSUP_VALUE_ERR;
  656. }
  657. }
  658. if (term->type == LSUP_TERM_LT_LITERAL) {
  659. if (!metadata) {
  660. log_warn ("Lang tag is NULL. Creating a non-tagged literal.");
  661. term->type = LSUP_TERM_LITERAL;
  662. } else {
  663. // FIXME metadata should be const all across.
  664. char *lang_str = (char *) metadata;
  665. LOG_TRACE("Lang string: '%s'", lang_str);
  666. // Lang tags longer than 7 characters will be truncated.
  667. strncpy(term->lang, lang_str, sizeof (term->lang) - 1);
  668. if (strlen (term->lang) < 1) {
  669. log_error ("Lang tag cannot be an empty string.");
  670. return LSUP_VALUE_ERR;
  671. }
  672. term->lang[7] = '\0';
  673. }
  674. }
  675. if (term->type == LSUP_TERM_LITERAL) {
  676. term->datatype = metadata;
  677. if (! term->datatype) term->datatype = LSUP_default_datatype;
  678. LOG_TRACE("Storing data type: %s", term->datatype->data);
  679. if (! LSUP_IS_IRI (term->datatype)) {
  680. log_error (
  681. "Literal data type is not an IRI: %s",
  682. term->datatype->data);
  683. return LSUP_VALUE_ERR;
  684. }
  685. LSUP_Term *ex = NULL;
  686. LSUP_term_set_add (LSUP_term_cache, term->datatype, &ex);
  687. if (ex && ex != term->datatype) {
  688. // Replace datatype handle with the one in term cache, and free
  689. // the new one.
  690. if (term->datatype != LSUP_default_datatype)
  691. LSUP_term_free (term->datatype);
  692. term->datatype = ex;
  693. }
  694. //LOG_TRACE("Datatype address: %p", term->datatype);
  695. LOG_TRACE("Datatype hash: %lx", LSUP_term_hash (term->datatype));
  696. } else if (term->type == LSUP_TERM_BNODE) {
  697. // TODO This is not usable for global skolemization.
  698. term->bnode_id = LSUP_HASH (
  699. term->data, strlen (term->data) + 1, LSUP_HASH_SEED);
  700. }
  701. return LSUP_OK;
  702. }
  703. /**
  704. * @brief scan an IRI string and parse IRI parts.
  705. *
  706. * Experimental replacement of a regex engine for better performance.
  707. *
  708. * Slightly adapted from regex on
  709. * https://datatracker.ietf.org/doc/html/rfc3986#appendix-B to capture relevant
  710. * parts of the IRI.
  711. *
  712. * Reference regex and group numbering:
  713. * ^((?([^:/?#]+):)?(?//([^/?#]*))?)((?[^?#]*)(?\?([^#]*))?(?#(.*))?)
  714. * 1 2 3 4 5 6
  715. *
  716. * Capturing groups:
  717. *
  718. * #0: Full parsed URI (http://example.org/123/456/?query=blah#frag)
  719. * #1: Prefix (http://example.org)
  720. * #2: Scheme (http)
  721. * #3: Authority (example.org)
  722. * #4: Path, including query and fragment (/123/456/?query=blah#frag)
  723. * #5: Query (query=blah)
  724. * #6: Fragment (frag)
  725. *
  726. *
  727. * @param iri_str[in] IRI string to parse.
  728. *
  729. * @param match_coord_t[out] coord Coordinates to be stored. This must be a
  730. * pre-allocated array of at least 7 elements.
  731. *
  732. * The first size_t of each element stores the relative position of a match,
  733. * and the second one stores the length of the match. A length of 0 indicates
  734. * no match.
  735. */
  736. static LSUP_rc
  737. parse_iri (char *iri_str, MatchCoord coord[]) {
  738. char *cur = iri_str;
  739. size_t iri_len = strlen (iri_str);
  740. MatchCoord tmp = {}; // Temporary storage for capture groups
  741. // Redundant if only called by term_init.
  742. // memset (coord, 0, sizeof(*coord));
  743. //LOG_DEBUG("Parsing IRI: %s", iri_str);
  744. // #2: ([^:/?#]+)
  745. while (
  746. *cur != ':' && *cur != '/' && *cur != '?'
  747. && *cur != '#' && *cur != '\0') {
  748. tmp.size++;
  749. cur++;
  750. }
  751. // Non-capturing: (?([^:/?#]+):)?
  752. if (tmp.size > 0 && *cur == ':') {
  753. // Got capture groups #2 and #3. Store them.
  754. coord[2].offset = 0;
  755. coord[2].size = tmp.size;
  756. cur++;
  757. //LOG_DEBUG("Group #2: %lu, %lu", coord[2].offset, coord[2].size);
  758. } else cur = iri_str; // Backtrack if no match.
  759. // Non-capturing: (?//([^/?#]*))?
  760. if (*cur == '/' && *(cur + 1) == '/') {
  761. cur += 2;
  762. tmp.offset = cur - iri_str;
  763. tmp.size = 0;
  764. // #3: ([^/?#]*)
  765. while (*cur != '/' && *cur != '?' && *cur != '#' && *cur != '\0') {
  766. tmp.size++;
  767. cur++;
  768. }
  769. coord[3].offset = tmp.offset;
  770. coord[3].size = tmp.size;
  771. //LOG_DEBUG("Group #3: %lu, %lu", coord[3].offset, coord[3].size);
  772. }
  773. // Capture group 1.
  774. coord[1].offset = 0;
  775. coord[1].size = cur - iri_str;
  776. //LOG_DEBUG("Group #1: %lu, %lu", coord[1].offset, coord[1].size);
  777. tmp.offset = cur - iri_str;
  778. tmp.size = 0;
  779. coord[4].offset = tmp.offset;
  780. coord[4].size = iri_len - tmp.offset;
  781. //LOG_DEBUG("Group #4: %lu, %lu", coord[4].offset, coord[4].size);
  782. // Non-capturing: (?[^?#]*)
  783. while (*cur != '?' && *cur != '#' && *cur != '\0') {
  784. tmp.size++;
  785. cur++;
  786. }
  787. // Non-capturing: (?\?([^#]*))
  788. if (*cur == '?') {
  789. // 5: ([^#]*)
  790. tmp.offset = ++cur - iri_str;
  791. tmp.size = 0;
  792. while (*cur != '#' && *cur != '\0') {
  793. tmp.size++;
  794. cur++;
  795. }
  796. if (tmp.size > 0) {
  797. // Got capture group #5.
  798. coord[5].offset = tmp.offset;
  799. coord[5].size = tmp.size;
  800. //LOG_DEBUG("Group #5: %lu, %lu", coord[5].offset, coord[5].size);
  801. }
  802. }
  803. // Non-capturing: (?#(.*))?
  804. if (*cur == '#') {
  805. // #6: (.*)
  806. coord[6].offset = ++cur - iri_str;
  807. coord[6].size = iri_str + iri_len - cur;
  808. //LOG_DEBUG("Group #6: %lu, %lu", coord[6].offset, coord[6].size);
  809. }
  810. coord[0].offset = 0;
  811. coord[0].size = iri_len;
  812. //LOG_DEBUG("Full match: %lu, %lu", coord[0].offset, coord[0].size);
  813. return LSUP_OK;
  814. }
  815. /*
  816. * Extern inline functions.
  817. */
  818. LSUP_Key LSUP_term_hash (const LSUP_Term *term);
  819. LSUP_Term *LSUP_iriref_new (const char *data, LSUP_NSMap *nsm);
  820. LSUP_Term *LSUP_literal_new (const char *data, LSUP_Term *datatype);
  821. LSUP_Term *LSUP_lt_literal_new (const char *data, char *lang);
  822. LSUP_Term *LSUP_bnode_new (const char *data);
  823. bool LSUP_term_equals (const LSUP_Term *term1, const LSUP_Term *term2);
  824. LSUP_Term *LSUP_triple_pos (const LSUP_Triple *trp, LSUP_TriplePos n);
  825. LSUP_Key LSUP_triple_hash (const LSUP_Triple *trp);