-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathexecutive.h
2338 lines (2141 loc) · 86.8 KB
/
executive.h
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
#ifndef EXECUTIVE_H_
#define EXECUTIVE_H_
#include "article.h"
#include "natural_deduction_mh.h"
constexpr double PERPLEXITY_THRESHOLD = 0.0; //0.01;
constexpr double SUFFICIENT_KNOWLEDGE_THRESHOLD = 8.0;
/* TODO: for debugging; delete these */
#include <atomic>
std::atomic_uint total_read_sentence(0);
std::atomic_uint add_formula_failures(0);
std::atomic_uint total_add_formula(0);
template<typename Formula>
inline void free_logical_forms(Formula** logical_forms, unsigned int count)
{
for (unsigned int i = 0; i < count; i++) {
free(*logical_forms[i]);
if (logical_forms[i]->reference_count == 0)
free(logical_forms[i]);
}
}
inline bool concatenate(
sentence_token* tokens, unsigned int token_count,
string& out, const string** reverse_string_map)
{
unsigned int length = reverse_string_map[tokens[0].id]->length;
for (unsigned int i = 1; i < token_count; i++)
length += 1 + reverse_string_map[tokens[i].id]->length;
if (!core::resize(out.data, length)) return false;
out.length = length;
unsigned int index = 0;
for (unsigned int i = 0; i < token_count; i++) {
if (i > 0) { out[index] = ' '; index++; }
for (unsigned int j = 0; j < reverse_string_map[tokens[i].id]->length; j++) {
out[index] = reverse_string_map[tokens[i].id]->data[j];
index++;
}
}
return true;
}
#if defined(SANITIZE_ADDRESS)
/* TODO: for memory debugging; delete this */
#include <sanitizer/lsan_interface.h>
#endif
template<typename ArticleSource, typename Parser,
typename Formula, bool Intuitionistic,
typename Canonicalizer, typename TheoryPrior, typename... Args>
bool read_sentence(
const ArticleSource& articles, Parser& parser, const typename Parser::SentenceType& s,
theory<natural_deduction<Formula, Intuitionistic>, Canonicalizer>& T,
unsigned int article_name, hash_map<string, unsigned int>& names,
hash_set<unsigned int>& visited_articles, TheoryPrior& theory_prior,
typename TheoryPrior::PriorState& proof_axioms,
unsigned int mcmc_iterations_per_retry = 100,
unsigned int max_retries = 0, Args&&... add_formula_args)
{
null_collector collector;
unsigned int parse_count, new_constant;
Formula* logical_forms[2];
double log_probabilities[2];
while (true) {
/* attempt to parse the sentence */
array<array<sentence_token>> unrecognized(16);
print("Reading sentence: '", stdout); print(s, stdout, parser.get_printer()); print("'\n", stdout);
if (!parser.template parse<2>(s, logical_forms, log_probabilities, parse_count, T, unrecognized, names)) {
print("read_sentence ERROR: Unable to parse sentence '", stderr); print(s, stderr, parser.get_printer()); print("'.\n", stderr);
return false;
}
#if defined(SANITIZE_ADDRESS)
// TODO: for memory debugging; delete this
__lsan_do_leak_check();
#endif
/* concatenate the unrecognized tokens */
array<unsigned int> unrecognized_concatenated(max((size_t) 1, unrecognized.length));
for (unsigned int i = 0; i < unrecognized.length; i++) {
string concatenated(16);
if (!concatenate(unrecognized[i].data, unrecognized[i].length, concatenated, parser.reverse_string_map())) {
for (array<sentence_token>& tokens : unrecognized) free(tokens);
free_logical_forms(logical_forms, parse_count);
return false;
}
bool contains;
unsigned int concatenated_id = names.get(concatenated, contains);
if (contains)
unrecognized_concatenated[unrecognized_concatenated.length++] = concatenated_id;
}
for (array<sentence_token>& tokens : unrecognized) free(tokens);
/* get unrecognized named entities */
array<string> named_entities(16);
if (parse_count > 0 && !get_named_entities(*logical_forms[0], named_entities)) {
free_logical_forms(logical_forms, parse_count);
return false;
}
for (const string& named_entity : named_entities) {
bool contains;
unsigned int named_entity_id = names.get(named_entity, contains);
if (contains
&& (named_entity_id == article_name || !visited_articles.contains(named_entity_id))
&& !unrecognized_concatenated.add(named_entity_id))
{
for (string& entity : named_entities) free(entity);
free_logical_forms(logical_forms, parse_count);
return false;
}
}
for (string& entity : named_entities) free(entity);
/* preemptively remove tokens for which an article doesn't exist in the corpus */
for (unsigned int i = 0; i < unrecognized_concatenated.length; i++) {
if (!articles.contains(unrecognized_concatenated[i])) {
if (!visited_articles.add(unrecognized_concatenated[i])) {
free_logical_forms(logical_forms, parse_count);
return false;
}
unrecognized_concatenated.remove(i--);
}
}
/* read the article on the unrecognized word */
if (unrecognized_concatenated.length == 0) {
break;
} else if (parse_count > 0 && unrecognized_concatenated.length == 1 && unrecognized_concatenated[0] == article_name) {
/* this could be a definition so try adding it to the theory */
set_changes<Formula> set_diff;
auto* new_proof = T.add_formula(logical_forms[0], set_diff, new_constant, std::forward<Args>(add_formula_args)...);
for (unsigned int i = 0; new_proof == nullptr && i < max_retries; i++) {
set_diff.clear();
for (unsigned int t = 0; t < mcmc_iterations_per_retry; t++)
do_exploratory_mh_step(T, theory_prior, proof_axioms, collector);
new_proof = T.add_formula(logical_forms[0], set_diff, new_constant, std::forward<Args>(add_formula_args)...);
}
if (new_proof != nullptr) {
if (proof_axioms.add(new_proof, set_diff.new_set_axioms, theory_prior)) {
if (!parser.add_definition(s, logical_forms[0], new_constant, names)) {
proof_axioms.subtract(new_proof, set_diff.new_set_axioms, theory_prior);
T.remove_formula(new_proof, set_diff);
new_proof = nullptr;
/* TODO: for debugging; delete this */
exit(EXIT_FAILURE);
}
} else {
T.remove_formula(new_proof, set_diff);
new_proof = nullptr;
}
}
if (new_proof == nullptr) {
print("read_sentence ERROR: Unable to add definition to theory.\n", stderr);
print(" Sentence: '", stderr); print(s, stderr, parser.get_printer()); print("'\n", stderr);
print(" Logical form: ", stderr); print(*logical_forms[0], stderr, parser.get_printer()); print("\n", stderr);
free_logical_forms(logical_forms, parse_count);
return false;
}
free_logical_forms(logical_forms, parse_count);
//for (unsigned int t = 0; t < 10; t++)
// do_mh_step(T, theory_prior, proof_axioms, collector);
return true;
}
/* find an article in order to learn about the unrecognized word */
unsigned int next_article = unrecognized_concatenated[0];
if (next_article == article_name) {
if (unrecognized_concatenated.length == 1) {
fprintf(stderr, "read_sentence ERROR: Unable to parse definitional sentence.\n");
free_logical_forms(logical_forms, parse_count);
return false;
}
next_article = unrecognized_concatenated[1];
}
read_article(next_article, articles, parser, T, names, visited_articles, theory_prior, proof_axioms, std::forward<Args>(add_formula_args)...);
free_logical_forms(logical_forms, parse_count);
}
if (parse_count == 0) {
fprintf(stderr, "read_sentence ERROR: Given sentence has no valid parses.\n");
return false;
} else if (parse_count > 1 && (log_probabilities[0] - log_probabilities[1]) / s.length < PERPLEXITY_THRESHOLD) {
/* this parse is too ambiguous */
free_logical_forms(logical_forms, parse_count);
return true;
}
/* add the most probable logical form to the theory */
total_add_formula++;
set_changes<Formula> set_diff;
auto* new_proof = T.add_formula(logical_forms[0], set_diff, new_constant, std::forward<Args>(add_formula_args)...);
total_read_sentence++;
fprintf(stderr, "total_read_sentence = %u, add_formula_failures = %u, total_add_formula = %u\n", total_read_sentence.load(), add_formula_failures.load(), total_add_formula.load());
for (unsigned int i = 0; new_proof == nullptr && i < max_retries; i++) {
add_formula_failures++;
set_diff.clear();
auto collector = make_log_probability_collector(T, theory_prior);
for (unsigned int t = 0; t < mcmc_iterations_per_retry; t++)
do_exploratory_mh_step(T, theory_prior, proof_axioms, collector);
total_add_formula++;
new_proof = T.add_formula(logical_forms[0], set_diff, new_constant, std::forward<Args>(add_formula_args)...);
}
if (new_proof != nullptr && !proof_axioms.add(new_proof, set_diff.new_set_axioms, theory_prior)) {
T.remove_formula(new_proof, set_diff);
new_proof = nullptr;
}
if (new_proof == nullptr) {
print("read_sentence ERROR: Unable to add logical form to theory.\n", stderr);
print(" Sentence: '", stderr); print(s, stderr, parser.get_printer()); print("'\n", stderr);
print(" Logical form: ", stderr); print(*logical_forms[0], stderr, parser.get_printer()); print("\n", stderr);
free_logical_forms(logical_forms, parse_count);
return false;
}
//for (unsigned int t = 0; t < 10; t++)
// do_mh_step(T, theory_prior, proof_axioms, collector);
free_logical_forms(logical_forms, parse_count);
return true;
}
template<typename ArticleSource, typename Parser,
typename Formula, bool Intuitionistic,
typename Canonicalizer, typename TheoryPrior, typename... Args>
bool read_article(
unsigned int article_name, const ArticleSource& articles, Parser& parser,
theory<natural_deduction<Formula, Intuitionistic>, Canonicalizer>& T,
hash_map<string, unsigned int>& names, hash_set<unsigned int>& visited_articles,
TheoryPrior& theory_prior, typename TheoryPrior::PriorState& proof_axioms,
unsigned int mcmc_iterations_per_retry = 100,
unsigned int max_retries = 0, Args&&... add_formula_args)
{
print("Reading article: '", stdout); print(article_name, stdout, parser.get_printer()); print("'\n", stdout);
bool article_exists;
const auto& doc = articles.get(article_name, article_exists);
if (!visited_articles.add(article_name)) {
return false;
} else if (!article_exists) {
print("read_article ERROR: No such article '", stderr); print(article_name, stderr, parser.get_printer()); print("'.\n", stderr);
return false;
}
for (unsigned int i = 0; i < doc.sentence_count; i++) {
if (!read_sentence(articles, parser, doc.sentences[i], T, article_name, names, visited_articles, theory_prior, proof_axioms, mcmc_iterations_per_retry, max_retries, std::forward<Args>(add_formula_args)...))
return false;
}
return true;
}
template<typename ArticleSource, typename Parser,
typename Formula, bool Intuitionistic,
typename Canonicalizer, typename TheoryPrior, typename... Args>
inline bool read_sentence(
const ArticleSource& articles, Parser& parser, const char* input_sentence,
theory<natural_deduction<Formula, Intuitionistic>, Canonicalizer>& T,
hash_map<string, unsigned int>& names, hash_set<unsigned int>& visited_articles,
TheoryPrior& theory_prior, typename TheoryPrior::PriorState& proof_axioms,
unsigned int mcmc_iterations_per_retry = 100,
unsigned int max_retries = 0, Args&&... add_formula_args)
{
typename Parser::SentenceType sentence;
if (!tokenize(input_sentence, sentence, names)
|| !parser.invert_name_map(names))
return false;
bool result = read_sentence(articles, parser, sentence, T, UINT_MAX, names, visited_articles, theory_prior, proof_axioms, mcmc_iterations_per_retry, max_retries, std::forward<Args>(add_formula_args)...);
free(sentence);
return result;
}
template<typename Parser, size_t ParseCount>
inline bool parse_sentence(Parser& parser,
const typename Parser::SentenceType& sentence,
hash_map<string, unsigned int>& names,
hol_term* (&logical_forms)[ParseCount],
double (&log_probabilities)[ParseCount],
unsigned int& parse_count)
{
array<array<sentence_token>> unrecognized(4);
if (parser.invert_name_map(names)) {
if (parser.template parse<ParseCount>(sentence, logical_forms, log_probabilities, parse_count, nullptr, unrecognized, names)) {
for (array<sentence_token>& tokens : unrecognized) free(tokens);
return true;
} else {
fprintf(stderr, "ERROR: Parsing failed.\n");
return false;
}
} else {
fprintf(stderr, "ERROR: `invert_name_map` failed.\n");
return false;
}
}
template<typename Parser, size_t ParseCount>
inline bool parse_sentence(Parser& parser,
const char* input_sentence,
hash_map<string, unsigned int>& names,
hol_term* (&logical_forms)[ParseCount],
double (&log_probabilities)[ParseCount],
unsigned int& parse_count)
{
typename Parser::SentenceType sentence;
if (!tokenize(input_sentence, sentence, names))
return false;
if (!parse_sentence(parser, sentence, names, logical_forms, log_probabilities, parse_count)) {
free(sentence);
return false;
}
free(sentence);
return true;
}
template<typename Parser, typename ProofCalculus, typename Canonicalizer, typename TheoryPrior>
inline bool parse_sentence_with_prior(Parser& parser, const char* input_sentence,
theory<ProofCalculus, Canonicalizer>& T, hash_map<string, unsigned int>& names,
TheoryPrior& theory_prior, typename TheoryPrior::PriorState& proof_axioms)
{
static constexpr unsigned int max_parse_count = 6;
hol_term* logical_forms[max_parse_count];
double log_likelihoods[max_parse_count];
unsigned int parse_count;
if (!parse_sentence(parser, input_sentence, names, logical_forms, log_likelihoods, parse_count))
return false;
double log_priors[max_parse_count];
double log_posteriors[max_parse_count];
for (unsigned int i = 0; i < parse_count; i++) {
log_priors[i] = log_joint_probability_of_observation(T, theory_prior, proof_axioms, logical_forms[i], 100000);
log_posteriors[i] = log_likelihoods[i] + log_priors[i];
}
unsigned int sorted_indices[max_parse_count];
for (unsigned int i = 0; i < parse_count; i++)
sorted_indices[i] = i;
if (parse_count > 1) {
insertion_sort(log_posteriors, sorted_indices, parse_count);
reverse(log_posteriors, parse_count);
reverse(sorted_indices, parse_count);
}
for (unsigned int i = 0; i < parse_count; i++) {
print(*logical_forms[sorted_indices[i]], stderr, parser.get_printer());
print(" with log likelihood ", stderr); print(log_likelihoods[sorted_indices[i]], stderr);
print(" + log prior ", stderr); print(log_priors[sorted_indices[i]], stderr);
print(" = log posterior ", stderr); print(log_posteriors[i], stderr);
print('\n', stderr);
free(*logical_forms[sorted_indices[i]]);
if (logical_forms[sorted_indices[i]]->reference_count == 0)
free(logical_forms[sorted_indices[i]]);
}
return true;
}
template<typename Parser>
inline bool parse_sentence(Parser& parser, const char* input_sentence, hash_map<string, unsigned int>& names)
{
static constexpr unsigned int max_parse_count = 4;
hol_term* logical_forms[max_parse_count];
double log_probabilities[max_parse_count];
unsigned int parse_count;
if (!parse_sentence(parser, input_sentence, names, logical_forms, log_probabilities, parse_count))
return false;
for (unsigned int i = 0; i < parse_count; i++) {
print(*logical_forms[i], stderr, parser.get_printer()); print(" with log probability ", stderr); print(log_probabilities[i], stderr); print('\n', stderr);
free(*logical_forms[i]);
if (logical_forms[i]->reference_count == 0)
free(logical_forms[i]);
}
return true;
}
template<typename Parser, typename Formula>
inline bool parse_sentence(
Parser& parser, const char* input_sentence, hash_map<string, unsigned int>& names,
array<array_map<typename Parser::SentenceType, Formula>>& training_set)
{
typename Parser::SentenceType sentence;
if (!tokenize(input_sentence, sentence, names))
return false;
static constexpr unsigned int max_parse_count = 4;
hol_term* logical_forms[max_parse_count];
double log_probabilities[max_parse_count];
unsigned int parse_count = 0;
bool result = parse_sentence(parser, sentence, names, logical_forms, log_probabilities, parse_count);
extern const thread_local string_map_scribe* debug_terminal_printer;
debug_terminal_printer = &parser.get_printer();
for (const auto& paragraph : training_set) {
bool found_training_sentence = false;
for (const auto& entry : paragraph) {
sequence expected_sentence(nullptr, 0);
if (is_empty(entry.key.derivation)) {
expected_sentence.tokens = (unsigned int*) malloc(sizeof(unsigned int) * entry.key.length);
if (expected_sentence.tokens == nullptr) {
fprintf(stderr, "parse_sentence ERROR: Out of memory.\n");
result = false; found_training_sentence = true;
break;
}
for (unsigned int i = 0; i < entry.key.length; i++)
expected_sentence.tokens[i] = entry.key.tokens[i].id;
expected_sentence.length = entry.key.length;
} else {
if (!yield(parser.G, *entry.key.derivation.tree, entry.value, expected_sentence, parser.get_printer(), entry.key.derivation.root))
continue;
}
if (expected_sentence.length != sentence.length) {
free(expected_sentence);
continue;
}
bool are_sentences_identical = true;
for (unsigned int i = 0; i < sentence.length && are_sentences_identical; i++)
if (sentence.tokens[i].id != expected_sentence.tokens[i]) are_sentences_identical = false;
if (!are_sentences_identical) {
free(expected_sentence);
continue;
}
free(expected_sentence);
found_training_sentence = true;
if (parse_count == 0) {
fprintf(stderr, "parse_sentence WARNING: Unable to parse sentence '%s' despite being in the training data.\n", input_sentence);
break;
}
if (!equivalent(logical_forms[0], entry.value.root)) {
fprintf(stderr, "parse_sentence WARNING: The parsed logical form does not match the label logical form in the training data:\n");
fprintf(stderr, " Sentence: '%s'\n", input_sentence);
print(" Parsed logical form: ", stderr); print(*logical_forms[0], stderr, parser.get_printer()); print('\n', stderr);
print(" Expected logical form: ", stderr); print(*entry.value.root, stderr, parser.get_printer()); print('\n', stderr);
if (!is_empty(entry.key.derivation)) {
double expected_log_probability = log_probability(parser.G, *entry.key.derivation.tree, entry.value, parser, entry.key.derivation.root);
print(" with log probability ", stderr); print(expected_log_probability, stderr); print('\n', stderr);
}
}
break;
}
if (found_training_sentence) break;
}
for (unsigned int i = 0; i < parse_count; i++) {
print(*logical_forms[i], stderr, parser.get_printer()); print(" with log probability ", stderr); print(log_probabilities[i], stderr); print('\n', stderr);
}
if (parse_count != 0) {
unsigned int generated_derivation_count;
static constexpr unsigned int max_generated_derivation_count = 12;
double log_likelihoods[max_generated_derivation_count];
typename Parser::DerivationType* generated_derivations =
(typename Parser::DerivationType*) alloca(sizeof(typename Parser::DerivationType) * max_generated_derivation_count);
if (!parser.template generate<max_generated_derivation_count>(generated_derivations, log_likelihoods, generated_derivation_count, logical_forms[0], names) || generated_derivation_count == 0) {
fprintf(stderr, "parse_sentence ERROR: Failed to generate derivation.\n");
for (unsigned int i = 0; i < parse_count; i++) {
free(*logical_forms[i]);
if (logical_forms[i]->reference_count == 0)
free(logical_forms[i]);
}
free(sentence);
return false;
}
const string** nonterminal_name_map = invert(parser.G.nonterminal_names);
string_map_scribe nonterminal_printer = { nonterminal_name_map, parser.G.nonterminal_names.table.size + 1 };
fprintf(stderr, "Generated %u derivations:\n", generated_derivation_count);
for (unsigned int i = 0; i < generated_derivation_count; i++) {
/* compute the yield of the derivation */
sequence new_sentence = sequence(NULL, 0);
if (!parser.yield(generated_derivations[i], logical_forms[0], new_sentence)) {
for (unsigned int i = 0; i < parse_count; i++) {
free(*logical_forms[i]);
if (logical_forms[i]->reference_count == 0)
free(logical_forms[i]);
} for (unsigned int i = 0; i < generated_derivation_count; i++)
free(generated_derivations[i]);
free(sentence); free(nonterminal_name_map);
return false;
}
print('"', stderr); print(new_sentence, stderr, parser.get_printer());
print("\" with log likelihood ", stderr); print(log_likelihoods[i], stderr);
print(" and derivation tree:\n", stderr);
print(generated_derivations[i], stderr, nonterminal_printer, parser.get_printer());
print('\n', stderr);
free(new_sentence);
}
free(nonterminal_name_map);
for (unsigned int i = 0; i < generated_derivation_count; i++)
free(generated_derivations[i]);
}
for (unsigned int i = 0; i < parse_count; i++) {
free(*logical_forms[i]);
if (logical_forms[i]->reference_count == 0)
free(logical_forms[i]);
}
free(sentence);
return result;
}
#include "network.h"
#include <fcntl.h>
#if !defined(DISABLE_SSL)
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/conf.h>
inline ssize_t read(SSL* ssl, void* buf, size_t nbytes) {
return SSL_read(ssl, buf, nbytes);
}
#elif defined(_WIN32)
inline ssize_t read(SOCKET handle, void* buf, size_t count) {
return recv(handle, buf, count, 0);
}
#endif /* DISABLE_SSL */
template<unsigned int BufferSize, typename Stream>
struct buffered_socket {
Stream& underlying_stream;
unsigned long long timeout_ms;
array<char> buffer;
size_t position;
bool eof;
buffered_socket(Stream& underlying_stream, unsigned long long timeout_ms) :
underlying_stream(underlying_stream), timeout_ms(timeout_ms), buffer(4096), position(0), eof(false) { }
bool fill_buffer() {
if (!buffer.ensure_capacity(buffer.length + BufferSize))
return false;
timer stopwatch;
while (true) {
int bytes_read = read(underlying_stream, buffer.data + buffer.length, BufferSize);
if (bytes_read == 0) {
eof = true;
return true;
} else if (bytes_read > 0) {
buffer.length += bytes_read;
return true;
#if defined(_WIN32)
} else if (WSAGetLastError() != WSAEWOULDBLOCK) {
fprintf(stderr, "buffered_socket.fill_buffer ERROR: `read` failed.\n");
return false;
#else
} else if (errno != EAGAIN && errno != EWOULDBLOCK) {
fprintf(stderr, "buffered_socket.fill_buffer ERROR: `read` failed.\n");
return false;
#endif
}
if (stopwatch.milliseconds() > timeout_ms)
return false;
}
}
};
template<unsigned int BufferSize, typename Stream>
int fgetc(buffered_socket<BufferSize, Stream>& in) {
if (in.position == in.buffer.length && (!in.fill_buffer() || in.eof))
return EOF;
return in.buffer[in.position++];
}
template<typename Stream>
bool read_line(Stream& in, array<char>& line)
{
while (true) {
int next = fgetc(in);
if (next == EOF) {
return false;
} else if (next == '\r') {
next = fgetc(in);
if (next == '\n') {
break;
} else {
if (!line.add('\r') || !line.add(next)) return false;
}
} else {
if (!line.add(next)) return false;
}
}
return true;
}
struct throttler
{
array_map<string, unsigned long long> next_request_times;
throttler() : next_request_times(16) { }
~throttler() {
for (auto entry : next_request_times) free(entry.key);
}
inline void prune_old_request_times()
{
unsigned long long current_time = milliseconds();
for (unsigned int i = 0; i < next_request_times.size; i++) {
if (current_time >= next_request_times.values[i]) {
free(next_request_times.keys[i]);
next_request_times.remove_at(i--);
}
}
}
inline unsigned long long get_next_request_time(const string& hostname) const
{
size_t index = next_request_times.index_of(hostname);
if (index < next_request_times.size)
return next_request_times.values[index];
else return 0;
}
inline bool set_next_request_time(const string& hostname, unsigned long long next_request_time) {
return next_request_times.put(hostname, next_request_time);
}
};
/* TODO: make this thread-safe */
throttler GLOBAL_THROTTLER;
constexpr unsigned long long THROTTLE_DURATION_MILLISECONDS = 400;
template<typename Stream>
bool parse_http_status(Stream& in,
string& version, unsigned int& status, string& reason)
{
/* read the first line */
array<char> line(64);
if (!read_line(in, line)) return false;
/* first try tokenizing the line */
unsigned int index = line.index_of(' ');
if (index == line.length) {
fprintf(stderr, "parse_http_status ERROR: HTTP response status is malformed.\n");
return false;
} else if (!init(version, line.data, index)) {
return false;
}
/* make sure the version starts with 'HTTP/' */
static string VERSION_PREFIX("HTTP/");
if (!compare_strings(VERSION_PREFIX, version.data, min(version.length, VERSION_PREFIX.length))) {
fprintf(stderr, "parse_http_status ERROR: HTTP response version string is malformed.\n");
return false;
}
unsigned int second_index = line.index_of(' ', index + 1);
if (second_index == line.length) {
if (!init(reason, 0)) {
free(version);
return false;
}
} else {
if (!init(reason, line.data + second_index + 1, line.length - second_index - 1)) {
free(version);
return false;
}
}
if (!parse_uint(string(line.data + index + 1, second_index - index - 1), status)) {
fprintf(stderr, "parse_http_status ERROR: Unable to parse HTTP response code.\n");
free(version); free(reason); return false;
} else if (status < 100 || status > 999) {
fprintf(stderr, "parse_http_status ERROR: Illegal HTTP response code.\n");
free(version); free(reason); return false;
}
return true;
}
template<typename Stream, typename FilterResponseHeader>
bool parse_http_response(Stream& in, array<char>& payload,
FilterResponseHeader filter_response_header)
{
unsigned int status;
string& version = *((string*) alloca(sizeof(string)));
string& reason = *((string*) alloca(sizeof(string)));
if (!parse_http_status(in, version, status, reason))
return false;
/* TODO: handle status 100 (CONTINUE) */
free(version); free(reason);
/* parse the headers */
array_map<string, string> headers(16);
while (true) {
array<char> line(64);
if (!read_line(in, line)) return false;
if (line.length == 0) break;
if (!headers.ensure_capacity(headers.size + 1)) {
for (auto entry : headers) { free(entry.key); free(entry.value); }
return false;
}
unsigned int index = line.index_of(':');
for (unsigned int i = 0; i < index; i++)
line[i] = tolower(line[i]);
unsigned int second_start = index + 1;
while (second_start < line.length && isspace(line[second_start])) second_start++;
while (second_start < line.length && isspace(line[line.length - 1])) line.length--;
if (!init(headers.keys[headers.size], line.data, index)) {
for (auto entry : headers) { free(entry.key); free(entry.value); }
return false;
} else if (!init(headers.values[headers.size], line.data + second_start, line.length - second_start)) {
free(headers.keys[headers.size]);
for (auto entry : headers) { free(entry.key); free(entry.value); }
return false;
}
headers.size++;
}
if (!filter_response_header(status, headers)) {
for (auto entry : headers) { free(entry.key); free(entry.value); }
return true;
}
/* check if the transfer encoding is chunked */
static const string TRANSFER_ENCODING("transfer-encoding");
bool contains, chunked = false;
string& transfer_encoding = headers.get(TRANSFER_ENCODING, contains);
if (contains) {
for (unsigned int i = 0; i < transfer_encoding.length; i++)
transfer_encoding[i] = tolower(transfer_encoding[i]);
static const string CHUNKED("chunked");
if (transfer_encoding == CHUNKED)
chunked = true;
}
/* get the content length, if provided */
unsigned int content_length;
if (chunked) {
content_length = UINT_MAX;
} else if (status >= 100 && status < 200) {
/* TODO: also check if `status` is NO_CONTENT or NOT_MODIFIED, or the request was "HEAD" */
content_length = 0;
} else {
static const string CONTENT_LENGTH("content-length");
string& content_length_str = headers.get(CONTENT_LENGTH, contains);
if (contains) {
if (!parse_uint(content_length_str, content_length)) {
fprintf(stderr, "parse_http_response WARNING: Invalid content-length value.\n");
content_length = UINT_MAX;
}
} else {
content_length = UINT_MAX;
}
}
for (auto entry : headers) { free(entry.key); free(entry.value); }
/* read the payload */
if (chunked) {
unsigned int chunk_bytes_remaining = UINT_MAX;
while (true) {
if (chunk_bytes_remaining == 0) {
/* discard the CLRF at the end of the chunk */
fgetc(in); fgetc(in);
chunk_bytes_remaining = UINT_MAX;
} if (chunk_bytes_remaining == UINT_MAX) {
/* read the next chunk size */
array<char> line(64);
if (!read_line(in, line)) return false;
unsigned int index = line.index_of(';');
line.length = index;
if (!parse_uint(line, chunk_bytes_remaining, 16)) {
fprintf(stderr, "parse_http_response WARNING: Invalid chunk length.\n");
return false;
}
if (chunk_bytes_remaining == 0)
break;
}
/* read the chunk */
bool eof = false;
for (; chunk_bytes_remaining > 0; chunk_bytes_remaining--) {
int next = fgetc(in);
if (next == EOF) {
fprintf(stderr, "parse_http_response WARNING: Payload is smaller than chunk length.\n");
eof = true; break;
}
if (!payload.add(next)) return false;
}
if (eof) break;
}
} else {
for (unsigned int i = 0; i < content_length; i++) {
int next = fgetc(in);
if (next == EOF) {
fprintf(stderr, "parse_http_response WARNING: Payload is smaller than content-length.\n");
break;
}
if (!payload.add(next)) return false;
}
}
return true;
}
#if !defined(DISABLE_SSL)
struct ssl_context_provider {
SSL_CTX* ctx;
SSL_CONF_CTX* conf;
ssl_context_provider() {
ERR_load_crypto_strings();
SSL_load_error_strings();
conf = SSL_CONF_CTX_new();
SSL_CONF_CTX_set_flags(conf, SSL_CONF_FLAG_CLIENT);
ctx = SSL_CTX_new(TLS_client_method());
//SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY);
SSL_CONF_CTX_set_ssl_ctx(conf, ctx);
if (!SSL_CONF_CTX_finish(conf)) ERR_print_errors_fp(stderr);
SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION);
//SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, nullptr);
//if (SSL_CTX_set_default_verify_file(ctx) <= 0
// || SSL_CTX_set_default_verify_dir(ctx) <= 0)
// ERR_print_errors_fp(stderr);
//SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE);
}
~ssl_context_provider() {
SSL_CTX_free(ctx);
SSL_CONF_CTX_free(conf);
}
};
ssl_context_provider GLOBAL_SSL_PROVIDER;
void print_openssl_error(SSL* ssl, int ret, bool& can_shutdown)
{
char msg[1024];
can_shutdown = true;
switch (SSL_get_error(ssl, ret)) {
case SSL_ERROR_ZERO_RETURN: fprintf(stderr, "TLS/SSL peer has closed the connection.\n"); break;
case SSL_ERROR_WANT_READ: fprintf(stderr, "Read operation did not complete.\n"); break;
case SSL_ERROR_WANT_WRITE: fprintf(stderr, "Write operation did not complete.\n"); break;
case SSL_ERROR_WANT_CONNECT: fprintf(stderr, "Connect operation did not complete.\n"); break;
case SSL_ERROR_WANT_ACCEPT: fprintf(stderr, "Accept operation did not complete.\n"); break;
case SSL_ERROR_WANT_X509_LOOKUP: fprintf(stderr, "X509 lookup operation did not complete.\n"); break;
case SSL_ERROR_WANT_ASYNC: fprintf(stderr, "Asynchronous engine is still processing data.\n"); break;
case SSL_ERROR_WANT_ASYNC_JOB: fprintf(stderr, "No asynchronous jobs are available.\n"); break;
#if defined(SSL_ERROR_WANT_CLIENT_HELLO_CB)
case SSL_ERROR_WANT_CLIENT_HELLO_CB: fprintf(stderr, "Client callback operation did not complete.\n"); break;
#endif
case SSL_ERROR_SYSCALL: fprintf(stderr, "I/O error.\n"); can_shutdown = false; break;
case SSL_ERROR_SSL:
ERR_error_string_n(ERR_get_error(), msg, sizeof(msg));
fprintf(stderr, "%s %s %s %s.\n", msg, ERR_lib_error_string(0), ERR_func_error_string(0), ERR_reason_error_string(0));
can_shutdown = false; break;
default: fprintf(stderr, "Unknown error.\n"); break;
}
}
#endif /* DISABLE_SSL */
template<bool UseSSL, typename FilterResponseHeader>
bool get_http_page(
const char* hostname, const char* query, const char* port,
unsigned long long timeout_ms, array<char>& response,
FilterResponseHeader filter_response_header)
{
#if defined(DISABLE_SSL)
static_assert(!UseSSL, "SSL support is disabled");
#endif
static constexpr int MAX_REQUEST_LEN = 1024;
static char REQUEST_TEMPLATE[] =
"GET %s HTTP/1.1\r\n"
"Host: %s\r\n"
"Accept: text/html,application/xhtml+xml,text/plain,application/xml;q=0.9,*/*;q=0.8\r\n"
"Accept-Encoding: identity\r\n"
"User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36\r\n"
"Connection: keep-alive\r\n"
"DNT: 1\r\n\r\n";
int request_length = snprintf(NULL, 0, REQUEST_TEMPLATE, query, hostname);
if (request_length >= MAX_REQUEST_LEN) {
fprintf(stderr, "get_http_page ERROR: Request length is at least `MAX_REQUEST_LENGTH`.\n");
return false;
}
char* request = (char*) malloc(sizeof(char) * request_length + 1);
if (request == nullptr) {
fprintf(stderr, "get_http_page ERROR: Out of memory.\n");
return false;
}
snprintf(request, request_length + 1, REQUEST_TEMPLATE, query, hostname);
bool success = true;
#if defined(DISABLE_SSL)
auto process_connection = [&response,&success,request,request_length,filter_response_header,timeout_ms](socket_type& connection)
#else
auto process_connection = [&response,&success,request,request_length,filter_response_header,timeout_ms,hostname](socket_type& connection)
#endif
{
#if !defined(_WIN32)
/* make the underlying socket non-blocking */
int flags;
while ((flags = fcntl(connection.handle, F_GETFL)) == -1 && errno == EINTR) { }
if (flags == -1) {
fprintf(stderr, "get_http_page ERROR: Failed to make socket non-blocking; %s.\n", strerror(errno));
close(connection);
success = false; return false;
}
int rv;
while ((rv = fcntl(connection.handle, F_SETFL, flags | O_NONBLOCK)) == -1 && errno == EINTR) { }
if (rv != 0) {
fprintf(stderr, "get_http_page ERROR: Failed to make socket non-blocking; %s.\n", strerror(errno));
close(connection);
success = false; return false;
}
#else
/* make the underlying socket non-blocking */
u_long mode = 1;
if (ioctlsocket(connection.handle, FIONBIO, &mode) != NO_ERROR) {
errno = (int) GetLastError();
fprintf(stderr, "get_http_page ERROR: Failed to make socket non-blocking; %s.\n", strerror(errno));
close(connection);
success = false; return false;
}
#endif
#if !defined(DISABLE_SSL)
SSL* ssl;
if (UseSSL) {
ssl = SSL_new(GLOBAL_SSL_PROVIDER.ctx);
if (ssl == nullptr) {
fprintf(stderr, "get_http_page ERROR: SSL_new failed; ");
char msg[1024];
ERR_error_string_n(ERR_get_error(), msg, sizeof(msg));
fprintf(stderr, "%s %s %s %s.\n", msg, ERR_lib_error_string(0), ERR_func_error_string(0), ERR_reason_error_string(0));
close(connection);
success = false; return false;
}
if (!SSL_set_tlsext_host_name(ssl, hostname)) {
fprintf(stderr, "get_http_page ERROR: SSL_set_tlsext_host_name failed; ");
ERR_print_errors_fp(stderr);
SSL_free(ssl); close(connection);
success = false; return false;
}
int ret = SSL_set_fd(ssl, connection.handle);
if (ret != 1) {
fprintf(stderr, "get_http_page ERROR: SSL_set_fd failed; ");
bool can_shutdown;
print_openssl_error(ssl, ret, can_shutdown);
if (can_shutdown) SSL_shutdown(ssl);
SSL_free(ssl); close(connection);
success = false; return false;
}
while (true) {
ret = SSL_connect(ssl);
if (ret == 1)
break;
int error = SSL_get_error(ssl, ret);
if (error != SSL_ERROR_WANT_READ && error != SSL_ERROR_WANT_WRITE) {
fprintf(stderr, "get_http_page ERROR: SSL_connect failed; ");
bool can_shutdown;
print_openssl_error(ssl, ret, can_shutdown);
if (can_shutdown) SSL_shutdown(ssl);
SSL_free(ssl); close(connection);
success = false; return false;
}
}
}
#endif /* DISABLE_SSL */
/* send HTTP request */
unsigned int total_written = 0;
while (total_written < (unsigned int) request_length) {
int written;
#if !defined(DISABLE_SSL)
if (UseSSL) {
written = SSL_write(ssl, request + total_written, request_length - total_written);
} else
#endif
{
written = send(connection.handle, request + total_written, request_length - total_written, 0);
}
if (written == -1) {
fprintf(stderr, "get_http_page ERROR: Failed to send HTTP request.\n");
#if !defined(DISABLE_SSL)
if (UseSSL) { SSL_shutdown(ssl); SSL_free(ssl); }
#endif
close(connection); success = false; return false;
}
total_written += written;
}
/* read the response */