-
Notifications
You must be signed in to change notification settings - Fork 65
/
Dash.w
3573 lines (3114 loc) · 146 KB
/
Dash.w
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
[Dash::] Dash.
The part of Inform most nearly like a typechecker in a conventional compiler.
@ Dash is the second typechecking algorithm to be used in Inform, installed in
early 2015: the first had served since 2003, but became unwieldy after so many
exceptional cases had been added to it, and was impossible to adapt to the
redesigned parse tree. Dash is not so called because it's faster (it's
actually a few percent slower), but because at one stage Inform was running
both typecheckers side by side: TC and TC-dash, or Dash for short. TC-dash
won, it's still called Dash, and TC is no more.
Because Dash also deals with text which entirely fails to make sense, which in
other compilers would be rejected at a lower level, it has to issue basic
syntax errors as well as type mismatch errors. This is arguably a good thing,
though, because it means they can be issued using the same generally helpful
system as more sophisticated problems.
Partly because of the need to do this, the type-checker has a top-down
approach. It aims to prove that the node found can match what's expected,
making selections from alternative readings, and in limited cases actually
making changes to the parse tree, in order to do this. For instance,
consider checking the tree for:
>> let the score be the score plus 10
Dash takes the view that the phrase usage can be proved correct, so long as
the arguments can also be proved. There are several valid interpretations of
"let ... be ...", and these are all present in the parse tree as alternative
interpretations, so the typechecker tries each in turn, accepting one (or
more) if the arguments can be proved to be of the right type. This means
proving that argument 0 ("the score") is an lvalue and also that argument 1
("the score plus 10") is an rvalue. A further rule requires that the kind of
value of argument 1 must match the kind of value stored in the variable, here
a "number", so we must prove that too. Now "plus" is polymorphic and can
produce different kinds of value depending on the kinds of value it acts upon,
so again we must check all possible interpretations. But we finally succeed in
showing that "score" is an lvalue, "10" is a number, "score" is also a number,
and that "plus" on two numbers gives a number, so we complete the proof and
the phrase is proved correct.
@ When issuing problems, we show a form of backtrace so that the user can
see what we've considered, and this is used to accumulate data for that.
=
typedef struct inv_token_problem_token {
struct wording problematic_text;
struct parse_node *as_parsed;
int already_described;
int new_name; /* found in context of a name not yet defined */
CLASS_DEFINITION
} inv_token_problem_token;
@h The Dashboard.
Dash uses a small suite of global variables to keep track of two decidedly
global side-effects of checking: the issuing of problem messages, and the
setting of kind variables. This suite is called the "dashboard".
First, we keep track of the problem messages we will issue, if any, using
a bitmap made up of the following modes:
@d BEGIN_DASH_MODE int s_dm = dash_mode;
kind **s_kvc = kind_of_var_to_create;
parse_node *s_invl = Dash_ambiguity_list;
@d DASH_MODE_ENTER(mode) dash_mode |= mode;
@d DASH_MODE_CREATE(K) kind_of_var_to_create = K;
@d DASH_MODE_EXIT(mode) dash_mode &= (~mode);
@d END_DASH_MODE dash_mode = s_dm;
kind_of_var_to_create = s_kvc;
Dash_ambiguity_list = s_invl;
@d TEST_DASH_MODE(mode) (dash_mode & mode)
@d ISSUE_PROBLEMS_DMODE 0x00000001 /* rather than keep silent about them */
@d ISSUE_LOCAL_PROBLEMS_DMODE 0x00000002 /* at the end, that is */
@d ISSUE_GROSS_PROBLEMS_DMODE 0x00000004 /* at the end, that is */
@d ISSUE_INTERESTING_PROBLEMS_DMODE 0x00000008 /* unless casting to text */
@d ABSOLUTE_SILENCE_DMODE 0x00000010 /* say nothing at all */
=
int dash_mode = ISSUE_PROBLEMS_DMODE; /* default */
kind **kind_of_var_to_create = NULL;
int dash_recursion_count = 0;
@ Three grades of problem can appear: "ordinary", "gross" and "grosser than
gross". We distinguish these in order to produce a Problem message which
reflects the biggest thing wrong, rather than being so esoteric that it misses
the main point. Changing a particular error condition from an ordinary to a
gross problem, or vice versa, has no effect on the result returned by Dash,
only on the Problem messages given to the user.
@d THIS_IS_A_GROSSER_THAN_GROSS_PROBLEM
no_gross_problems_thrown++; /* problems this gross cannot be suppressed */
@d THIS_IS_A_GROSS_PROBLEM
no_gross_problems_thrown++; /* this increments even if the message is suppressed */
if ((TEST_DASH_MODE(ISSUE_PROBLEMS_DMODE) == FALSE) &&
(TEST_DASH_MODE(ISSUE_GROSS_PROBLEMS_DMODE) == FALSE)) return NEVER_MATCH;
@d THIS_IS_AN_ORDINARY_PROBLEM
if (TEST_DASH_MODE(ISSUE_PROBLEMS_DMODE) == FALSE) return NEVER_MATCH;
=
int no_gross_problems_thrown = 0;
int no_interesting_problems_thrown = 0;
int initial_problem_count = 0;
int backtraced_problem_count = 0;
int Dash::problems_have_been_issued(void) {
if (initial_problem_count < problem_count) return TRUE;
return FALSE;
}
@ Next, we keep track of the most recent set of meanings attached to the
kind variables A, B, C, ..., Z, and the most recently looked-at list of
invocations.
=
kind_variable_declaration *most_recent_interpretation = NULL;
parse_node *Dash_ambiguity_list = NULL;
@ We need careful debug logging of what Dash does. During Inform's infancy, the
type checker was the hardest thing to debug, but that wasn't so much because
this was the great habitat and breeding ground for bugs; it was more that those
bugs which were here were by far the hardest to root out. So careful logging
on demand is vital.
Each call to the recursive Dash has its own unique ID number, to make logging
more legible.
@d LOG_DASH_LEFT
LOGIF(MATCHING, "[%d%s] ",
unique_DR_call_identifier,
(TEST_DASH_MODE(ISSUE_PROBLEMS_DMODE))?"":"-silent");
@d LOG_DASH(stage)
LOGIF(MATCHING, "[%d%s] %s $P\n",
unique_DR_call_identifier,
(TEST_DASH_MODE(ISSUE_PROBLEMS_DMODE))?"":"-silent", stage, p);
=
int unique_DR_call_identifier = 0, DR_call_counter = 0; /* solely to make the log more legible */
@h Return values.
Dash records the outcome of checking as one of three states.
It is perhaps telling that we never need a |Dash::best_case| routine.
Typecheckers are not allowed to be optimistic.
=
int Dash::worst_case(int rv1, int rv2) {
if ((rv1 == NEVER_MATCH) || (rv2 == NEVER_MATCH)) return NEVER_MATCH;
if ((rv1 == SOMETIMES_MATCH) || (rv2 == SOMETIMES_MATCH)) return SOMETIMES_MATCH;
return ALWAYS_MATCH;
}
@h (1) Entering Dash.
Dash is structured into levels and this is level 1, the topmost.
Dash has three points of entry: to check a condition, check a value, or check
an invocation list for a phrase used in a routine.
These top-level routines do not look recursive, but in fact some can be,
because Dash needs to call the predicate calculus engine to typecheck
propositions: and these in turn call Dash to check that constant values
are used correctly.
All of these funnel downwards into level 2:
=
int Dash::check_condition(parse_node *p) {
parse_node *cn = Node::new(CONDITION_CONTEXT_NT);
cn->down = p;
LOGIF(MATCHING, "Dash (1): condition\n");
return Dash::funnel_to_level_2(cn, FALSE);
}
int Dash::check_value(parse_node *p, kind *K) {
parse_node *vn = Node::new(RVALUE_CONTEXT_NT);
if (K) Node::set_kind_required_by_context(vn, K);
vn->down = p;
if (K) LOGIF(MATCHING, "Dash (1): value of kind %u\n", K);
if (K == NULL) LOGIF(MATCHING, "Dash (1): value\n");
return Dash::funnel_to_level_2(vn, FALSE);
}
int Dash::check_value_silently(parse_node *p, kind *K) {
parse_node *vn = Node::new(RVALUE_CONTEXT_NT);
if (K) Node::set_kind_required_by_context(vn, K);
vn->down = p;
if (K) LOGIF(MATCHING, "Dash (1): value of kind %u\n", K);
if (K == NULL) LOGIF(MATCHING, "Dash (1): value\n");
return Dash::funnel_to_level_2(vn, TRUE);
}
int Dash::check_invl(parse_node *p) {
LOGIF(MATCHING, "Dash (1): invocation list '%W'\n", Node::get_text(p));
return Dash::funnel_to_level_2(p, FALSE);
}
int Dash::funnel_to_level_2(parse_node *p, int silently) {
no_gross_problems_thrown = 0;
dash_recursion_count = 0;
BEGIN_DASH_MODE;
if (!silently) DASH_MODE_ENTER(ISSUE_PROBLEMS_DMODE);
initial_problem_count = problem_count;
DASH_MODE_CREATE(NULL);
Latticework::show_frame_variables();
int rv = Dash::typecheck_recursive(p, NULL, TRUE);
END_DASH_MODE;
return rv;
}
@h (2) Recursion point.
Loosely speaking, Dash works by visiting every node in the parse tree being
examined with the following routine, which is therefore recursive as Dash
heads ever downward.
The routine itself is really just an outer shell, though, and has two
functions: it keeps the debugging log tidy (see above) and it produces
the backtrace if the inner routine should throw a problem message.
The recursion limit below is clearly arbitrary, but is there to prevent the
algorithm from slowing Inform unacceptably in the event of something like
>> say g + g + g + g + g + g + g + g + g + g + g + g + g + g + g + g + g + g + g + g + g + g + g;
where "g" is a term Inform doesn't recognise, because otherwise this will
recurse through every possible interpretation of the plus sign (i.e. every
possible order of operations).
@d MAX_DASH_RECURSION 10000
=
int Dash::typecheck_recursive(parse_node *p, parse_node *context, int consider_alternatives) {
if (p == NULL) internal_error("Dash on null node");
if (dash_recursion_count >= MAX_DASH_RECURSION) return NEVER_MATCH;
dash_recursion_count++;
int outer_id = unique_DR_call_identifier;
int problem_count_before = problem_count;
unique_DR_call_identifier = DR_call_counter++;
LOG_INDENT;
LOG_DASH("(2)");
int return_value = Dash::typecheck_recursive_inner(p, context, consider_alternatives);
switch(return_value) {
case ALWAYS_MATCH: LOG_DASH_LEFT; LOGIF(MATCHING, "== always\n"); break;
case SOMETIMES_MATCH: LOG_DASH_LEFT; LOGIF(MATCHING, "== sometimes\n"); break;
case NEVER_MATCH: LOG_DASH_LEFT; LOGIF(MATCHING, "== never\n"); break;
default: internal_error("impossible verdict from Dash");
}
LOG_OUTDENT;
if ((problem_count > problem_count_before) && (consider_alternatives))
@<Consider adding a backtrace of what the type-checker was up to@>;
unique_DR_call_identifier = outer_id;
return return_value;
}
@ The backtrace is added to problem messages only if we have just been checking
a phrase, and if it produced problems not previously seen. The trick here is
to ensure that if we have
>> let X be a random wibble bibble spong;
then it will be the "random ..." phrase which is backtraced, and not the
"let ..." phrase, even though that also goes wrong in turn.
@<Consider adding a backtrace of what the type-checker was up to@> =
if (problem_count > backtraced_problem_count) {
if ((p) && (p->down) &&
(Node::get_type(p) == INVOCATION_LIST_NT)) {
TextSubstitutions::it_is_not_worth_adding();
@<Backtrace what phrase definitions the type-checker was looking at@>;
TextSubstitutions::it_is_worth_adding();
backtraced_problem_count = problem_count;
}
}
@ We skip proven invocations, and those never needed because of them, since
those aren't in dispute; and we also skip groups not even reached, since they
aren't where the problem lies. (This can happen when checking a compound "say",
from a text substitution.)
@<Backtrace what phrase definitions the type-checker was looking at@> =
parse_node *inv;
LOOP_THROUGH_ALTERNATIVES(inv, p->down) LOG("$e\n", inv);
int to_show = 0;
LOOP_THROUGH_ALTERNATIVES(inv, p->down) {
id_body *idb = Node::get_phrase_invoked(inv);
if (IDTypeData::is_a_spare_say_X_phrase(&(idb->type_data))) continue;
to_show++;
}
int announce = TRUE;
text_stream *latest = Problems::latest_sigil();
if (Str::eq_wide_string(latest, L"PM_AllInvsFailed")) announce = FALSE;
if (announce) @<Produce the I was trying... banner@>;
@<Produce the list of possibilities@>;
int real_found = FALSE;
@<Produce the tokens which were recognisable as something@>;
@<Produce the tokens which weren't recognisable as something@>;
@<Produce the tokens which were intentionally not recognisable as something@>;
if (real_found) @<Produce a note about real versus integer@>;
@<Produce the I was trying... banner@> =
Problems::issue_problem_begin(Task::syntax_tree(), "*");
if (to_show > 1)
Problems::issue_problem_segment("I was trying to match one of these phrases:");
else
Problems::issue_problem_segment("I was trying to match this phrase:");
Problems::issue_problem_end();
@<Produce the list of possibilities@> =
int shown = 0;
LOOP_THROUGH_ALTERNATIVES(inv, p->down) {
id_body *idb = Node::get_phrase_invoked(inv);
if (IDTypeData::is_a_spare_say_X_phrase(&(idb->type_data))) continue;
shown++;
Problems::quote_number(1, &shown);
Problems::quote_invocation(2, inv);
if (announce == FALSE) {
Problems::issue_problem_begin(Task::syntax_tree(), "***");
announce = TRUE;
} else {
Problems::issue_problem_begin(Task::syntax_tree(), "****");
}
if (to_show > 1) Problems::issue_problem_segment("%1. %2");
else Problems::issue_problem_segment("%2");
Problems::issue_problem_end();
}
@<Produce the tokens which were recognisable as something@> =
int any = FALSE;
inv_token_problem_token *itpt;
LOOP_OVER(itpt, inv_token_problem_token)
if (Node::is(itpt->as_parsed, UNKNOWN_NT) == FALSE)
if (itpt->already_described == FALSE) {
itpt->already_described = TRUE;
if (any == FALSE) {
any = TRUE;
Problems::issue_problem_begin(Task::syntax_tree(), "*");
Problems::issue_problem_segment("I recognised:");
Problems::issue_problem_end();
}
@<Produce this token@>;
}
@<Produce this token@> =
Problems::quote_wording_tinted_green(1, itpt->problematic_text);
Problems::quote_spec(2, itpt->as_parsed);
Problems::issue_problem_begin(Task::syntax_tree(), "****");
if (Specifications::is_value(itpt->as_parsed)) {
kind *K = Specifications::to_kind(itpt->as_parsed);
int changed = FALSE;
K = Kinds::substitute(K, NULL, &changed, FALSE);
Problems::quote_kind(3, K);
if (Kinds::eq(K, K_real_number)) real_found = TRUE;
if (Lvalues::is_lvalue(itpt->as_parsed))
@<Produce the token for an lvalue@>
else if (Node::is(itpt->as_parsed, PHRASE_TO_DECIDE_VALUE_NT))
@<Produce the token for a phrase deciding a value@>
else
@<Produce the token for a constant rvalue@>;
} else Problems::issue_problem_segment("%1 = <i>%2</i>");
Problems::issue_problem_end();
@<Produce the token for an lvalue@> =
Problems::issue_problem_segment("%1 = <i>%2</i>, holding <i>%3</i>");
@<Produce the token for a phrase deciding a value@> =
char *seg = "%1 = an instruction to work out <i>%3</i>";
if (K == NULL) seg = "%1 = a phrase";
parse_node *found_invl = itpt->as_parsed->down;
parse_node *inv;
LOOP_THROUGH_ALTERNATIVES(inv, found_invl) {
LOG("$e\n", inv);
if (Dash::reading_passed(inv) == FALSE) {
seg = "%1 = an instruction I think should work out <i>%3</i>, "
"but which I can't make sense of";
for (int i=0; i<Invocations::get_no_tokens(inv); i++) {
parse_node *tok = Invocations::get_token_as_parsed(inv, i);
if (Node::is(tok, UNKNOWN_NT)) {
Problems::quote_wording(4, Node::get_text(tok));
seg = "%1 = an instruction I think should work out <i>%3</i>, "
"but which I can't perform because '%4' doesn't make sense here";
break;
}
}
}
}
Problems::issue_problem_segment(seg);
@<Produce the token for a constant rvalue@> =
char *seg = "%1 = <i>%3</i>";
if (Rvalues::is_CONSTANT_construction(itpt->as_parsed, CON_property)) {
property *prn = Node::get_constant_property(itpt->as_parsed);
if (Properties::is_value_property(prn)) {
binary_predicate *bp = ValueProperties::get_stored_relation(prn);
if (bp) {
seg = "%1 = <i>%3</i>, which is used to store %4, "
"but is not the same thing as the relation itself";
Problems::quote_relation(4, bp);
}
}
}
Problems::issue_problem_segment(seg);
@<Produce the tokens which were intentionally not recognisable as something@> =
int unknowns = 0;
inv_token_problem_token *itpt;
LOOP_OVER(itpt, inv_token_problem_token)
if ((Node::is(itpt->as_parsed, UNKNOWN_NT)) && (itpt->new_name))
if (itpt->already_described == FALSE) {
itpt->already_described = TRUE;
if (unknowns < 5) {
Problems::quote_wording_tinted_red(++unknowns,
itpt->problematic_text);
}
}
if (unknowns > 0) {
Problems::issue_problem_begin(Task::syntax_tree(), "*");
char *chunk = "";
switch (unknowns) {
case 1: chunk = "The name '%1' doesn't yet exist."; break;
case 2: chunk = "The names '%1' and '%2' don't yet exist."; break;
case 3: chunk = "The names '%1', '%2' and '%3' don't yet exist."; break;
case 4: chunk = "The names '%1', '%2', '%3' and '%4' don't yet exist."; break;
default: chunk = "The names '%1', '%2', '%3', '%4', and so on, don't yet exist."; break;
}
Problems::issue_problem_segment(chunk);
Problems::issue_problem_end();
}
@<Produce the tokens which weren't recognisable as something@> =
int unknowns = 0;
inv_token_problem_token *itpt;
LOOP_OVER(itpt, inv_token_problem_token)
if ((Node::is(itpt->as_parsed, UNKNOWN_NT)) &&
(itpt->new_name == FALSE))
if (itpt->already_described == FALSE) {
itpt->already_described = TRUE;
if (unknowns < 5) {
Problems::quote_wording_tinted_red(++unknowns,
itpt->problematic_text);
}
}
if (unknowns > 0) {
Problems::issue_problem_begin(Task::syntax_tree(), "*");
char *chunk = "";
switch (unknowns) {
case 1: chunk = "But I didn't recognise '%1'."; break;
case 2: chunk = "But I didn't recognise '%1' or '%2'."; break;
case 3: chunk = "But I didn't recognise '%1', '%2' or '%3'."; break;
case 4: chunk = "But I didn't recognise '%1', '%2', '%3' or '%4'."; break;
default: chunk = "But I didn't recognise '%1', '%2', '%3', '%4' and so on."; break;
}
Problems::issue_problem_segment(chunk);
Problems::issue_problem_end();
}
@<Produce a note about real versus integer@> =
Problems::issue_problem_begin(Task::syntax_tree(), "*");
Problems::issue_problem_segment(
" %PNote that Inform's kinds 'number' and 'real number' are not "
"interchangeable. A 'number' like 7 can be used where a 'real "
"number' is expected - it becomes 7.000 - but not vice versa. "
"Use 'R to the nearest whole number' if you want to make a "
"conversion.");
Problems::issue_problem_end();
@h (3) Context switching.
After those epic preliminaries, we finally do some typechecking.
The scheme here is that our expectations of |p| depend on the context, and
this is defined by some node higher in the current subtree than |p|, which
we will call |context|. Most of the time this is the parent of |p|, but
sometimes the grandparent or great-grandparent; and at the start of the
recursion, when no context has appeared yet, it will be null. In effect,
then, the tree we're checking contains its own instructions on how it
should be checked. For example, the subtree
= (text)
CONDITION_CONTEXT_NT
p
=
tells us that when we reach |p| it should be checked as a condition.
=
int Dash::typecheck_recursive_inner(parse_node *p, parse_node *context, int consider_alternatives) {
LOG_DASH("(3)");
switch (p->node_type) {
case CONDITION_CONTEXT_NT: @<Switch context@>;
case RVALUE_CONTEXT_NT: @<Switch context@>;
case MATCHING_RVALUE_CONTEXT_NT: @<Switch context to an rvalue matching a description@>;
case SPECIFIC_RVALUE_CONTEXT_NT: @<Switch context to an rvalue matching a value@>;
case VOID_CONTEXT_NT: @<Switch to a void context@>;
case LVALUE_CONTEXT_NT: @<Switch context to an lvalue@>;
case LVALUE_TR_CONTEXT_NT: @<Switch context to a table reference lvalue@>;
case LVALUE_LOCAL_CONTEXT_NT: @<Switch context to an existing local variable lvalue@>;
case NEW_LOCAL_CONTEXT_NT: @<Deal with a new local variable name@>;
default: @<Typecheck within current context@>;
}
return NEVER_MATCH; /* to prevent compiler warnings: unreachable in fact */
}
@ When we find a node like |CONDITION_CONTEXT_NT|, that becomes the new context
and we move down to its only child.
@d SWITCH_CONTEXT_AND_RECURSE(p) Dash::typecheck_recursive(p->down, p, TRUE)
@<Switch context@> =
return SWITCH_CONTEXT_AND_RECURSE(p);
@ Other context switches are essentially the same thing, plus a check that
the value meets some extra requirement. For example:
@<Switch context to an lvalue@> =
int rv = SWITCH_CONTEXT_AND_RECURSE(p);
if (Lvalues::is_lvalue(p->down) == FALSE)
@<Issue problem for not being an lvalue@>;
return rv;
@ More specifically:
@<Switch context to a table reference lvalue@> =
int rv = SWITCH_CONTEXT_AND_RECURSE(p);
if (Node::is(p->down, TABLE_ENTRY_NT) == FALSE)
@<Issue problem for not being a table reference@>;
return rv;
@<Switch context to an existing local variable lvalue@> =
int rv = SWITCH_CONTEXT_AND_RECURSE(p);
if (Node::is(p->down, LOCAL_VARIABLE_NT) == FALSE)
@<Issue problem for not being an existing local@>;
return rv;
@ Suppose we are matching the parameter of a phrase like this:
>> To inspect (D - an open door): ...
and typechecking the following invocation:
>> inspect the Marble Portal;
Then we would have |p| set to some value -- here "the Marble Portal" --
and the |MATCHING_RVALUE_CONTEXT_NT| node would point to a description node
for open doors. We must see if |p| matches that. Any match can be at best at
the "sometimes" level. We can prove the Marble Portal is a door at compile
time, but we can't prove it's open until run-time.
Note that we switch context and recurse first, then make the supplementary
check afterwards, when we know the kinds at least must be right.
@<Switch context to an rvalue matching a description@> =
int rv = SWITCH_CONTEXT_AND_RECURSE(p);
if (rv != NEVER_MATCH)
rv = Dash::worst_case(rv,
Dash::compatible_with_description(p->down,
Node::get_token_to_be_parsed_against(p)));
return rv;
@ This is something else that wouldn't appear in a typical typechecker.
Here we are dealing with a phrase specification such as:
>> To attract (N - 10) things: ...
where the "N" argument will be accepted if and only if it's the value 10.
The fact that Inform allows this is further evidence of the slippery way
that natural language doesn't distinguish values from types; early designs
of Inform didn't allow it, but many people reported this as a bug.
Again we switch context and recurse first. We can't safely test pointer
values, such as texts, for equality at compile time -- for one thing, we
don't know what text substitutions will then expand to -- so the value
test only forces us towards never or always when the constants being
compared are word values.
@<Switch context to an rvalue matching a value@> =
int rv = SWITCH_CONTEXT_AND_RECURSE(p);
if (rv != NEVER_MATCH) {
kind *K = Specifications::to_kind(p->down);
if ((Kinds::Behaviour::uses_block_values(K) == FALSE) &&
(Node::is(p->down, CONSTANT_NT))) {
parse_node *val = Node::get_token_to_be_parsed_against(p);
if (!(Rvalues::compare_CONSTANT(p->down, val)))
@<Issue problem for being the wrong rvalue@>;
} else {
rv = Dash::worst_case(rv, SOMETIMES_MATCH);
LOGIF(MATCHING, "dropping to sometimes level for value comparison\n");
}
}
return rv;
@ I would ideally like to remove void contexts from Dash entirely, but was
forced to retain them by the popularity of the Hypothetical Questions
extension, which made use of the old undocumented |phrase| token.
@<Switch to a void context@> =
int rv = SWITCH_CONTEXT_AND_RECURSE(p);
if (rv != NEVER_MATCH) {
if (!(Node::is(p->down, PHRASE_TO_DECIDE_VALUE_NT))) {
@<Issue problem for not being a phrase@>;
}
}
return rv;
@ A whole set of problem messages arise out of contextual failures:
@<Issue problem for not being an lvalue@> =
THIS_IS_AN_ORDINARY_PROBLEM;
Problems::quote_source(1, current_sentence);
Problems::quote_wording(2, Node::get_text(p->down));
StandardProblems::handmade_problem(Task::syntax_tree(), _p_(PM_ValueAsStorageItem));
Problems::issue_problem_segment(
"You wrote %1, but '%2' is a value, not a place where a value is "
"stored. "
"%PFor example, if 'The tally is a number that varies.', then "
"I can 'increment the tally', but I can't 'increment 37' - the "
"number 37 is always what it is. Similarly, I can't 'increment "
"the number of people'. Phrases like 'increment' work only on "
"stored values, like values that vary, or table entries.");
Problems::issue_problem_end();
return NEVER_MATCH;
@<Issue problem for not being a table reference@> =
THIS_IS_AN_ORDINARY_PROBLEM;
Problems::quote_source(1, current_sentence);
Problems::quote_wording(2, Node::get_text(p->down));
StandardProblems::handmade_problem(Task::syntax_tree(), _p_(PM_ValueAsTableReference));
Problems::issue_problem_segment(
"You wrote %1, but '%2' is a value, not a reference to an entry "
"in a table.");
Problems::issue_problem_end();
return NEVER_MATCH;
@<Issue problem for not being an existing local@> =
if (TEST_DASH_MODE(ISSUE_LOCAL_PROBLEMS_DMODE)) {
THIS_IS_AN_ORDINARY_PROBLEM;
Problems::quote_source(1, current_sentence);
Problems::quote_wording(2, Node::get_text(p));
if (Specifications::is_kind_like(p->down))
Problems::quote_text(3, "a kind of value");
else
Problems::quote_kind_of(3, p->down);
StandardProblems::handmade_problem(Task::syntax_tree(), _p_(PM_ExistingVarNotFound));
Problems::issue_problem_segment(
"In the sentence %1, I was expecting that '%2' would be the "
"name of a temporary value, but it turned out to be %3.");
Problems::issue_problem_end();
}
return NEVER_MATCH;
@<Issue problem for being the wrong rvalue@> =
THIS_IS_AN_ORDINARY_PROBLEM;
Problems::quote_source(1, current_sentence);
Problems::quote_wording(2, Node::get_text(p->down));
Problems::quote_spec(3, p->down);
Problems::quote_spec(4, val);
StandardProblems::handmade_problem(Task::syntax_tree(), _p_(PM_NotExactValueWanted));
Problems::issue_problem_segment(
"In the sentence %1, I was expecting that '%2' would be the specific "
"value '%4'.");
Problems::issue_problem_end();
return NEVER_MATCH;
@<Issue problem for not being a phrase@> =
THIS_IS_AN_ORDINARY_PROBLEM;
Problems::quote_source(1, current_sentence);
Problems::quote_wording(2, Node::get_text(p->down));
StandardProblems::handmade_problem(Task::syntax_tree(), _p_(...));
Problems::issue_problem_segment(
"In the sentence %1, I was expecting that '%2' would be a phrase.");
Problems::issue_problem_end();
return NEVER_MATCH;
@h New variables.
The following doesn't switch context and recurse down: there's nothing
to recurse down to, since all we have is a name for a new variable. Instead
we deal with that right away.
It might seem rather odd that the typechecker should be the part of Inform
which creates local variables. Surely that's a sign that the parsing went
wrong, so how did things get to this stage?
In a C-like language, where variables are predeclared, that would be true.
But in Inform, a phrase like:
>> let the monster be a random pterodactyl;
can be valid even where "the monster" is text not known to the S-parser
as yet -- indeed, that's how local variables are made. It's the typechecker
which sorts this out, because only the typechecker can decide which of the
subtly different forms of "let" is being used.
@<Deal with a new local variable name@> =
kind *K = Node::get_kind_required_by_context(p);
parse_node *check = p->down;
if (Node::is(check, AMBIGUITY_NT)) check = check->down;
if (LocalVariables::permit_as_new_local(check, FALSE)) {
if (kind_of_var_to_create) *kind_of_var_to_create = K;
return ALWAYS_MATCH;
}
@<Issue a problem for an inappropriate variable name@>;
return NEVER_MATCH;
@ This problem message is never normally seen using the definitions in the
Standard Rules because the definitions made there are such that other
problems appear first. So the only way to see this message is to declare an
unambiguous phrase with one of its tokens requiring a variable of a
species; and then to misuse that phrase.
@<Issue a problem for an inappropriate variable name@> =
THIS_IS_AN_ORDINARY_PROBLEM;
Problems::quote_source(1, current_sentence);
Problems::quote_wording(2, Node::get_text(p));
if (Specifications::is_kind_like(p->down))
Problems::quote_text(3, "a kind of value");
else
Problems::quote_kind_of(3, p->down);
Problems::quote_kind(4, K);
StandardProblems::handmade_problem(Task::syntax_tree(), _p_(PM_KindOfVariable));
Problems::issue_problem_segment(
"In the sentence %1, I was expecting that '%2' would be a new "
"variable name (to hold %4), but it turned out to be %3.");
Problems::issue_problem_end();
@h (4) Typechecking within current context.
Everything else, then, passes through here, with the context now set either
to |NULL| (meaning no expectations) or to some ancestor of |p| in the parse
tree.
Level 4 forks rapidly into three branches: (4A), for ambiguous readings;
(4I), for single invocations; and (4S), for single readings other than
invocations. Here's the code which does the switching:
@<Typecheck within current context@> =
kind *kind_needed = NULL;
int condition_context = FALSE;
if (context) {
kind_needed = Node::get_kind_required_by_context(context);
if ((Node::is(context, CONDITION_CONTEXT_NT)) ||
(Node::is(context, LOGICAL_AND_NT)) ||
(Node::is(context, LOGICAL_OR_NT)) ||
(Node::is(context, LOGICAL_NOT_NT)) ||
(Node::is(context, LOGICAL_TENSE_NT)))
condition_context = TRUE;
}
LOG_DASH("(4)");
int outcome = ALWAYS_MATCH;
if ((consider_alternatives) && (p->next_alternative))
@<Resolve an ambiguous reading@>
else
@<Verify an unambiguous reading@>;
return outcome;
@ For a phrase node, we pass the buck down to its invocation list. For an
invocation list, we pass the buck down to its invocation (which may or
may not be the first in a chain of alternatives), which means we end up
in (4I) either directly or via (4A). For everything else, it's (4S) for us.
@<Verify an unambiguous reading@> =
switch (p->node_type) {
case PHRASE_TO_DECIDE_VALUE_NT:
outcome = Dash::typecheck_recursive(p->down, context, TRUE);
break;
case INVOCATION_LIST_NT: case INVOCATION_LIST_SAY_NT: case AMBIGUITY_NT:
if (p->down == NULL) @<Unknown found text occurs as a command@>;
BEGIN_DASH_MODE;
Dash_ambiguity_list = p;
outcome = Dash::typecheck_recursive(p->down, context, TRUE);
END_DASH_MODE;
break;
case INVOCATION_NT: @<Step (4I) Verify an invocation@>; break;
default: @<Step (4S) Verify anything else@>; break;
}
@ (4A) Ambiguities.
Ambiguities presently consist of chains of invocation nodes listed in
the tree as alternatives.
@<Resolve an ambiguous reading@> =
LOG_DASH("(4A)");
parse_node *list_of_possible_readings[MAX_INVOCATIONS_PER_PHRASE];
int no_of_possible_readings = 0;
int no_of_passed_readings = 0;
@<Step (4A.a) Set up the list of readings to test@>;
@<Step (4A.b) Recurse Dash to try each reading in turn@>;
if (Dash::problems_have_been_issued()) return NEVER_MATCH;
if (no_of_passed_readings > 0) @<Step (4A.c) Preserve successful readings@>
else @<Step (4A.d) Give up with no readings possible@>;
LOGIF(MATCHING, "Ambiguity resolved to: $E", p);
@ Phrase definitions are kept in a linked list with a total ordering which
properly contains the partial ordering in which $P_1\leq P_2$ if they are
lexically identical and if each parameter of $P_1$ provably, at compile time,
also satisfies the requirements for the corresponding parameter of $P_2$.
They have already been lexically parsed in that order, so the list of
invocations (which will have accumulated during parsing) is also in that
same order. Now this is nearly the correct order for type-checking. But we
make one last adjustment: the phrase being compiled is moved to the back of
the list. This is to make recursion always the last thing checked, so that
later rules can override earlier ones but still make use of them.
@<Step (4A.a) Set up the list of readings to test@> =
LOG_DASH("(4A.a)");
parse_node *alt;
LOOP_THROUGH_ALTERNATIVES(alt, p)
if ((Node::is(alt, INVOCATION_NT)) &&
(Node::get_phrase_invoked(alt) != Functions::defn_being_compiled()))
@<Add this reading to the list of test cases@>;
LOOP_THROUGH_ALTERNATIVES(alt, p)
if (!((Node::is(alt, INVOCATION_NT)) &&
(Node::get_phrase_invoked(alt) != Functions::defn_being_compiled())))
@<Add this reading to the list of test cases@>;
LOGIF(MATCHING, "Resolving %d possible readings:\n", no_of_possible_readings);
for (int i=0; i<no_of_possible_readings; i++)
LOGIF(MATCHING, "Possibility (P%d) $e\n", i, list_of_possible_readings[i]);
@ In general, it's not great for typecheckers in compilers to put an upper bound
on complexity, because although human-written code seldom hits such maxima, there's
always the possibility of mechanically-generated code which does. On the other hand,
the result of that doctrine is that a lot of modern compilers (Swift, for example)
slow to a painful crawl and allocate gigabytes of memory trying to understand
strange type constraints in two or three lines of code. So, for now at least,
let's be pragmatic.
@<Add this reading to the list of test cases@> =
if (no_of_possible_readings >= MAX_INVOCATIONS_PER_PHRASE) {
THIS_IS_AN_ORDINARY_PROBLEM;
Problems::quote_wording(1, Node::get_text(p));
StandardProblems::handmade_problem(Task::syntax_tree(), _p_(PM_AmbiguitiesTooDeep));
Problems::issue_problem_segment(
"The phrase %1 is too complicated for me to disentangle without "
"running very, very slowly as I check many ambiguities in it. There "
"ought to be some way to simplify things for me?");
Problems::issue_problem_end();
return NEVER_MATCH;
}
list_of_possible_readings[no_of_possible_readings++] = alt;
Dash::clear_flags(alt);
@ Now we work through the list of tests. We must produce at least one reading
passing at least at the "sometimes" level marked by the |UNPROVEN_DASHFLAG|, or
else the whole specification fails its match. The first proven match stops our
work, since we can never need lower-priority interpretations.
@<Step (4A.b) Recurse Dash to try each reading in turn@> =
LOG_DASH("(4A.b)");
for (int ref = 0; ref<no_of_possible_readings; ref++) {
parse_node *inv = list_of_possible_readings[ref];
@<Test the current reading and set its results flags accordingly@>;
LOGIF(MATCHING, "(P%d) %s: $e\n", ref, Dash::verdict_to_text(inv), inv);
if (Dash::test_flag(inv, PASSED_DASHFLAG)) {
no_of_passed_readings++;
if (Dash::test_flag(inv, UNPROVEN_DASHFLAG) == FALSE) break;
}
if (Dash::problems_have_been_issued()) break; /* to prevent duplication of problem messages */
}
LOGIF(MATCHING, "List %s: ", (no_of_passed_readings > 0)?"passed":"failed");
for (int i=0; i<no_of_possible_readings; i++) {
parse_node *inv = list_of_possible_readings[i];
LOGIF(MATCHING, "%s ", Dash::quick_verdict_to_text(inv));
}
LOGIF(MATCHING, "|\n");
@ We tell Dash to run silently unless grosser-than-gross problems arise, and
also tell it to check the reading with no alternatives considered. (If we
let it consider alternatives, that would be circular: we'd end up here
again, and so on forever.)
@<Test the current reading and set its results flags accordingly@> =
LOGIF(MATCHING, "(P%d) Trying <%W>: $e\n", ref, Node::get_text(inv), inv);
BEGIN_DASH_MODE;
DASH_MODE_EXIT(ISSUE_PROBLEMS_DMODE);
int rv = Dash::typecheck_recursive(inv, context, FALSE);
END_DASH_MODE;
Dash::set_flag(inv, TESTED_DASHFLAG);
if (rv != NEVER_MATCH) {
Dash::set_flag(inv, PASSED_DASHFLAG);
outcome = Dash::worst_case(outcome, rv);
}
@ This is the happy ending, in which the list can probably be passed, though
there are still a handful of pitfalls.
@<Step (4A.c) Preserve successful readings@> =
LOG_DASH("(4A.c)");
@<Step (4A.c.1) Winnow the reading list down to the survivors@>;
@<Step (4A.c.2) Infer the kind of any requested local variable@>;
@ To recap, after checking through the possible readings we have something
like this as the result:
= (text)
f ? f g ? ? p - - -
=
We can now throw away the |f|, |g| and |-| readings -- failed, grossly failed,
or never reached -- to leave just those which will be compiled:
= (text)
? ? ? p
=
If compiled this will result in run-time code to check if the arguments
allow the first invocation and run it if so; then the second; then the third;
and, if those three fell through, run the fourth invocation without further
checking.
@<Step (4A.c.1) Winnow the reading list down to the survivors@> =
LOG_DASH("(4A.c.1)");
int invocational = TRUE;
if (Node::is(Dash_ambiguity_list, AMBIGUITY_NT)) invocational = FALSE;
LOGIF(MATCHING, "Winnow %s from $T\n",
(invocational)?"invocationally":"regularly", Dash_ambiguity_list);
if (invocational) Dash_ambiguity_list->down = NULL;
parse_node *last_survivor = NULL;
for (int ref = 0; ref<no_of_possible_readings; ref++) {
parse_node *inv = list_of_possible_readings[ref];
inv->next_alternative = NULL;
if (Dash::test_flag(inv, PASSED_DASHFLAG)) {
if (invocational) {
if (last_survivor) last_survivor->next_alternative = inv;
else Dash_ambiguity_list->down = inv;
last_survivor = inv;
} else {
parse_node *link = Dash_ambiguity_list->next;
Node::copy(Dash_ambiguity_list, inv);
Dash_ambiguity_list->next = link;
Dash_ambiguity_list->next_alternative = NULL;
break;
}
}
}
if (invocational) {
p = Dash_ambiguity_list->down;
int nfi = -1, number_ambiguity = FALSE;
parse_node *inv;
LOOP_THROUGH_ALTERNATIVES(inv, p)
if (Node::is(inv, INVOCATION_NT)) {
int nti = Invocations::get_no_tokens(inv);
if (nfi == -1) nfi = nti;
else if (nfi != nti) number_ambiguity = TRUE;
}
if (number_ambiguity) @<Issue the number ambiguity problem message@>;
}
LOGIF(MATCHING, "After winnowing, CS is $T\n", current_sentence);
@ This is another sort of error which couldn't happen with a conventional
programming language -- in C, for instance, it's syntactically obvious
how many arguments a function call has, because the brackets and commas
are unambiguous. But in Inform, there are no reserved tokens of syntax
acting like that. So we could easily have two accepted invocations in the
list which have different numbers of arguments to each other, and there's
no way safely to adjudicate that at run-time.
@<Issue the number ambiguity problem message@> =
THIS_IS_AN_ORDINARY_PROBLEM;
Problems::quote_source(1, current_sentence);
StandardProblems::handmade_problem(Task::syntax_tree(), _p_(PM_UnequalValueAmbiguity));
Problems::issue_problem_segment(
"The phrase %1 is ambiguous in a way that I can't disentangle. "
"It has more than one plausible interpretation, such that it "
"would only be possible to tell which is valid at run-time: "
"ordinarily that would be fine, but because the different "
"interpretations are so different (and involve different "
"numbers of values being used) there's no good way to cope. "
"Try rewording one of the phrases which caused this clash: "
"there's a good chance the problem will then go away.");
Problems::issue_problem_end();
return NEVER_MATCH;
@ If an invocation passes, and asks to create a local variable, we need
to mark the tree accordingly. If there's just one invocation then (4I)
handles this, but if there's ambiguity, we handle it here, and only
for the surviving nodes.
@<Step (4A.c.2) Infer the kind of any requested local variable@> =
LOG_DASH("(4A.c.2)");
parse_node *inv;
LOOP_THROUGH_ALTERNATIVES(inv, p)
if (Node::is(inv, INVOCATION_NT))