-
Notifications
You must be signed in to change notification settings - Fork 9
/
marpa_tau.cpp
1058 lines (858 loc) · 32.5 KB
/
marpa_tau.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
http://www.w3.org/2000/10/swap/grammar/bnf
http://www.w3.org/2000/10/swap/grammar/n3.n3
doesnt do proofs.
*/
#include <iostream>
#include <fstream>
#include "prover.h"
#include "json_object.h"
#include "cli.h"
#include "rdf.h"
#include "misc.h"
#include "jsonld.h"
#include "marpa_tau.h"
extern "C" {
#include "marpa.h"
#include "marpa_codes.c"
}
#include <boost/regex.hpp>
#include <boost/algorithm/string/predicate.hpp>
typedef Marpa_Symbol_ID sym;
typedef Marpa_Rule_ID rule;
typedef std::vector <sym> syms;
typedef std::pair <string::const_iterator, string::const_iterator> tokt;
class terminal {
public:
resid thing;
string name, regex_string;
boost::wregex regex;
terminal(resid thing_, string name_, string regex_) {
name = name_;
thing = thing_;
regex_string = regex_;
regex = boost::wregex(regex_);
}
};
typedef std::shared_ptr <terminal> pterminal;
struct MarpaIris{
pnode iri(const std::string s)
{
return mkiri(pstr(prefix + ws(s)));
}
string prefix = L"http://idni.org/marpa#";
const pnode has_value = iri("has_value");
const pnode is_parse_of = iri("is_parse_of");
const pnode list_of = iri("list_of");
const pnode separator = iri("separator");
const pnode arg0 = iri("arg0");
const pnode arg1 = iri("arg1");
const pnode arg2 = iri("arg2");
};
MarpaIris *marpa = 0;
struct Marpa {
Marpa_Grammar g;
bool precomputed = false;
// everything in the grammar is either a terminal, defined by a regex, a "literal" - a simple string, or a rule
map <sym, pterminal> terminals;
map <sym, string> literals;
map <resid, sym> done;//tracks rules and terminals..i might rework this
map <rule, sym> rules;
prover *prvr, *prvr2;/*prvr is the one we are called from. we will use prvr2 for querying the grammar, so that prvr doesnt get messed up*/
string whitespace = L""; // i use this for comment regex, comments are processed kinda specially so they dont have to pollute the grammar
const resid pcomma = dict[mkliteral(pstr(L","), 0, 0)];
const pnode rdfs_nil = mkiri(pstr(L"http://www.w3.org/1999/02/22-rdf-syntax-ns#nil"));
const pnode rdfs_rest = mkiri(pstr(L"http://www.w3.org/1999/02/22-rdf-syntax-ns#rest"));
const pnode rdfs_first = mkiri(pstr(L"http://www.w3.org/1999/02/22-rdf-syntax-ns#first"));
const pnode bnf_matches = mkiri(pstr(L"http://www.w3.org/2000/10/swap/grammar/bnf#matches"));
const pnode bnf_document = mkiri(pstr(L"http://www.w3.org/2000/10/swap/grammar/bnf#document"));
const pnode bnf_whitespace = mkiri(pstr(L"http://www.w3.org/2000/10/swap/grammar/bnf#whiteSpace"));
const pnode bnf_zeroormore = mkiri(pstr(L"http://www.w3.org/2000/10/swap/grammar/bnf#zeroOrMore"));
const pnode bnf_mustBeOneSequence = mkiri(pstr(L"http://www.w3.org/2000/10/swap/grammar/bnf#mustBeOneSequence"));
const pnode bnf_commaSeparatedListOf = mkiri(pstr(L"http://www.w3.org/2000/10/swap/grammar/bnf#commaSeparatedListOf"));
resid sym2resid(sym s) {
for (auto it = done.begin(); it != done.end(); it++)
if (it->second == s)
return it->first;
throw std::runtime_error("this sym isnt for a rule..this shouldnt happen");
}
resid rule2resid(rule r) {
for (auto rr : rules)
if (rr.first == r) {
for (auto rrr: done)
if (rr.second == rrr.second)
return rrr.first;
}
throw std::runtime_error("and this shouldnt happen either");
}
string sym2str_(sym s) {
if (literals.find(s) != literals.end())
return L": \"" + literals[s] + L"\"";
if (terminals.find(s) != terminals.end())
return terminals[s]->name + L" - " + terminals[s]->regex_string;
return *dict[sym2resid(s)].value;
}
string sym2str(sym s) {
std::wstringstream sss;
sss << L"(" << s << L")" << sym2str_(s);
return sss.str();
}
string value(resid val) {
return *dict[val].value;
}
~Marpa() {
marpa_g_unref(g);
}
Marpa(prover *prvr_, resid language) {
/*init marpa*/
if (marpa_check_version(MARPA_MAJOR_VERSION, MARPA_MINOR_VERSION, MARPA_MICRO_VERSION) != MARPA_ERR_NONE)
throw std::runtime_error("marpa version...");
Marpa_Config marpa_config;
marpa_c_init(&marpa_config);
g = marpa_g_new(&marpa_config);
if (!g) {
stringstream ssss("marpa_g_new: error ");
ssss << marpa_c_error(&marpa_config, NULL);
throw std::runtime_error(ssss.str());
}
if (marpa_g_force_valued(g) < 0)
throw std::runtime_error("marpa_g_force_valued failed?!?!?");
if (!marpa)marpa=new MarpaIris();
prvr = prvr_;
prvr2 = new prover(*prvr);
/*bnf:whitespace is a property of bnf:language*/
resid whitespace_ = ask1(prvr2, language, bnf_whitespace);
if (whitespace_) {
whitespace = value(whitespace_);
TRACE(dout << L"whitespace:" << whitespace <<std::endl);
}
/*so is bnf:document, the root rule*/
resid root = ask1(prvr2, language, bnf_document);
sym start = add(root);
start_symbol_set(start);
delete prvr2;
}
//create marpa symbols and rules from grammar description in rdf
sym add(resid thing) {
//what we are adding
string thingv = value(thing);
TRACE(dout << "thingv:" << thingv << std::endl);
//is it a rule or terminal thats been added or we started adding it already?
if (done.find(thing) != done.end())
return done[thing];
//is it a literal?
if ((dict[thing]._type == node::LITERAL) ||
(dict[thing]._type == node::IRI && thingv == L".")) // crap: nquads parser bug workaround
{
//dout << "itsa str"<<std::endl;
for (auto t: literals)
if (t.second == thingv) // is it a done literal?
return t.first;
sym symbol = symbol_new();
//dout << "adding " << thingv << std::endl;
//we add it to the literals table and are done with it.
literals[symbol] = thingv;
return symbol;
}
//dout << "adding " << thingv << std::endl;
sym symbol = symbol_new_resid(thing);
// is it a...
resid bind;
if ((bind = ask1(prvr2, thing, bnf_matches))) {
//dout << "terminal: " << thingv << std::endl;
terminals[symbol] = pterminal(new terminal(thing, thingv, value(bind)));
return symbol;
}
if ((bind = ask1(prvr2, thing, bnf_mustBeOneSequence))) {
// mustBeOneSequence is a list of lists
std::vector <resid> lll = get_list(prvr2, bind);
if (!bind)
throw wruntime_error(L"mustBeOneSequence empty");
for (auto l:lll) {
syms rhs;
std::vector <resid> seq = get_list(prvr2, l);
for (auto rhs_item: seq)
rhs.push_back(add(rhs_item));
rule_new(symbol, rhs);
}
}
else if ((bind = ask1(prvr2, thing, bnf_commaSeparatedListOf))) {
seq_new(symbol, add(bind), add(pcomma), 0, MARPA_PROPER_SEPARATION);
}
else if ((bind = ask1(prvr2, thing, marpa->list_of))) {
auto sep = ask1(prvr2, thing, marpa->separator);
seq_new(symbol, add(bind), sep?add(sep):-1, 0, 0);
}
else if ((bind = ask1(prvr2, thing, bnf_zeroormore))) {
seq_new(symbol, add(bind), -1, 0, 0);
}
else if (thingv == L"http://www.w3.org/2000/10/swap/grammar/bnf#eof") { }//so what?
else
throw wruntime_error(L"whats " + thingv + L"?");
TRACE(dout << "added sym " << symbol << std::endl);
return symbol;
}
int check_int(int result) {
if (result == -2)
error();
return result;
}
void check_null(void *result) {
if (result == NULL)
error();
}
void error_clear() {
marpa_g_error_clear(g);
}
sym symbol_new() {
return check_int(marpa_g_symbol_new(g));
}
sym symbol_new_resid(resid thing) {
return done[thing] = symbol_new();
}
void rule_new(sym lhs, syms rhs) {
TRACE(dout << sym2str(lhs) << L" ::= ");
for (sym s: rhs)
TRACE(dout << sym2str(s));
TRACE(dout << std::endl);
rules[check_int(marpa_g_rule_new(g, lhs, &rhs[0], rhs.size()))] = lhs;
/*if (r == -2)
{
int e = marpa_g_error(g, NULL);
if (e == MARPA_ERR_DUPLICATE_RULE)
{
*/
}
void seq_new(sym lhs, sym rhs, sym separator, int min, int flags) {
int r = marpa_g_sequence_new(g, lhs, rhs, separator, min, flags);
if (r == -2) {
int e = marpa_g_error(g, NULL);
if (e == MARPA_ERR_DUPLICATE_RULE)
dout << sym2str(lhs) << L" ::= sequence of " << sym2str(rhs) << std::endl;
}
rules[check_int(r)] = lhs;
}
void print_events() {
int count = check_int(marpa_g_event_count(g));
if (count > 0) {
dout << count << " events" << std::endl;
Marpa_Event e;
for (int i = 0; i < count; i++) {
int etype = check_int(marpa_g_event(g, &e, i));
dout << L" " << etype << ", " << e.t_value << std::endl;
}
}
}
void start_symbol_set(sym s) {
check_int(marpa_g_start_symbol_set(g, s));
}
void error() {
int e = marpa_g_error(g, NULL);
stringstream s;
s << e << ":" << marpa_error_description[e].name << " - " << marpa_error_description[e].suggested;
throw(std::runtime_error(s.str()));// + ": " + errors[e]));
}
bool is_ws(wchar_t x) {
string wss = L"\n\r \t";
for (auto ws: wss)
if (x == ws)
return true;
return false;
}
termid parse(const string inp) {
if (!precomputed)
check_int(marpa_g_precompute(g));
print_events();
TRACE(dout << "terminals:\n");
for (auto t:terminals)
TRACE(dout << "(" << t.first << ")" << t.second->name << ": " << t.second->regex << std::endl);
TRACE(dout << "tokenizing..\n");
std::vector <tokt> toks; // ranges of individual tokens within the input string
toks.push_back(tokt(inp.end(), inp.end()));
Marpa_Recognizer r = marpa_r_new(g);
check_null(r);
marpa_r_start_input(r);
auto pos = inp.begin();
std::vector <sym> expected;
expected.resize(check_int(marpa_g_highest_symbol_id(g)));
boost::wregex whitespace_regex = boost::wregex(whitespace);
while (pos < inp.end()) {
if (is_ws(*pos)) {
pos++;
continue;
}
boost::wsmatch what;
if (whitespace.size() && regex_search(pos, inp.end(), what, whitespace_regex, boost::match_continuous)) {
if (what.size()) {
int llll = what[0].length();
TRACE(dout << L"skipping " << llll << L" comment chars" << std::endl);
pos += llll;
continue;
}
}
std::vector <sym> best_syms;
size_t best_len = 0;
expected.clear();
int num_expected = check_int(marpa_r_terminals_expected(r, &expected[0]));
for (int i = 0; i < num_expected; i++) {
sym e = expected[i];
if (literals.find(e) != literals.end()) {
if (boost::starts_with(string(pos, inp.end()), literals[e])) {
if (literals[e].size() > best_len) {
best_syms.clear();
best_syms.push_back(e);
best_len = literals[e].size();
}
else if (literals[e].size() == best_len)
best_syms.push_back(e);
}
}
else {
if (terminals.find(e) != terminals.end()) {
auto t = terminals[e];
if (!regex_search(pos, inp.end(), what, t->regex, boost::match_continuous)) continue;
if (what.empty()) continue;
size_t l = what.length();
if (l > best_len) {
best_len = l;
best_syms.clear();
best_syms.push_back(e);
}
else if (l == best_len)
best_syms.push_back(e);
}
}
}
if (best_len) {
if (best_syms.size() > 1) {
dout << L"cant decide between:" << std::endl;
for (auto ccc: best_syms)
dout << L" " << sym2str(ccc) << std::endl;
}
assert(best_syms.size());
toks.push_back(tokt(pos, pos + best_len));
TRACE(dout << std::distance(inp.begin(), pos) << L"-" << std::distance(inp.begin(), pos + best_len) <<
L" \"" << string(pos, pos + best_len) << L"\" - " << sym2str(best_syms[0]) << std::endl);
check_int(marpa_r_alternative(r, best_syms[0], toks.size(), 1));
check_int(marpa_r_earleme_complete(r));
pos += best_len;
}
else {
auto pre(pos);
size_t charnum = 0;
while (pre != inp.begin() && *pre != '\n') {
pre -= 1;
charnum++;
}
//pre -= 10;
auto post(pos);
while (post != inp.end() && *post != '\n')
post += 1;
//post += 10;
dout << L"at line " << 1 + std::count(inp.begin(), pos, '\n') << L", char " << charnum << L":" << std::endl;
auto poss(pos);
//if (poss != inp.begin()) poss--;
dout << string(pre, poss) << L"<HERE>" << string(pos, post) << std::endl;
// dout << L"..\"" << string(pre, pos-1) << L"<HERE>" << string(pos, post) << L"\"..." << std::endl;
dout << "expecting:" << std::endl;
for (int i = 0; i < num_expected; i++) {
sym e = expected[i];
dout << sym2str(e) << std::endl;
}
throw(std::runtime_error("no parse"));
}
}
TRACE(dout << "evaluating.." << std::endl);
//marpa allows variously ordered lists of ambiguous parses, we just grab the default
Marpa_Bocage b = marpa_b_new(r, -1);
check_null(b);
Marpa_Order o = marpa_o_new(b);
check_null(o);
Marpa_Tree t = marpa_t_new(o);
check_null(t);
check_int(marpa_t_next(t));
Marpa_Value v = marpa_v_new(t);
check_null(v);
//"valuator" loop. marpa tells us what rules with what child nodes or tokens were matched,
//we build the value/parse/ast in the stack, bottom-up
map <int, termid> stack;
map <int, string> sexp;
while (1) {
Marpa_Step_Type st = check_int(marpa_v_step(v));
print_events();
if (st == MARPA_STEP_INACTIVE) break;
switch (st) {
case MARPA_STEP_TOKEN: {
sym symbol = marpa_v_symbol(v);
size_t token = marpa_v_token_value(v) - 1;
string token_value = string(toks[token].first, toks[token].second);
sexp[marpa_v_result(v)] = L"/*" + token_value + L"*/";
termid xx;
if (terminals.find(symbol) != terminals.end()) {
xx = prvr->make(mkbnode(gen_bnode_id()));
prvr->kb.add(prvr->make(bnf_matches, xx, prvr->make(terminals[symbol]->thing)));
prvr->kb.add(prvr->make(marpa->has_value, xx, prvr->make(mkliteral(pstr(token_value), XSD_STRING, 0))));
}
else // it must be a literal
xx = prvr->make(mkliteral(pstr(token_value), 0, 0));
stack[marpa_v_result(v)] = xx;
break;
}
case MARPA_STEP_RULE: {
resid res = rule2resid(marpa_v_rule(v));
string sexp_str = L"\"" + value(res) + L"\":{ ";
std::list <termid> args;
for (int i = marpa_v_arg_0(v); i <= marpa_v_arg_n(v); i++) {
if (stack[i]) {
args.push_back(stack[i]);
sexp_str += sexp[i] + L" ";
}
}
termid xx;
// if its a sequence
if (check_int(marpa_g_sequence_min(g, marpa_v_rule(v))) != -1) {
xx = prvr->list2term_simple(args);
}
else {
xx = prvr->make(mkbnode(gen_bnode_id()));
//dout << L".xx: " << prvr->format(xx) << std::endl;
for (int i = 0; i <= marpa_v_arg_n(v) - marpa_v_arg_0(v); i++) {
termid arg = stack[marpa_v_arg_0(v) + i];
if (!arg) continue; // if it was nulled
sym arg_sym = check_int(marpa_g_rule_rhs(g, marpa_v_rule(v), i));
if (literals.find(arg_sym) == literals.end() )
prvr->kb.add(prvr->make(sym2resid(arg_sym), xx, arg));
std::wstringstream arg_pred;
arg_pred << L"http://idni.org/marpa#arg" << i;
prvr->kb.add(prvr->make(mkiri(pstr(arg_pred.str())), xx, arg));
}
}
prvr->kb.add(prvr->make(marpa->is_parse_of, xx, prvr->make(res)));
//dout << L"xx: " << prvr->format(xx) << std::endl;
stack[marpa_v_result(v)] = xx;
sexp[marpa_v_result(v)] = sexp_str + L"} ";
break;
}
case MARPA_STEP_NULLING_SYMBOL:
sexp[marpa_v_result(v)] = L"0";
stack[marpa_v_result(v)] = 0;
break;
default:
dout << marpa_step_type_description[st].name << std::endl;
}
}
marpa_v_unref(v);
if(check_int(marpa_t_next(t)) != -1)
throw std::runtime_error("ambiguous parse");
marpa_t_unref(t);
marpa_o_unref(o);
marpa_b_unref(b);
TRACE(dout << L"{" << sexp[0] << L"}" << std::endl<< std::endl);
termid result = stack[0];
TRACE(dout << L"result0: " << prvr->format(result) << std::endl);
return result;
}
};
class N3 {
public:
pnode uri(std::string s) {
return mkiri(pstr(ws("http://www.w3.org/2000/10/swap/grammar/n3#" + s)));
}
pnode n3symbol = uri("symbol");
pnode n3subject = uri("subject");
pnode n3object = uri("object");
pnode n3objecttail = uri("objecttail");
pnode n3explicituri = uri("explicituri");
pnode n3propertylist = uri("propertylist");
pnode n3propertylisttail = uri("propertylisttail");
pnode n3expression = uri("expression");
pnode n3pathitem = uri("pathitem");
pnode n3predicate = uri("predicate");
//pnode n3statement_with_dot = uri("statement_with_dot");
pnode n3statement = uri("statement");
pnode n3declaration = uri("declaration");
pnode n3simpleStatement = uri("simpleStatement");
pnode n3prefix = uri("prefix");
pnode n3qname = uri("qname");
pnode n3literal = uri("literal");
pnode n3numericliteral = uri("numericliteral");
pnode n3string = uri("string");
pnode n3boolean = uri("boolean");
pnode n3integer = uri("integer");
//pnode n3dtlang = uri("dtlang");
pnode n3quickvariable= uri("quickvariable");
pnode n3formulacontent = uri("formulacontent");
prover *prvr;
qdb *dest;
qdb kb;
qdb query;
bool single_file_mode;
map<string, string> prefixes;
string listid()
{
static int curid = 0;
std::wstringstream ss;
ss << L"_:list" << curid++;
return ss.str();
};
resids get_dotstyle_list(termid l) {
std::list<resid> r;
prvr->get_dotstyle_list(l, r);
resids rr;
for (auto x:r)
rr.push_back(x);
return rr;
}
string get_value(resid n)
{
assert(n);
resid v = q(n, marpa->has_value);
assert(v);
auto s = dict[v].value;
assert(s);
return *s;
}
N3(prover &prvr_, bool single_file_mode_ = false):prvr(&prvr_), single_file_mode(single_file_mode_), dest(&kb)
{
if (!marpa)marpa=new MarpaIris();
}
resid q(resid s, pnode p)
{
return ask1(prvr, s, p);
}
void trim(string &s, string xxx)
{
assert(startsWith(s, xxx));
assert(endsWith(s, xxx));
s.erase(0, xxx.size());
s.erase(s.size() - xxx.size());
}
pnode add_literal(resid x) {
resid sss = q(x, n3string);
assert (sss);
resid v = q(sss, marpa->has_value);
assert(v);
string s = *dict[v].value;
string triple = string(L"\"\"\"");
if(startsWith(s, triple))
trim(s, triple);
else
trim(s, L"\"");
return mkliteral(pstr(s), 0, 0);
}
pnode add_numericliteral(resid x) {
resid sss = q(x, n3integer);
assert (sss);
resid v = q(sss, marpa->has_value);
assert(v);
return mkliteral(dict[v].value, XSD_INTEGER, 0);
}
pnode add_boolean(resid x) {
resid v = q(x, marpa->arg0);
assert(v);
auto s = *dict[v].value;
s.erase(0, 1);
return mkliteral(pstr(s), XSD_BOOLEAN, 0);
}
pnode add_symbol(resid x)
{
resid uri = q(x, n3explicituri);
if (uri)
{
resid val = q(uri, marpa->has_value);
assert(val);
return mkiri(dict[val].value);
}
resid qname = q(x, n3qname);
if (qname)
{
string v = get_value(qname);
auto pos = v.find(L":");
if (pos != string::npos)
{
string pref = string(v.begin(), v.begin() + pos);
if (prefixes.find(pref) != prefixes.end())
{
string rest = string(v.begin() + pos + 1, v.end());
v = prefixes[pref] + rest;
}
}
return mkiri(pstr(v));
}
assert(false);
}
pnode add_quickvariable(resid x)
{
resid v = q(x, marpa->has_value);
assert(v);
string s = *dict[v].value;
//s[0] = '?';//workaround
return mkiri(pstr(s));
}
pnode add_formulacontent(termid x)
{
auto graph = mkbnode(gen_bnode_id());
add_statements(x, *graph->value);
return graph;
}
pnode add_pathlist(termid/*TERMID - internalized list*/x)
{
std::list<pnode> r;
if(x) {
resids items = get_dotstyle_list(x);
for (auto i:items)
r.push_back(add_expression(i));
}
auto id = listid();
dest->second[id] = r;
return mkbnode(pstr(id));
}
pnode add_pathitem(resid pi)
{
resid sym = q(pi, n3symbol);
if (sym)
return add_symbol(sym);
termid f = ask1t(prvr, pi, n3formulacontent);
if (f)
return add_formulacontent(f);
resid qv = q(pi, n3quickvariable);
if (qv)
return add_quickvariable(qv);
resid nl = q(pi, n3numericliteral);
if (nl)
return add_numericliteral(nl);
resid lit = q(pi, n3literal);
if (lit)
return add_literal(lit);
//( "[" propertylist "]" )
resid l = q(pi, marpa->arg0);
if(l && *dict[l].value == L"(") {
termid x = ask1t(prvr, pi, marpa->arg1);
return add_pathlist(x);
}
resid b = q(pi, n3boolean);
if (b)
return add_boolean(b);
assert(false);
}
pnode add_expression(resid e)
{
resid sepi = q(e, n3pathitem);
assert(sepi);
//todo pathtail
return add_pathitem(sepi);
}
void add_simpleStatement(resid sim, string graph)
{
assert(sim);
TRACE(dout << " " << sim << " ");
resid subj = q(sim, n3subject);
assert(subj);
resid se = q(subj, n3expression);
assert(se);
resid sepi = q(se, n3pathitem);
assert(sepi);
pnode subject = add_pathitem(sepi);
resid sspl = q(sim, n3propertylist);
if (sspl) {
resid prop = sspl;
resids props;
while (prop) {
props.push_back(prop);
prop = q(prop, n3propertylisttail);
if (prop)
prop = q(prop, n3propertylist);
}
TRACE(dout << "props:" << props.size());
//now we have property lists in a list
for (auto prop:props) {
pnode predicate;
bool reverse = false;
resid pred = q(prop, n3predicate);
resid pe = q(pred, n3expression);
//get string value of first item
resid i0 = q(pred, marpa->arg0);
string i0v = *dict[i0].value; //?
if (pe) { // if this predicate contains an expression
predicate = add_expression(pe);
/* ( expression )
( "@has" expression )
( "@is" expression "@of" )*/
if (i0v == L"@is")
reverse = true;
}
else {
string ps;
if (i0v == L"@a")
ps = L"http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
else if (i0v == L"=")
ps = L"http://www.w3.org/2002/07/owl#sameAs";
else if (i0v == L"=>")
ps = L"http://www.w3.org/2000/10/swap/log#implies";
else if (i0v == L"<=") {
ps = L"http://www.w3.org/2000/10/swap/log#implies";
reverse = true;
}
else
throw std::runtime_error("this shouldnt happen");
predicate = mkiri(pstr(ps));
}
/* objects */
std::vector<pnode> objs;
resid t = prop;
while (t) {
resid ob = q(t, n3object);
if(!ob)break;
resid oe = q(ob, n3expression);
objs.push_back(add_expression(oe));
t = q(t, n3objecttail);
}
for (auto object: objs) {
pnode s, o;
if (reverse) {
s = object;
o = subject;
}
else {
o = object;
s = subject;
}
if(dest->first.find(graph) == dest->first.end())
dest->first[graph] = mk_qlist();
dest->first[graph]->push_back(make_shared<quad>(s, predicate, o, graph));
}
}
}
else if (single_file_mode && *subject->value == L"fin" && graph == L"@default") {
single_file_mode = false;//ignore further fins
dout << kb.first.size() << " rules loaded." << std::endl;
dest = &query;
}
}
void add_statements(termid list, string graph) {
resids statements = get_dotstyle_list(list);
TRACE(dout << std::endl << graph << ":" << std::endl);
for (auto s: statements) {
if (ask(prvr, s, marpa->is_parse_of, n3statement)) {
resid sim = q(s, n3simpleStatement);
if (sim)
add_simpleStatement(sim, graph);
}else if (ask(prvr, s, marpa->is_parse_of, n3declaration)) {
resid decl = q(s, n3declaration);
resid a0 = q(decl, marpa->arg0);
assert(a0);
if(*dict[a0].value == L"@prefix")
{
resid p = q(decl, n3prefix);
resid uri = q(decl, n3explicituri);
string uri_s = get_value(uri);
string p_s = get_value(p);
prefixes[p_s] = uri_s;
}
}
}
}
};
N3 parse(std::ifstream &f, prover& grammar, bool single_file_mode = false)
{
setproc(L"N3");
prover prvr(grammar);
pnode input = mkliteral(pstr(load_file(f)), 0, 0);
assert(input);
prvr.kb.add(
prvr.make(
mkiri(pstr(L":contents")),
prvr.make(mkiri(pstr(L":input"))),
prvr.make(input)));
std::wifstream ln3("load_n3");
auto query = readqdb (ln3);
TRACE(dout << "query loaded.");
prvr.do_query(query);
TRACE(dout << "query done.");
termid raw = 0;
for (auto x : prvr.subs) {
TRACE(dout << "subst:");
TRACE(prvr.prints(x));
TRACE(dout << std::endl);
for (auto it: x) {
TRACE(dout << *dict[it.first].value << std::endl);
if (*dict[it.first].value == L"?O") {
raw = it.second;
break;
}
}
}
prvr.subs.clear();
prvr.e.clear();
TRACE(dout << std::endl << std::endl << "prvr:" << std::endl << prvr.formatkb());
if (!raw)
throw std::runtime_error("oopsie, something went wrong with your tau.");
/*
query = load_quads(L"test", true);
dout << "------" << std::endl;
prover prvr2(prvr);
prvr2(*query);
*/
TRACE(dout << "retrieving results." << std::endl);
N3 n3(prvr, single_file_mode);
n3.add_statements(raw, L"@default");
return n3;
}
/*cli*/
std::string load_n3_cmd::desc() const { return "load n3"; }
std::string load_n3_cmd::help() const {
stringstream ss("Hilfe! Hilfe!:");
return ss.str();
}
int load_n3_cmd::operator()(const strings &args) {
prover prvr(*load_quads(L"n3-grammar.nq", false));
TRACE(dout << "grammar loaded."<<std::endl);
if (args.size() == 4) {
std::string fname = ws(args[2]);
std::ifstream f(fname);
if (!f.is_open())
throw std::runtime_error("couldnt open natural3 kb file \"" + fname + "\"");
N3 kb = parse(f, prvr);
fname = ws(args[3]);
std::ifstream qf(fname);
if (!qf.is_open())
throw std::runtime_error("couldnt open natural3 query file \"" + fname + "\"");
N3 query = parse(qf, prvr);