term.c 26 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033
  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 may 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. LSUP_Term * ext; ///< External link to look for connections.
  45. Link * link; ///< Current link being retrieved.
  46. };
  47. /*
  48. * A link map is thus nested:
  49. *
  50. * - A link map contains a hash map of Link instances (link).
  51. * - Each Link contains a KeyedTerm (term) and a TermSet (tset).
  52. * - Each term set is a hash map of KeyedTerm instances.
  53. * - Each KeyedTerm contains a Term and its hash.
  54. */
  55. typedef struct link_map {
  56. LSUP_LinkType type; ///< Link type.
  57. struct hashmap * links; ///< Map of #Link instances.
  58. } LSUP_LinkMap;
  59. /*
  60. * External variables.
  61. */
  62. uint32_t LSUP_default_dtype_key = 0;
  63. LSUP_Term *LSUP_default_datatype = NULL;
  64. LSUP_TermSet *LSUP_term_cache = NULL;
  65. /*
  66. * Static variables.
  67. */
  68. // Characters not allowed in a URI string.
  69. static const char *invalid_uri_chars = "<>\" {}|\\^`";
  70. /// Minimum valid type code.
  71. static const LSUP_TermType MIN_VALID_TYPE = LSUP_TERM_IRIREF;
  72. /// Maximum valid type code. Change this if adding to enum LSUP_TermType.
  73. static const LSUP_TermType MAX_VALID_TYPE = LSUP_TERM_BNODE;
  74. /*
  75. * Static prototypes.
  76. */
  77. static LSUP_rc
  78. term_init (
  79. LSUP_Term *term, LSUP_TermType type, const char *data, void *metadata);
  80. /*
  81. * Term set callbacks.
  82. */
  83. static uint64_t
  84. tset_hash_fn (
  85. const void *item, uint64_t seed0, uint64_t seed1)
  86. { return ((const KeyedTerm *) item)->key; }
  87. static int
  88. tset_cmp_fn (const void *a, const void *b, void *udata)
  89. {
  90. return
  91. ((const KeyedTerm *) a)->key -
  92. ((const KeyedTerm *) b)->key;
  93. }
  94. static void
  95. tset_free_fn (void *item)
  96. { LSUP_term_free (((KeyedTerm *) item)->term); }
  97. /*
  98. * Link map callbacks.
  99. */
  100. static uint64_t
  101. link_map_hash_fn (
  102. const void *item, uint64_t seed0, uint64_t seed1)
  103. { return ((const Link *)item)->term->key; }
  104. static int
  105. link_map_cmp_fn (const void *a, const void *b, void *udata)
  106. {
  107. return
  108. ((const Link *)a)->term->key -
  109. ((const Link *)b)->term->key;
  110. }
  111. static void
  112. link_map_free_fn (void *item)
  113. {
  114. Link *link = item;
  115. LSUP_term_free (link->term->term);
  116. free (link->term);
  117. LSUP_term_set_free (link->tset);
  118. }
  119. static LSUP_rc parse_iri (char *iri, MatchCoord coords[]);
  120. /*
  121. * Term API.
  122. */
  123. LSUP_Term *
  124. LSUP_term_new (
  125. LSUP_TermType type, const char *data, void *metadata)
  126. {
  127. LSUP_Term *term;
  128. CALLOC_GUARD (term, NULL);
  129. // If undefined, just set the type.
  130. if (type == LSUP_TERM_UNDEFINED) term->type = type;
  131. else 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. MALLOC_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 (LSUP_LinkType type)
  453. {
  454. LSUP_LinkMap *cm;
  455. MALLOC_GUARD (cm, NULL);
  456. cm->type = type;
  457. cm->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. return cm;
  461. }
  462. void
  463. LSUP_link_map_free (LSUP_LinkMap *cm)
  464. {
  465. hashmap_free (cm->links);
  466. free (cm);
  467. }
  468. LSUP_LinkType
  469. LSUP_link_map_type (const LSUP_LinkMap *map)
  470. { return map->type; }
  471. // TODO Memory error handling.
  472. LSUP_rc
  473. LSUP_link_map_add (
  474. LSUP_LinkMap *cmap, LSUP_Term *term, LSUP_TermSet *tset)
  475. {
  476. // Keyed term to look up the link term and insert it, if necessary.
  477. KeyedTerm entry_s = {.key=LSUP_term_hash (term), .term=term};
  478. Link *ex = hashmap_get (cmap->links, &(Link){.term=&entry_s});
  479. if (ex) {
  480. // Add terms one by one to the existing term set.
  481. log_trace (
  482. "Linking term %s exists. Adding individual terms.",
  483. ex->term->term->data);
  484. size_t i = 0;
  485. KeyedTerm *kt;
  486. while (hashmap_iter (tset, &i, (void **)&kt)) {
  487. log_trace (
  488. "Adding term %s to link %s",
  489. kt->term->data, ex->term->term->data);
  490. if (hashmap_get (ex->tset, kt))
  491. // Term already exist, free the new one and move on.
  492. LSUP_term_free (kt->term);
  493. else
  494. // Insert KeyedTerm, the term set now owns the underlying term.
  495. hashmap_set (ex->tset, kt);
  496. }
  497. // Free link term that hasn't been used.
  498. LSUP_term_free (term);
  499. } else {
  500. // Add the new term and the termset wholesale.
  501. log_trace ("Adding new linking term %s.", term->data);
  502. // Allocate inserted member on heap, it will be owned by the map.
  503. KeyedTerm *ins;
  504. MALLOC_GUARD (ins, LSUP_MEM_ERR);
  505. memcpy (ins, &entry_s, sizeof (entry_s));
  506. Link link = {.term=ins, .tset=tset};
  507. hashmap_set (cmap->links, &link);
  508. }
  509. return LSUP_OK;
  510. }
  511. LSUP_LinkMapIterator *
  512. LSUP_link_map_iter_new (const LSUP_LinkMap *lmap, LSUP_Term *ext)
  513. {
  514. LSUP_LinkMapIterator *it;
  515. CALLOC_GUARD (it, NULL);
  516. it->map = lmap;
  517. it->ext = ext;
  518. return it;
  519. }
  520. void
  521. LSUP_link_map_iter_free (LSUP_LinkMapIterator *it)
  522. { free (it); }
  523. LSUP_rc
  524. LSUP_link_map_next (
  525. LSUP_LinkMapIterator *it, LSUP_Term **lt, LSUP_TermSet **ts)
  526. {
  527. if (!hashmap_iter (it->map->links, &it->i, (void **)&it->link))
  528. return LSUP_END;
  529. *lt = it->link->term->term;
  530. *ts = it->link->tset;
  531. return LSUP_OK;
  532. }
  533. // TODO dismantle if the only triple generator is for the graph.
  534. LSUP_rc
  535. LSUP_link_map_triples (
  536. LSUP_LinkMapIterator *it, LSUP_Triple *spo)
  537. {
  538. // Assign external (related) term.
  539. if (it->map->type == LSUP_LINK_INBOUND)
  540. spo->o = it->ext;
  541. else if (it->map->type == LSUP_LINK_OUTBOUND)
  542. spo->s = it->ext;
  543. else spo->p = it->ext;
  544. KeyedTerm *kt;
  545. // If we are already handling a link, continue the internal loop.
  546. if (it->link) goto int_loop;
  547. ext_loop:
  548. // Advance external counter and start new internal loop.
  549. it->j = 0;
  550. if (!hashmap_iter (it->map->links, &it->i, (void **)&it->link))
  551. return LSUP_END;
  552. int_loop:
  553. // If end of the term set is reached, start with a new linking term.
  554. if (!hashmap_iter (it->link->tset, &it->j, (void **)&kt)) goto ext_loop;
  555. // Continue pulling from term set.
  556. // Assign linking term.
  557. if (it->map->type == LSUP_LINK_EDGE) spo->s = it->link->term->term;
  558. else spo->p = it->link->term->term;
  559. // Assign term in term set.
  560. if (it->map->type == LSUP_LINK_INBOUND) spo->s = kt->term;
  561. else spo->o = kt->term;
  562. return LSUP_OK;
  563. }
  564. /*
  565. * Static functions.
  566. */
  567. static LSUP_rc
  568. term_init (
  569. LSUP_Term *term, LSUP_TermType type,
  570. const char *data, void *metadata)
  571. {
  572. // This can never be LSUP_TERM_UNDEFINED.
  573. if (type < MIN_VALID_TYPE || type > MAX_VALID_TYPE) {
  574. log_error ("%d is not a valid term type.", type);
  575. return LSUP_VALUE_ERR;
  576. }
  577. term->type = type;
  578. if (data) {
  579. // Validate IRI.
  580. if (LSUP_IS_IRI (term)) {
  581. char *fquri;
  582. // Find fully qualified IRI to parse.
  583. if (term->type == LSUP_TERM_NS_IRIREF) {
  584. if (LSUP_nsmap_normalize_uri (metadata, data, &fquri) < 0) {
  585. log_error ("Error normalizing IRI data.");
  586. return LSUP_VALUE_ERR;
  587. }
  588. log_debug ("Fully qualified IRI: %s", fquri);
  589. } else fquri = (char *) data;
  590. if (strpbrk (fquri, invalid_uri_chars) != NULL) {
  591. log_warn (
  592. "Characters %s are not valid in a URI. Got: %s\n",
  593. invalid_uri_chars, fquri);
  594. #if 0
  595. // TODO This causes W3C TTL test #29 to fail. Remove?
  596. return LSUP_VALUE_ERR;
  597. #endif
  598. }
  599. // Capture interesting IRI parts.
  600. MatchCoord matches[7] = {}; // Initialize all to 0.
  601. if (UNLIKELY (parse_iri (fquri, matches) != LSUP_OK)) {
  602. log_error ("Error matching URI pattern.");
  603. return LSUP_VALUE_ERR;
  604. }
  605. if (term->type == LSUP_TERM_NS_IRIREF) free (fquri);
  606. MALLOC_GUARD (term->iri_info, LSUP_MEM_ERR);
  607. term->iri_info->prefix = matches[1];
  608. term->iri_info->path = matches[4];
  609. term->iri_info->frag = matches[6];
  610. term->iri_info->nsm = metadata;
  611. }
  612. term->data = strdup (data);
  613. } else {
  614. // No data. Make up a random UUID or URI if allowed.
  615. if (type == LSUP_TERM_IRIREF || type == LSUP_TERM_BNODE) {
  616. uuid_t uuid;
  617. uuid_generate_random (uuid);
  618. uuid_str_t uuid_str;
  619. uuid_unparse_lower (uuid, uuid_str);
  620. if (type == LSUP_TERM_IRIREF) {
  621. term->data = malloc (UUID4_URN_SIZE);
  622. snprintf (
  623. term->data, UUID4_URN_SIZE, "urn:uuid4:%s", uuid_str);
  624. MALLOC_GUARD (term->iri_info, LSUP_MEM_ERR);
  625. // Allocate IRI match patterns manually.
  626. term->iri_info->prefix.offset = 0;
  627. term->iri_info->prefix.size = 4;
  628. term->iri_info->path.offset = 4;
  629. term->iri_info->path.size = UUIDSTR_SIZE + 6;
  630. term->iri_info->frag.offset = 0;
  631. term->iri_info->frag.size = 0;
  632. term->iri_info->nsm = NULL;
  633. } else term->data = strdup (uuid_str);
  634. } else {
  635. log_error ("No data provided for term.");
  636. return LSUP_VALUE_ERR;
  637. }
  638. }
  639. if (term->type == LSUP_TERM_LT_LITERAL) {
  640. if (!metadata) {
  641. log_warn ("Lang tag is NULL. Creating a non-tagged literal.");
  642. term->type = LSUP_TERM_LITERAL;
  643. } else {
  644. char *lang_str = (char *) metadata;
  645. log_trace("Lang string: '%s'", lang_str);
  646. // Lang tags longer than 7 characters will be truncated.
  647. strncpy(term->lang, lang_str, sizeof (term->lang) - 1);
  648. if (strlen (term->lang) < 1) {
  649. log_error ("Lang tag cannot be an empty string.");
  650. return LSUP_VALUE_ERR;
  651. }
  652. term->lang[7] = '\0';
  653. }
  654. }
  655. if (term->type == LSUP_TERM_LITERAL) {
  656. term->datatype = metadata;
  657. if (! term->datatype) term->datatype = LSUP_default_datatype;
  658. log_trace ("Storing data type: %s", term->datatype->data);
  659. if (! LSUP_IS_IRI (term->datatype)) {
  660. log_error (
  661. "Literal data type is not an IRI: %s",
  662. term->datatype->data);
  663. return LSUP_VALUE_ERR;
  664. }
  665. LSUP_Term *ex = NULL;
  666. LSUP_term_set_add (LSUP_term_cache, term->datatype, &ex);
  667. if (ex && ex != term->datatype) {
  668. // Replace datatype handle with the one in term cache, and free
  669. // the new one.
  670. if (term->datatype != LSUP_default_datatype)
  671. LSUP_term_free (term->datatype);
  672. term->datatype = ex;
  673. }
  674. //log_trace ("Datatype address: %p", term->datatype);
  675. log_trace ("Datatype hash: %lx", LSUP_term_hash (term->datatype));
  676. } else if (term->type == LSUP_TERM_BNODE) {
  677. // TODO This is not usable for global skolemization.
  678. term->bnode_id = LSUP_HASH (
  679. term->data, strlen (term->data) + 1, LSUP_HASH_SEED);
  680. }
  681. return LSUP_OK;
  682. }
  683. /**
  684. * @brief scan an IRI string and parse IRI parts.
  685. *
  686. * Experimental replacement of a regex engine for better performance.
  687. *
  688. * Slightly adapted from regex on
  689. * https://datatracker.ietf.org/doc/html/rfc3986#appendix-B to capture relevant
  690. * parts of the IRI.
  691. *
  692. * Reference regex and group numbering:
  693. * ^((?([^:/?#]+):)?(?//([^/?#]*))?)((?[^?#]*)(?\?([^#]*))?(?#(.*))?)
  694. * 1 2 3 4 5 6
  695. *
  696. * Capturing groups:
  697. *
  698. * #0: Full parsed URI (http://example.org/123/456/?query=blah#frag)
  699. * #1: Prefix (http://example.org)
  700. * #2: Scheme (http)
  701. * #3: Authority (example.org)
  702. * #4: Path, including query and fragment (/123/456/?query=blah#frag)
  703. * #5: Query (query=blah)
  704. * #6: Fragment (frag)
  705. *
  706. *
  707. * @param iri_str[in] IRI string to parse.
  708. *
  709. * @param match_coord_t[out] coord Coordinates to be stored. This must be a
  710. * pre-allocated array of at least 7 elements.
  711. *
  712. * The first size_t of each element stores the relative position of a match,
  713. * and the second one stores the length of the match. A length of 0 indicates
  714. * no match.
  715. */
  716. static LSUP_rc
  717. parse_iri (char *iri_str, MatchCoord coord[]) {
  718. char *cur = iri_str;
  719. size_t iri_len = strlen (iri_str);
  720. MatchCoord tmp = {}; // Temporary storage for capture groups
  721. // Redundant if only called by term_init.
  722. // memset (coord, 0, sizeof(*coord));
  723. //log_debug ("Parsing IRI: %s", iri_str);
  724. // #2: ([^:/?#]+)
  725. while (
  726. *cur != ':' && *cur != '/' && *cur != '?'
  727. && *cur != '#' && *cur != '\0') {
  728. tmp.size++;
  729. cur++;
  730. }
  731. // Non-capturing: (?([^:/?#]+):)?
  732. if (tmp.size > 0 && *cur == ':') {
  733. // Got capture groups #2 and #3. Store them.
  734. coord[2].offset = 0;
  735. coord[2].size = tmp.size;
  736. cur++;
  737. //log_debug ("Group #2: %lu, %lu", coord[2].offset, coord[2].size);
  738. } else cur = iri_str; // Backtrack if no match.
  739. // Non-capturing: (?//([^/?#]*))?
  740. if (*cur == '/' && *(cur + 1) == '/') {
  741. cur += 2;
  742. tmp.offset = cur - iri_str;
  743. tmp.size = 0;
  744. // #3: ([^/?#]*)
  745. while (*cur != '/' && *cur != '?' && *cur != '#' && *cur != '\0') {
  746. tmp.size++;
  747. cur++;
  748. }
  749. coord[3].offset = tmp.offset;
  750. coord[3].size = tmp.size;
  751. //log_debug ("Group #3: %lu, %lu", coord[3].offset, coord[3].size);
  752. }
  753. // Capture group 1.
  754. coord[1].offset = 0;
  755. coord[1].size = cur - iri_str;
  756. //log_debug ("Group #1: %lu, %lu", coord[1].offset, coord[1].size);
  757. tmp.offset = cur - iri_str;
  758. tmp.size = 0;
  759. coord[4].offset = tmp.offset;
  760. coord[4].size = iri_len - tmp.offset;
  761. //log_debug ("Group #4: %lu, %lu", coord[4].offset, coord[4].size);
  762. // Non-capturing: (?[^?#]*)
  763. while (*cur != '?' && *cur != '#' && *cur != '\0') {
  764. tmp.size++;
  765. cur++;
  766. }
  767. // Non-capturing: (?\?([^#]*))
  768. if (*cur == '?') {
  769. // 5: ([^#]*)
  770. tmp.offset = ++cur - iri_str;
  771. tmp.size = 0;
  772. while (*cur != '#' && *cur != '\0') {
  773. tmp.size++;
  774. cur++;
  775. }
  776. if (tmp.size > 0) {
  777. // Got capture group #5.
  778. coord[5].offset = tmp.offset;
  779. coord[5].size = tmp.size;
  780. //log_debug ("Group #5: %lu, %lu", coord[5].offset, coord[5].size);
  781. }
  782. }
  783. // Non-capturing: (?#(.*))?
  784. if (*cur == '#') {
  785. // #6: (.*)
  786. coord[6].offset = ++cur - iri_str;
  787. coord[6].size = iri_str + iri_len - cur;
  788. //log_debug ("Group #6: %lu, %lu", coord[6].offset, coord[6].size);
  789. }
  790. coord[0].offset = 0;
  791. coord[0].size = iri_len;
  792. //log_debug ("Full match: %lu, %lu", coord[0].offset, coord[0].size);
  793. return LSUP_OK;
  794. }
  795. /*
  796. * Extern inline functions.
  797. */
  798. LSUP_Key LSUP_term_hash (const LSUP_Term *term);
  799. LSUP_Term *LSUP_iriref_new (const char *data, LSUP_NSMap *nsm);
  800. LSUP_Term *LSUP_literal_new (const char *data, LSUP_Term *datatype);
  801. LSUP_Term *LSUP_lt_literal_new (const char *data, char *lang);
  802. LSUP_Term *LSUP_bnode_new (const char *data);
  803. bool LSUP_term_equals (const LSUP_Term *term1, const LSUP_Term *term2);
  804. LSUP_Term *LSUP_triple_pos (const LSUP_Triple *trp, LSUP_TriplePos n);
  805. LSUP_Key LSUP_triple_hash (const LSUP_Triple *trp);