File: astma2-fact.yp

package info (click to toggle)
libtm-perl 1.20-2
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 672 kB
  • ctags: 139
  • sloc: perl: 3,707; makefile: 45
file content (906 lines) | stat: -rw-r--r-- 39,526 bytes parent folder | download
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
%{
use Data::Dumper;
use TM;
use TM::Literal;

use constant {
    XSD        => 'http://www.w3.org/2001/XMLSchema',
    XSD_STRING => 'http://www.w3.org/2001/XMLSchema#string',
    ASTMA      => 'http://psi.tm.bond.edu.au/astma/2.0/',
    ONTOLOGY   => 'http://psi.tm.bond.edu.au/astma/2.0/#ontology',
    TEMPLATE   => 'http://psi.tm.bond.edu.au/astma/2.0/#template'
    };

sub _expand_template {
    my $store  = shift;
    my $ted    = shift;
    my $params = shift; # they are all strings at this level

#warn "params".Dumper $params;

    my @returns = $store->match (TM->FORALL, type => 'tm:return', irole => 'tm:thing', iplayer => $store->mids ($ted) )
                  or die "template '$ted' does not have a 'return' characteristic";
#warn Dumper \@returns;
    my $return = $returns[0]->[TM->PLAYERS]->[1] and (scalar @returns == 1
                  or die "ambiguous 'return' characteristics for '$ted'");

    my $value  = $return->[0] and ($return->[1] eq 'http://www.w3.org/2001/XMLSchema#string' 
		  or die "'return' characteristic of '$ted' is no string");
#warn "template id '$ted' >>>$value<<<";
    foreach my $p (keys %$params) {
	$value =~ s/{\s*\$$p\s*}/$params->{$p}/sg;
    }
#warn "after template id '$ted' >>>$value<<<";
    die "variable '$1' in template '$ted' has no value at expansion" if $value =~ /{\s*(\$\w+)\s*}/;
    return $value;
}

%}

%token DUMMY

%token EOL
%token DOT
%token BRA
%token KET
%token URI
%token TILDE
%token EQUAL
%token COLON
%token NAME
%token OCC
%token VALUE
%token HAS
%token DOWNCOMMA
%token COMMA
%token WHICH
%token TED
%token REIFIES
%token ISREIFIED
%token LPAREN
%token RPAREN

%token SUBCL
%token ISA

%token LOG
%token CANCEL
%token VERSION
%token INCLUDE


%token COMMENT
%token WILDCARD
%token DATE

%token BN
%token OC
%token IN
%token SIN
%token STRING
%token ID
%token ISINDICATEDBY
%token LBRACKET
%token RBRACKET
%token AT

%%



instance            : # empty
                    | instance EOL
                    | instance clause
    ;

clause              :                                     { $_[0]->{USER}->{ctx} = undef; } 
                      theme DOT
                    | template_expansion
                    | directive
    ;

directive           : CANCEL                              { die "Cancelled"; }
                    | LOG                                 { warn $_[1]; 1; }              # write message to STDERR
                    | VERSION                             { die "unsupported version $_[1]" unless $_[1] =~ /^2\./; 1; }
                    | INCLUDE                             {
                                                            my $content;

                                                            if ($_[1] =~ /\|\s*$/) { # a pipe | at the end, this is a UNIX pipe
								my $fh = IO::File->new ($_[1]) || die "unable to open pipe '$_[1]'";
								local $/ = undef;
								$content = <$fh>;
								$fh->close;
							    } else {
								use LWP::Simple;
								$content = get($_[1]) || die "unable to load '$_[1] with LWP'\n";
							    }
#warn "new content >>>$content<<<";
                                                            $_[0]->YYData->{INPUT} = $content . $_[0]->YYData->{INPUT}; # prepend it
                                                            }
                    | ENCODING                            {
                                                            use Encode;
                                                            Encode::from_to ($_[0]->YYData->{INPUT}, "iso-8859-1", $_[1]);
                                                            }
    ;

template_expansion  : TED parameters                      { $_[0]->YYData->{INPUT} .= "\n" . 
                                                                                      _expand_template ($_[0]->{USER}->{store},
													$_[1],
													$_[2])      # compute the expanded version
                                                                                    . "\n";                         # extend the text at the end;
                                                           }
    ;

parameters          : # empty
                                                          { { } }
                    | LPAREN bindings RPAREN              { $_[2] }
    ;

bindings            : binding
                    | bindings COMMA binding              { $_[1] = { %{$_[1]}, %{$_[3]} }; $_[1]; }                # combine the hashes
    ;

binding             : ID COLON { $_[0]->{USER}->{value} = 1 } VALUE          { { "$_[1]" => $_[4]->[0] } }          # create a small hash (and use the string)
    ;

theme               : BRA topic KET
                    | topic
    ;

topic               : { unshift @{$_[0]->{USER}->{ctx}}, undef; }                      # push a (yet unknown) topic
                      attachments
                      association
    ;

association         : # empty
                    | REIFIES          { $_[0]->{USER}->{reifier} = $_[0]->{USER}->{ctx}->[0]; 
					                            $_[0]->{USER}->{ctx}->[0] = undef;
				       }
                      identification   { $_[0]->{USER}->{atype}   = $_[0]->{USER}->{ctx}->[0];
					 $_[0]->{USER}->{assoc}   = 1;                                 # indicate to lexer that we are in assoc context
				       }
                      scope
                      rolesin roles rolesout
                      {
#  warn "roles :". Dumper $_[7];
			  $_[0]->{USER}->{store}->assert ([ $_[0]->{USER}->{reifier},       # LID
							    $_[5],                          # SCOPE
							    $_[0]->{USER}->{atype},         # TYPE
							    TM->ASSOC,                      # KIND
							    @{$_[7]},  # ROLES, PLAYERS
							    undef ] );
                          $_[0]->{USER}->{implicits}->{'isa-scope'}->{$_[5]}++ if $_[5];
	                  $_[0]->{USER}->{assoc} = undef;                                 # indicate to lexer that we left assoc context
		      }
    ;

rolesin             : LPAREN | EOL
    ;
rolesout            : # empty
                    | RPAREN
                    | EOL
    ;
rolesep             : COMMA | EOL
    ;

roles               : role
                    | roles rolesep role         { 
                                                  push @{$_[1]->[0]}, @{$_[3]->[0]};
						  push @{$_[1]->[1]}, @{$_[3]->[1]};
						  $_[1];
					          }
    ;

role                : topic { $_[0]->{USER}->{role} = $_[0]->{USER}->{ctx}->[0] }
                      COLON {                         $_[0]->{USER}->{ctx}->[0] = undef } # clean out context
                      identifications          {
			                        [ [ ($_[0]->{USER}->{role}) x scalar @{$_[5]} ], $_[5] ]
						}
    ;

identifications     :                 identification { $_[0]->{USER}->{ctx}->[0] = undef }  # clean out context here
                                                     { [ $_[1] ] }
                    | identifications identification { $_[0]->{USER}->{ctx}->[0] = undef }
                                                     { push @{$_[1]}, $_[2]; $_[1]; }
    ;

attachments         : # empty
                    | attachments       HAS characteristic
                    | attachments WHICH HAS characteristic
                    | attachments           expansion
                    | attachments WHICH     expansion
                    | attachments           identification
                    | attachments EOL       identification
    ;

relative            : # empty
                    | DOWNCOMMA attachments upcomma
    ;

upcomma             : # empty
                    | COMMA
    ;

predefined_inlines  : ISA   { 'isa' }
                    | SUBCL { 'subclasses' }
                    | TED
    ;

expansion           : predefined_inlines parameters { unshift @{$_[0]->{USER}->{ctx}}, undef; } identification
                               {
#  warn " expand ctx ".Dumper $_[0]->{USER}->{ctx};
				my $left      = $_[0]->{USER}->{ctx}->[1];
				my $ted       = $_[1];
				my $right     = $_[0]->{USER}->{ctx}->[0];
				my $store     = $_[0]->{USER}->{store};
                                my $params    = $_[2];

#warn "left $left ted $ted right $right";

				if ($ted eq 'subclasses') {
				    $store->assert ([ undef,                          # LID
						      undef,                          # SCOPE
						      'is-subclass-of',               # TYPE
						      TM->ASSOC,                      # KIND
						      [ 'subclass',  'superclass' ],  # ROLES
						      [ $left,       $right ],        # PLAYERS
						      undef ] );
				} elsif ($ted eq 'isa') {
				    $store->assert ([ undef,                   	      # LID
						      undef,                   	      # SCOPE
						      'isa',                  	      # TYPE
						      TM->ASSOC,        	      # KIND
						      [ 'instance', 'class' ], 	      # ROLES
						      [ $left,       $right ],	      # PLAYERS
						      undef ] );
				} elsif ($ted eq 'hasa') {                            # same, but other way round
				    $store->assert ([ undef,                   	      # LID
						      undef,                   	      # SCOPE
						      'isa',               	      # TYPE
						      TM->ASSOC,        	      # KIND
						      [ 'instance', 'class' ], 	      # ROLES
						      [ $right,     $left ],	      # PLAYERS
						      undef ] );
				} else {
				    $_[0]->YYData->{INPUT} .= "\n" .
    					                      _expand_template ($store,
										$ted,
										{ %$params,
										  '_left' => $left,
										  '_right' => $right})      # compute the expanded version
                                                            . "\n";                                         # extend the text at the end;
				}
			    }

                       relative  { shift @{$_[0]->{USER}->{ctx}}; } # clean out context
    ;

identification      : tid      {
#    warn "tid: >>".$_[1]."<<";
                                 if (! defined $_[1]) {                                                     # wildcard
				     $_[0]->{USER}->{ctx}->[0] ||= $_[0]->{USER}->{store}->internalize (sprintf "uuid-%010d", $TM::toplet_ctr++);
				 } elsif (ref ($_[1])) {                                                    # reference means indicator
                                     $_[0]->{USER}->{ctx}->[0] = $_[0]->{USER}->{store}->internalize ($_[0]->{USER}->{ctx}->[0] => $_[1]);
				 } elsif ($_[1] =~ /^\w+:.+/) {                                             # URI means subject address
                                     $_[0]->{USER}->{ctx}->[0] = $_[0]->{USER}->{store}->internalize ($_[0]->{USER}->{ctx}->[0] => $_[1]);
				 } else {                                                                   # some lousy identifier
#   warn "checking for context ".Dumper $_[0]->{USER}->{ctx}->[0] ;
				     die "duplicate ID: $_[1] and $_[0]->{USER}->{ctx}->[0]"
					 if ($_[0]->{USER}->{ctx}->[0]);                                    # we already have an identifier!
				     $_[0]->{USER}->{ctx}->[0] = $_[0]->{USER}->{store}->internalize ($_[1]);
				 }
                                 $_[1] = $_[0]->{USER}->{ctx}->[0];                                     # whatever that was, that's it
			     }
;

characteristic      : tid scope type COLON { $_[0]->{USER}->{value} = 1 } VALUE
                            {
				my $ctype = $_[1];
				my $cclass;                                        # we do not yet know what this will be
				if ($_[3]) {                                       # there is a type specified
				    $cclass = $_[3];                               # take this to be the class of what ctype is
				} elsif ($_[1] =~ /.*name$/) {                     # looks like a name
				    if ($_[6]->[1] eq XSD_STRING) {                # but we check first what type the value is
					$cclass = 'name';                          # for a string we allow it to be a name
				    } else {
					$cclass = 'occurrence';                    # otherwise, we guess it is an occurrence
				    }
				} else {                                           # type does not end with 'name'
				    $cclass = 'occurrence';                        # this is then an occurrence
				}

				if ($cclass ne $ctype) { # a new instance was introduced
				    $store->assert ([ undef,                   	      # LID
						      undef,                   	      # SCOPE
						      'is-subclass-of',        	      # TYPE
						      TM->ASSOC,        	      # KIND
						      [ 'subclass', 'superclass' ],   # ROLES
						      [ $ctype,      $cclass ],	      # PLAYERS
						      undef ] );
				}
#  warn "char $_[1] ctx ".Dumper $_[0]->{USER}->{ctx};
				$_[0]->{USER}->{store}->assert (                                                  #
								[
								 undef,                                           # LID
								 $_[2],                                           # SCOPE (undef is ok)
								 $_[1],                                           # TYPE

								 $cclass eq 'name'       ? TM->NAME
                                                                 :
                                                                ($cclass eq 'occurrence' ? TM->OCC
                                                                                         : TM->ASSOC),            # KIND
								 [ 'thing', 'value' ],                            # ROLES
								 [ $_[0]->{USER}->{ctx}->[0],     $_[6] ],        # PLAYERS
								 undef
								 ]
								);
			    }
    ;

scope               : # empty
                    | AT tid { $_[2]; }
    ;

type                : # empty
                    | SUBCL tid { $_[2] }
    ;


ctype               : NAME
                    | OCC
    ;

tid                 : ID                           {   $_[1]; }
                    | WILDCARD                     {   undef; }       # make sure we have an ID
                    | DATE                         { \ $_[1]; }
                    | EQUAL URI                    {   $_[2]; }
                    | TILDE URI                    { \ $_[2]; }
                    | URI                          {
                                                     my $baseuri = $_[0]->{USER}->{store}->baseuri;
                                                     $_[1] =~ /^$baseuri(.+)/ ? $1 : \ $_[1];
                                                     }
   ;


#-------------------------------------------

xinstance           : # empty
                    | instance EOL
                    | instance theme
    ;

xxxtopic              : identification involvements
    ;

xinvolvements       : # empty
                   | involvements involvement
    ;

involvement        : identification
                   | AND attachment
                   | attachment
                   | LRELATIVE relative RRELATIVE
    ;

xattachment         : statement
    ;

statement          : ISA topic
    ;






xxtopic              : tid 
                     {
			 warn "involve ".Dumper $_[2];
			 1;
		      }
;

tids               : tid                          { [ $_[1] ] } # singleton
                   | tids tid                     { push @{$_[1]}, $_[2]; $_[1] }
;

involvements       :                                                               { [] } #empty
                   | involvements inlined_expansion                                { push @{$_[1]}, $_[2]; $_[1] }
;

inlined_expansion  : LPAREN tids RPAREN                                            { $_[2] }
;

#types                      :                                         { [] } # empty
#                           | types type                              { push @{$_[1]}, @{$_[2]}; $_[1] }
#;
#
#type                       : ISA ID                                  { [ $_[2] ] }
#                           | LPAREN ids RPAREN                       {   $_[2]   }
#;





xtopic            : ID types reification_indication inline_assocs EOL
                    {
			$_[1] = $_[0]->{USER}->{store}->internalize ($_[1]);

			if (ref $_[3]) {                                                   # we have reification info
			    if (     $_[3]->[0] == 1) {                                    # 1 = REIFIES, means current ID is a shorthand for the other
				$_[0]->{USER}->{store}->internalize ($_[1] => $_[3]->[1]); 
			    } elsif ($_[3]->[0] == 0) {                                    # 0 = IS-REIFIED, this must be the other way round
				$_[0]->{USER}->{store}->internalize ($_[3]->[1] => $_[1]);
			    } elsif ($_[3]->[0] == 2) {                                    # 2 = ISINDICATEDBY, add the subject indicators
				$_[0]->{USER}->{store}->internalize ($_[1] => \ $_[3]->[1]);
			    } else {
				die "internal fu**up";
			    }
			}
			# assert instance/class
                        if (@{$_[2]}) {
			    $_[0]->{USER}->{store}->assert ( map {
							  [ undef, 
							    undef, 
							    'isa', 
							    undef,
							    [ 'class', 'instance' ], 
                                                            [ $_, $_[1] ], 
							    ]}  
							     @{$_[2]} );
			}
			{                                                                  # memorize that the types should be a 'topic' at the end (see end of parse)
			    my $implicits = $_[0]->{USER}->{implicits};
#			    my $s         = $_[0]->{USER}->{store};
			    map { $implicits->{'isa-thing'}->{$_}++ } 
			             (@{$_[2]}, $_[1]);                                    # the types and the ID are declared implicitely
			}
			
			if (ref $_[4]) {                                                   # there are inline assocs
#warn "test for inlines";
			    foreach (@{$_[4]}) {
				my $type      = $_->[0];
				my $player    = $_->[1];
				my $store     = $_[0]->{USER}->{store};
				my $templates = $_[0]->{USER}->{templates};
#warn "found type $type $player";
				if ($type eq 'is-subclass-of' || $type eq 'subclasses') {
				    $store->assert ([ undef,                          # LID
						      undef,                          # SCOPE
						      'is-subclass-of',               # TYPE
						      TM->ASSOC,                      # KIND
						      [ 'subclass',  'superclass' ],  # ROLES
						      [ $_[1],       $player ],       # PLAYERS
						      undef ] );
				} elsif ($type eq 'is-a') {
				    $store->assert ([ undef,                   	      # LID
						      undef,                   	      # SCOPE
						      'isa',                  	      # TYPE
						      TM->ASSOC,        	      # KIND
						      [ 'instance', 'class' ], 	      # ROLES
						      [ $_[1],       $player ],	      # PLAYERS
						      undef ] );
				} elsif ($type eq 'has-a') {                          # same, but other way round
				    $store->assert ([ undef,                   	      # LID
						      undef,                   	      # SCOPE
						      'isa',               	      # TYPE
						      TM->ASSOC,        	      # KIND
						      [ 'instance', 'class' ], 	      # ROLES
						      [ $player,     $_[1] ],	      # PLAYERS
						      undef ] );
				} elsif ($templates->mids ( $type ) &&
					 (my @ts    = $templates->match (TM->FORALL, type => $templates->mids ( $type )  ))) {
#warn "found templates for $type";
				    warn "duplicate template for '$type' found, taking one" if @ts > 1;
				    my $t = $ts[0];                                   # I choose one

#warn "YYY cloning ($type)";

				    $store->assert ([ undef,                   	      # LID
						      undef,                   	      # SCOPE
						      $type,               	      # TYPE
						      TM->ASSOC,        	      # KIND
						      [  	                      # ROLES
							map {
							    my $l = $templates->reified_by ($_);
							    ($l && $l eq LEFT ?
							           $_[1]
							     :
							           ($l && $l eq RIGHT ?
                                                                          $player
                                                                    :
								          $_)
							     )
							    } @{$t->[TM->ROLES]} 
						      ],
						      [                       	      # PLAYERS
							map {
							    my $l = $templates->reified_by ($_);
							    ($l && $l eq LEFT ?
							           $_[1]
							     :
							           ($l && $l eq RIGHT ?
                                                                          $player
                                                                    :
								          $_)
							     )
							    } @{$t->[TM->PLAYERS]} 
						      ],
						      undef ] );
				} else {
				    die "unknown association type '$type' in inlined association";
				}
			    }
			}
		    }
                       characteristics_indication
                        {
#warn "char/ind in topic: ".Dumper $_[7];
                         my $id = $_[1];
                         # add assertions for every characteristic
                         $_[0]->{USER}->{store}->assert ( map {[ undef,                                         # LID
                                                                 $_->[1],                                       # SCOPE
                                                                 $_->[2] || $TM::CharInfo[$_->[0]]->[0],        # TYPE
                                                                 $_->[0],                                       # KIND
                                                                 [ 'thing', $TM::CharInfo[$_->[0]]->[1] ],      # ROLES
                                                                 [ $id,             $_->[3] ],                  # PLAYERS
                                                                 undef ] }
                                                               @{$_[7]->[0]} );

                         map { $store->internalize ($id => $_ ) } @{$_[7]->[1]};         # add the subject indicators

			 {                                                               # memorize basename types and scopes as implicitely defined
			     my $implicits = $_[0]->{USER}->{implicits};
			     map { $implicits->{'isa-scope'}->{$_}++ }
                                   map { $_->[1] } grep ($_->[1], @{$_[7]->[0]});        # get the bloody scopes and tuck them away

			     map { $implicits->{'subclasses'}->{ $TM::CharInfo[$_->[0]]->[0] }->{$_->[2]}++ }
                                   grep ($_->[2], @{$_[7]->[0]});                        # get all the characteristics with types

#warn "implicits then ".Dumper $implicits;
			 }
		         }
;

reification_indication     : # empty
                           | REIFIES       ID                        { [ 1, $_[2] ] }            # 0, 1, 2 are just local encoding, nothing relevant 
                           | ISREIFIED     ID                        { [ 0, $_[2] ] }
                           | ISINDICATEDBY ID                        { [ 2, $_[2] ] }
;

types                      :                                         { [] } # empty
                           | types type                              { push @{$_[1]}, @{$_[2]}; $_[1] }
;

xtype                       : ISA ID                                  { [ $_[2] ] }
                           | LPAREN ids RPAREN                       {   $_[2]   }
;

characteristics_indication : # empty
                           | characteristics_indication  characteristic_indication
                                                                     { push @{$_[1]->[ ref($_[2]) eq 'ARRAY' ? 0 : 1 ]}, $_[2]; $_[1] }
;                                                                    # do not tell me this is not cryptic, it fast, though
                                                                     # if we get a characteristic back, then it is a list ref, then we add it to $_[1]->[0]
                                                                     # if we get a subject indication back, then it is a scalar, so we add it to $_[1]->[1]
xcharacteristic_indication  : characteristic
                           | indication
;

indication                 : SIN           { $_[0]->{USER}->{string} ||= "\n" } string            { $_[3] }        # TODO: replace with ID?
;


class                      : BN                                      { TM->KIND_BN  }
                           | OC                                      { TM->KIND_OC  }
                           | IN                                      { TM->KIND_IN  }
;

char_type                  : # empty
                           | assoc_type
;

assoc_type                 : LPAREN ID RPAREN                        {   $_[2]   }
;


inline_assocs              : # empty
                           | inline_assocs inline_assoc              { push @{$_[1]}, $_[2]; $_[1] }
;

inline_assoc               : ID ID                                   { [ $_[1], $_[2] ] }
;

template_definition        : LBRACKET 
                                      { ($_[0]->{USER}->{templates}, $_[0]->{USER}->{store}) = ($_[0]->{USER}->{store}, $_[0]->{USER}->{templates}); }
                                                                         # flag that we are inside a template
                             association_definition
                                      { ($_[0]->{USER}->{templates}, $_[0]->{USER}->{store}) = ($_[0]->{USER}->{store}, $_[0]->{USER}->{templates}); }
                             #RBRACKET                                   # consumed by members already
;

association_definition     : LPAREN ID RPAREN scope reification_indication EOL
                             association_members
                             {
##warn "members ".Dumper $_[5];
## ??? TODO SCOPE ????
			       my (@roles, @players);
			       foreach my $m (@{$_[7]}) {                 # one member
				   my $role = shift @$m;                  # first is role
				   
				   while (@$m) {
				       push @roles, $role;                # roles repeat for every player
				       my $player = shift @$m;
				       push @players, $player;
				   }
			       }
			       my ($a) = $_[0]->{USER}->{store}->assert ( [ undef, $_[4], $_[2], TM->ASSOC, \@roles, \@players, undef ] );
##warn "templates" .Dumper $_[0]->{USER}->{store};
                              { # reification
				  my $ms = $_[0]->{USER}->{store};
				  if (ref $_[5]) {
				      if ($_[5]->[0] == 1) {                   # 1 = REIFIES, 0 = IS-REIFIED
					  # (assoc) reifies http://.... means
					  #     1) the assoc will be addes as thing (is done already)
					  #     2) the http:// will be used as one subject indicator
					  die "reifier of association must be a URI" unless $_[5]->[1] =~ /^\w+:.+/;
					  $ms->internalize ($a->[TM::LID], $_[5]->[1]);
				      } elsif ($_[5]->[0] == 0) {              # something reifies this assoc
					  # (assoc) is-reified-by xxx   means
					  #     1) assoc is added as thing (is done already)
					  #     2) the local identifier is added as thing with the abs URL of the assoc as subject address
					  die "reifier must be local identifier" unless $_[5]->[1] =~ /^\w+$/;
					  $ms->internalize ($_[5]->[1] => $a->[TM::LID]);
				      } else { # this would be 'indication' but we do not want that here
					  die "indication for association are undefined";
				      }
				  }
			      }

			       { # memorize that association type subclasses association
#				   my $implicits = $_[0]->{USER}->{implicits};

# implicit			   $implicits->{'subclasses'}->{'association'}->{$_[2]}++;
				   $_[0]->{USER}->{implicits}->{'isa-scope'}->{$_[4]}++ if $_[4];
			       }
			   }
;

association_members        : member                           {                       [ $_[1] ] }
                           | association_members member       { push @{$_[1]}, $_[2];   $_[1]  }
;

member                     : ID COLON ids1 eom                { [ $_[1], @{$_[3]} ] }
;

eom                        : EOL                              # normal assoc
                           | RBRACKET EOL                     # in case we are inside a template
;

ids1                       : ids ID                           { push @{$_[1]}, $_[2]; $_[1] }
;

ids                        :                                  { [] } # empty
                           | ids ID                           { push @{$_[1]}, $_[2]; $_[1] }
;

string                     : STRING EOL { die "empty string in characteristics" unless $_[1]; \$_[1] }
;

%%

sub _Error {
    die "Syntax error: Found ".$_[0]->YYCurtok." but expected ".join (' or ', $_[0]->YYExpect);
}

sub _Lexer {
    my $parser = shift;
    my $refINPUT = \$parser->YYData->{INPUT};

#    study $$refINPUT;

    $$refINPUT                                        or  return ('',              undef);  # this is the end of the world, as we know it
    $$refINPUT =~ s/^[ \t]+//o;

#warn "lexer ($parser->{USER}->{string}):>>>".$parser->YYData->{INPUT};

    $$refINPUT =~ s/^\n\n//so                         and return ('DOT',       	   undef);
    $$refINPUT =~ s/^\n$//so                          and return ('DOT',       	   undef);
    $$refINPUT =~ s/^\.//so                           and return ('DOT',       	   undef);
    $$refINPUT =~ s/^\~//so                           and return ('TILDE',     	   undef);
    $$refINPUT =~ s/^=//o                             and return ('EQUAL',   	   undef);
    $$refINPUT =~ s/^://o                             and return ('COLON',         undef);
    $$refINPUT =~ s/^,\s*(which|who)\b//o             and return ('DOWNCOMMA',     undef);
    $$refINPUT =~ s/^,(?!\s*(which|who)\b)//o         and return ('COMMA',         undef);

    $$refINPUT =~ s/^is-?a\b//o                       and return ('ISA',       	   undef);
#    $$refINPUT =~ s/^has-?a\b//o                      and return ('TED',       	   'hasa');
    $$refINPUT =~ s/^subclasses\b//o                  and return ('SUBCL',     	   undef);

    $$refINPUT =~ s/^has\b//o                         and return ('HAS',       	   undef);

    unless ($parser->{USER}->{assoc}) {                                                    # in topic context this corresponds to HAS
	$$refINPUT =~ s/^\n\s*(?=\w+\s*[:<@]\s)//so   and return ('HAS',           undef); # positive look-ahead for things like <CR>bn :<blank>
    }

    $$refINPUT =~ s/^(which|who)\b//o                 and return ('WHICH',         undef);
    $$refINPUT =~ s/^and(\s+(which|who))?\b//so       and return ('WHICH',         undef); # (can go over lines)


    $$refINPUT =~ s/^\n//so                           and return ('EOL',       	   undef);

    $$refINPUT =~ s/^{//so                            and return ('BRA',     	   undef);
    $$refINPUT =~ s/^}//so                            and return ('KET',     	   undef);
    $$refINPUT =~ s/^\(//so                           and return ('LPAREN',        undef);
    $$refINPUT =~ s/^\)//so                           and return ('RPAREN',        undef);

    $$refINPUT =~ s/^<<//o                            and return ('REIFIES',   	   undef);
    $$refINPUT =~ s/^<//o                             and return ('SUBCL',   	   undef);

    $$refINPUT =~ s/^>>//o                            and return ('ISREIFIED', 	   undef);


    $$refINPUT =~ s/^\*//o                            and return ('WILDCARD',      undef);

    $$refINPUT =~ s/^(\d{4}-\d{1,2}-\d{1,2})(T(\d{1,2}):(\d{2}))?//o
                                                      and return ('DATE',          sprintf "urn:x-date:%s:%02d:%02d", $1, $3 || 0, $4 || 0); # is a date

    $$refINPUT =~ s/^bn\b//o                          and return ('ID',      	   "name");
    $$refINPUT =~ s/^oc\b//o                          and return ('ID',       	   "occurrence");
    $$refINPUT =~ s/^in\b//o                          and return ('ID',       	   "occurrence");

    if ($parser->{USER}->{value}) {  # parser said we should expect a value now
##warn "expect value >>".$$refINPUT."<<";
	$$refINPUT =~ s/^\"{3}(.*?)\"{3}(?=\n)//so    and
#            (warn "returning multi $1" or 1) and
	    (undef $parser->{USER}->{value}           or  return ('VALUE',         new TM::Literal ($1)));
	$$refINPUT =~ s/^\"(.*?)\"(^^(\S+))?//o       and
#            (warn "returning simlg $1" or 1) and
	    (undef $parser->{USER}->{value}           or  return ('VALUE',         new TM::Literal ($1, $3)));
	$$refINPUT =~ s/^(\d+\.\d+)//o                and
#            (warn "returning float $1" or 1) and
	    (undef $parser->{USER}->{value}           or  return ('VALUE',         new TM::Literal  ($1, 'xsd:decimal')));
	$$refINPUT =~ s/^(\d+)//o                     and
#            (warn "returning int $1" or 1) and
	    (undef $parser->{USER}->{value}           or  return ('VALUE',         new TM::Literal  ($1, 'xsd:integer')));
	$$refINPUT =~ s/^(\w+:\S+)//o                 and
#            (warn "returning uri $1" or 1) and
	    (undef $parser->{USER}->{value}           or  return ('VALUE',         new TM::Literal  ($1, 'xsd:uri')));
	$$refINPUT =~ s/^(.+?)(?=\s*\n)//o            and
#            (warn "returning unquo $1" or 1) and
	    (undef $parser->{USER}->{value}           or  return ('VALUE',         new TM::Literal  ($1)));

##            (warn "returning $1" or 1) and
##	    (undef $parser->{USER}->{value}           or  return ('VALUE',         new TM::Literal ($1)));
##warn "no string";
    }

## unfortunately, this does not what I want:
##  $$refINPUT =~ s/^([A-Za-z][A-Za-z0-9_-]*)(?!:)//o and return ('ID',        $1); # negative look-ahead
## tricky optimization: don't ask
    my $aux;                                                                        # need this to store identifier/uri prefix temporarily (optimization)
    my $aux2;                                                                       # need this to store ontology URL, if there is one
    $$refINPUT =~ s/^([A-Za-z][A-Za-z0-9_-]*)//o      and $aux = $1                 # save this for later
	                                              and $$refINPUT !~ /^:[\w\/]/
                                                      and return (_is_template ($parser->{USER}->{store},
										$aux) 
                                                               ? 'TED' : 'ID', $aux);

    $$refINPUT =~ s/^(:([^\s\)\(\]\[]+))//o           and return ('URI',       ( $aux2 = _is_ontology ($parser->{USER}->{store},
												       $parser->{USER}->{prefixes},
												       $aux)) ? $aux2."#$2" : $aux.$1); # is a URL/URN actually

    $$refINPUT =~ s/^@//so                            and return ('AT',        undef);


    $$refINPUT =~ s/^%include\s+(.*?)(?=\n)//so       and return ('INCLUDE',   $1); # positive look-ahead
    $$refINPUT =~ s/^%log\s+(.*?)(?=\n)//so           and return ('LOG',       $1); # positive look-ahead
    $$refINPUT =~ s/^%cancel(?=\n)//so                and return ('CANCEL',    $1); # positive look-ahead
    $$refINPUT =~ s/^%version\s+(\d+\.\d+)(?=\n)//so  and return ('VERSION',   $1); # positive look-ahead

    $$refINPUT =~ s/^%encoding\s+(.*?)(?=\n)//so      and return ('ENCODING',  $1); # positive look-ahead


#    $$refINPUT =~ s/^\[//so                           and return ('LBRACKET',  undef);
#    $$refINPUT =~ s/^\]//so                           and return ('RBRACKET',  undef);

    $$refINPUT =~ s/^(.)//so                          and return ($1,          $1); # should not be an issue except on error
}

sub _is_template {
    my $store = shift;
    my $id    = shift;

    my $t = $store->mids ($id) or return undef;
    return $store->is_a ($t, $store->mids (\ TEMPLATE));
}

sub _is_ontology {
    my $store    = shift;
    my $prefixes = shift;
    my $prefix   = shift;

#warn "texting prefix '$prefix' on ".Dumper $prefixes;
    return $prefixes->{$prefix} if $prefixes->{$prefix};                                  # cache

    if ($prefix eq 'astma') {                                                             # this is one predefined prefix
	$prefixes->{$prefix} = ASTMA;
    } elsif ($prefix eq 'xsd') {                                                          # this is the other predefined prefix
	$prefixes->{$prefix} = XSD;
    } else {
	my $p = $store->mids ($prefix);
	if ($p && $store->is_a ($p, $store->mids (\ ONTOLOGY))) {                         # is the topic an instance of astma:ontology?
	    $prefixes->{$prefix} = $store->midlet ($prefix)->[TM->INDICATORS]->[0]        # then take its subject indicator as expanded URI
		or die "no subject indicator for '$prefix' provided";                     # if there is none, complain
	}
    }
#warn "prefixes now".Dumper $prefixes;
    return $prefixes->{$prefix};
}

sub parse {
    my $self               = shift;
    $self->YYData->{INPUT} = shift;

#warn "parse";

    $self->YYData->{INPUT} =~ s/\r/\n/sg;
    $self->YYData->{INPUT} =~ s/(?<!\\)\\\n//sg;   # a \, but not a \\
    $self->YYData->{INPUT} =~ s/ \+{3} /\n/g;      # replace _+++_ with \n
    $self->YYData->{INPUT} =~ s/\+{4}/+++/g;       # stuffed ++++ cleanout
    $self->YYData->{INPUT} =~ s/^\#.*?\n/\n/mg;    # # at there start of every line -> gone
    $self->YYData->{INPUT} =~ s/\s+\#.*?\n/\n/mg;  # anything which starts with <blank>#, all blanks are ignored
    $self->YYData->{INPUT} =~ s/\n\n\n+/\n\n/sg;
    $self->YYData->{INPUT} =~ s/\n\s+\n+/\n\n/sg;  # trimm lines with blanks only

    # we not only capture what is said EXPLICITELY in the map, we also collect implicit knowledge
    # we could add this immediately into the map at parsing, but it would slow the process down and
    # it would probably duplicate/complicate things
    $self->{USER}->{implicits} = {
	'isa-thing'  => undef,                                          # just let them spring into existence
	'isa-scope'  => undef,                                          # just let them spring into existence
	'subclasses' => undef
	};
#    $self->{USER}->{topic_count} = 0;

#   $self->{USER}->{templates} = new TM (psis => undef, baseuri => $self->{USER}->{store}->baseuri);
    $self->{USER}->{prefixes}  = {};

    eval {
	$self->YYParse ( yylex => \&_Lexer, yyerror => \&_Error); #, yydebug => 0x01 );
    }; if ($@ =~ /^Cancelled/) {
	warn $@;                                                         # de-escalate Cancelling to warning
    } elsif ($@) {
	die $@;                                                          # otherwise re-raise the exception
    }
#warn "in parse end";
#warn "in parse end ".Dumper $self->{USER}->{implicits};

    { # resolving implicit stuff
	my $implicits = $self->{USER}->{implicits};
	my $store     = $self->{USER}->{store};

	{ # all super/subclasses
	    foreach my $superclass (keys %{$implicits->{'subclasses'}}) {
		$store->assert ( map {
		    [ undef, undef, 'is-subclass-of', TM->ASSOC, [ 'superclass', 'subclass' ], [ $superclass, $_ ] ] 
		    }  keys %{$implicits->{'subclasses'}->{$superclass}});
	    }
#warn "done with subclasses";
	}
	{ # all things in isa-things are THINGS, simply add them
##warn "isa things ".Dumper [keys %{$implicits->{'isa-thing'}}];
	    $store->internalize (map { $_ => undef } keys %{$implicits->{'isa-thing'}});
	}
	{ # establishing the scoping topics
	    $store->assert (map {
                                 [ undef, undef, 'isa', TM->ASSOC, [ 'class', 'instance' ], [ 'scope', $_ ] ] 
				 } keys %{$implicits->{'isa-scope'}});
	}
        $store->externalize ( $store->instances ($store->mids (\ TEMPLATE)) );                  # "removing templates now";
    }
    return $self->{USER}->{store};
}

#my $f = new TM::AsTMa::Fact;
#$f->Run;