summaryrefslogtreecommitdiff
path: root/sample/rbc.rb
blob: 7ab0edba12faa75ada4eec3c3aeabdcfebd065e8 (plain)
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
#!/usr/local/bin/ruby
#
#   rbc.rb - 
#   	$Release Version: 0.6 $
#   	$Revision: 1.2 $
#   	$Date: 1997/11/27 13:46:06 $
#   	by Keiju ISHITSUKA(Nippon Rational Inc.)
#
# --
# Usage:
#
#   rbc.rb [options] file_name opts
#   options:
#	-d		    debug mode(not encouraged)
#	-m		    bc mode(calculate rational, matrix)
#	-r load-module	    same as `ruby -r'
#	--inspect	    use inspect for output.
#                           (default except in bc mode)
#	--noinspect	    do not use inspect for output.
#	--noreadline	    do not use readline library.
#                           (rbc tries to use readline as default).
#
# additional private methods:
#   exit, quit		    quit
#   inspect(sw = nil)	    toggle inspect mode
#   trace_load(sw = nil)    toggle trace mode for load/require.
#			    (default is trace mode on)
#
require "e2mmap.rb"

$stdout.sync = TRUE

module BC_APPLICATION__

  RCS_ID=%q$Id: rbc.rb,v 1.2 1997/11/27 13:46:06 keiju Exp keiju $

  extend Exception2MessageMapper
  def_exception :UnrecognizedSwitch, "Unrecognized switch: %s"
  
  $DEBUG = FALSE
  $INSPECT = nil
  
  CONFIG = {}
  CONFIG[0] = $0
  CONFIG[:USE_READLINE] = TRUE
  CONFIG[:LOAD_MODULES] = []
  CONFIG[:INSPECT] = nil
  CONFIG[:TRACE_LOAD] = TRUE

  while opt = ARGV.shift
    case opt
    when "-d"
      $DEBUG = TRUE
    when "-m"
      CONFIG[:INSPECT] = FALSE if CONFIG[:INSPECT].nil?
      require "mathn.rb"
      include Math
    when "-r"
      opt = ARGV.shift
      CONFIG[:LOAD_MODULES].push opt if opt
    when "--inspect"
      CONFIG[:INSPECT] = TRUE
    when "--noinspect"
      CONFIG[:INSPECT] = FALSE
    when "--noreadline"
      CONFIG[:USE_READLINE] = FALSE
    when /^-/
      #	  print UnrecognizedSwitch.inspect, "\n"
      BC.fail UnrecognizedSwitch, opt
    else
      CONFIG[:USE_READLINE] = FALSE
      $0 = opt
      break
    end
  end
  CONFIG[:INSPECT] = TRUE if CONFIG[:INSPECT].nil?

  PROMPTi = "rbc%d> "
  PROMPTs = "rbc%d%s "
  PROMPTe = "rbc%d* "
  
  class BC
    def initialize
      lex_init
    end
    
    def eval_input(io, cont, bind)
      line = ''
      @io = io
      @ltype = nil
      @quoted = nil
      @indent = 0
      @lex_state = EXPR_BEG
      
      @io.prompt = format(PROMPTi, @indent)

      loop do
	@continue = FALSE
	l = @io.gets

	unless l
	  break if line == ''
	else
	  line = line + l
	  
	  lex(l) if l != "\n"
	  print @quoted.inspect, "\n" if $DEBUG
	  if @ltype
	    @io.prompt = format(PROMPTs, @indent, @ltype)
	    next
	  elsif @continue
	    @io.prompt = format(PROMPTe, @indent)
	    next
	  elsif @indent > 0
	    @io.prompt = format(PROMPTi, @indent)
	    next
	  end
	end
	
	if line != "\n"
	  begin
	    if CONFIG[:INSPECT]
	      print((cont._=eval(line, bind)).inspect, "\n")
	    else
	      print((cont._=eval(line, bind)), "\n")
	    end
	  rescue
	    #	$! = 'exception raised' unless $!
	    #	print "ERR: ", $!, "\n"
	    $! = RuntimeError.new("exception raised") unless $!
	    print $!.type, ": ", $!, "\n"
	  end
	end
	break if not l
	line = ''
	indent = 0
	@io.prompt = format(PROMPTi, indent)
      end
      print "\n"
    end
    
    EXPR_BEG = :EXPR_BEG
    EXPR_MID = :EXPR_MID
    EXPR_END = :EXPR_END
    EXPR_ARG = :EXPR_ARG
    EXPR_FNAME = :EXPR_FNAME

    CLAUSE_STATE_TRANS = {
      "alias"	=>  EXPR_FNAME,
      "and"	=>  EXPR_BEG,
      "begin"	=>  EXPR_BEG,
      "case"	=>  EXPR_BEG,
      "class"	=>  EXPR_BEG,
      "def"	=>  EXPR_FNAME,
      "defined?"	=>  EXPR_END,
      "do"	=>  EXPR_BEG,
      "else"	=>  EXPR_BEG,
      "elsif"	=>  EXPR_BEG,
      "end"	=>  EXPR_END,
      "ensure"	=>  EXPR_BEG,
      "for"	=>  EXPR_BEG,
      "if"	=>  EXPR_BEG,
      "in"	=>  EXPR_BEG,
      "module"	=>  EXPR_BEG,
      "nil"	=>  EXPR_END,
      "not"	=>  EXPR_BEG,
      "or"	=>  EXPR_BEG,
      "rescue"	=>  EXPR_MID,
      "return"	=>  EXPR_MID,
      "self"	=>  EXPR_END,
      "super"	=>  EXPR_END,
      "then"	=>  EXPR_BEG,
      "undef"	=>  EXPR_FNAME,
      "unless"	=>  EXPR_BEG,
      "until"	=>  EXPR_BEG,
      "when"	=>  EXPR_BEG,
      "while"	=>  EXPR_BEG,
      "yield"	=>  EXPR_END
    }
    
    ENINDENT_CLAUSE = [
      "case", "class", "def", "do", "for", "if",
      "module", "unless", "until", "while", "begin" #, "when"
    ]
    DEINDENT_CLAUSE = ["end"]

    PARCENT_LTYPE = {
      "q" => "\'",
      "Q" => "\"", #"
      "x" => "\`",
      "r" => "\/"
    }
    
    PARCENT_PAREN = {
      "{" => "}",
      "[" => "]",
      "<" => ">",
      "(" => ")"
    }
    
    def lex_init()
      @OP = Trie.new
      @OP.def_rules("\0", "\004", "\032"){}
      @OP.def_rules(" ", "\t", "\f", "\r", "\13") do
	@space_seen = TRUE
	next
      end
      @OP.def_rule("#") do
	|op, rests|
	@ltype = "#"
	identify_comment(rests)
      end
      @OP.def_rule("\n") do
	print "\\n\n" if $DEBUG
	if @lex_state == EXPR_BEG || @lex_state == EXPR_FNAME
	  @continue = TRUE
	else
	  @lex_state = EXPR_BEG
	end
      end
      @OP.def_rules("*", "*=", "**=", "**") {@lex_state = EXPR_BEG}
      @OP.def_rules("!", "!=", "!~") {@lex_state = EXPR_BEG}
      @OP.def_rules("=", "==", "===", "=~", "=>") {@lex_state = EXPR_BEG}
      @OP.def_rules("<", "<=", "<=>", "<<", "<=") {@lex_state = EXPR_BEG}
      @OP.def_rules(">", ">=", ">>", ">=") {@lex_state = EXPR_BEG}
      @OP.def_rules("'", '"') do
	|op, rests|
	@ltype = op
	@quoted = op
	identify_string(rests)
      end
      @OP.def_rules("`") do
	|op, rests|
	if @lex_state != EXPR_FNAME
	  @ltype = op
	  @quoted = op
	  identify_string(rests)
	end
      end
      @OP.def_rules('?') do
	|op, rests|
	@lex_state = EXPR_END
	identify_question(rests)
      end
      @OP.def_rules("&", "&&", "&=", "|", "||", "|=") do
	@lex_state = EXPR_BEG
      end
      @OP.def_rule("+@", proc{@lex_state == EXPR_FNAME}) {}
      @OP.def_rule("-@", proc{@lex_state == EXPR_FNAME}) {}
      @OP.def_rules("+=", "-=") {@lex_state = EXPR_BEG}
      @OP.def_rules("+", "-") do
	|op, rests|
	if @lex_state == EXPR_ARG
	  if @space_seen and rests[0] =~ /[0-9]/
	    identify_number(rests)
	  else
	    @lex_state = EXPR_BEG
	  end
	elsif @lex_state != EXPR_END and rests[0] =~ /[0-9]/
	  identify_number(rests)
	else
	  @lex_state = EXPR_BEG
	end
      end
      @OP.def_rule(".") do
	|op, rests|
	@lex_state = EXPR_BEG
	if rests[0] =~ /[0-9]/
	  rests.unshift op
	  identify_number(rests)
	end
      end
      @OP.def_rules("..", "...") {@lex_state = EXPR_BEG}
      
      lex_int2
    end
    
    def lex_int2
      @OP.def_rules("]", "}", ")") do
	@lex_state = EXPR_END
	@indent -= 1
      end
      @OP.def_rule(":") {}
      @OP.def_rule("::") {@lex_state = EXPR_BEG}
      @OP.def_rule("/") do
	|op, rests|
	if @lex_state == EXPR_BEG || @lex_state == EXPR_MID
	  @ltype = op
	  @quoted = op
	  identify_string(rests)
	elsif rests[0] == '='
	  rests.shift
	  @lex_state = EXPR_BEG
	elsif @lex_state == EXPR_ARG and @space_seen and rests[0] =~ /\s/
	  @ltype = op
	  @quoted = op
	  identify_string(rests)
	else 
	  @lex_state = EXPR_BEG
	end
      end
      @OP.def_rules("^", "^=") {@lex_state = EXPR_BEG}
      @OP.def_rules(",", ";") {@lex_state = EXPR_BEG}
      @OP.def_rule("~") {@lex_state = EXPR_BEG}
      @OP.def_rule("~@", proc{@lex_state = EXPR_FNAME}) {}
      @OP.def_rule("(") do
	@lex_state = EXPR_BEG
	@indent += 1
      end
      @OP.def_rule("[]", proc{@lex_state == EXPR_FNAME}) {}
      @OP.def_rule("[]=", proc{@lex_state == EXPR_FNAME}) {}
      @OP.def_rule("[") do
	@indent += 1
	if @lex_state != EXPR_FNAME
	  @lex_state = EXPR_BEG
	end
      end
      @OP.def_rule("{") do
	@lex_state = EXPR_BEG
	@indent += 1
      end
      @OP.def_rule('\\') {|op, rests| identify_escape(rests)} #')
      @OP.def_rule('%') do
	|op, rests|
	if @lex_state == EXPR_BEG || @lex_state == EXPR_MID
	  identify_quotation(rests)
	elsif rests[0] == '='
	  rests.shift
	elsif @lex_state == EXPR_ARG and @space_seen and rests[0] =~ /\s/
	  identify_quotation(rests)
	else
	  @lex_state = EXPR_BEG
	end
      end
      @OP.def_rule('$') do #'
	|op, rests|
	identify_gvar(rests)
      end
      @OP.def_rule('@') do
	|op, rests|
	if rests[0] =~ /[\w_]/
	  rests.unshift op
	  identify_identifier(rests)
	end
      end
      @OP.def_rule("") do
	|op, rests|
	printf "match: start %s: %s", op, rests.inspect if $DEBUG
	if rests[0] =~ /[0-9]/
	  identify_number(rests)
	elsif rests[0] =~ /[\w_]/
	  identify_identifier(rests)
	end
	printf "match: end %s: %s", op, rests.inspect if $DEBUG
      end
    end
    
    def lex(l)
      chrs = l.split(//)
      tokens = []
      
      case @ltype
      when "'", '"', '`', '/'
	identify_string(chrs)
	return if chrs.empty?
      when "#"
	identify_comment(chrs)
	return
      when "="
	if l =~ /^=end/
	  $ltype = nil
	  return
	end
      else
	if l =~ /^=begin/
	  $ltype = "="
	  return
	end
      end
      
      until chrs.empty?
	@space_seen = FALSE
	printf "perse: %s\n", chrs.join("") if $DEBUG
	@OP.match(chrs)
	printf "lex_state: %s continue: %s\n", @lex_state.id2name, @continue if $DEBUG
      end
    end
    
    def identify_gvar(chrs)
      @lex_state = EXPR_END
      
      ch = chrs.shift
      case ch
      when /[_~*$?!@/\\;,.=:<>"]/   #"
	return
	
      when "-"
	ch = chrs.shift
	return
	
      when "&", "`", "'", "+"
	return
	
      when /[1-9]/
	chrs.unshift ch
	v = "$"
	while (ch = chrs.shift) =~ /[0-9]/
	end
	chrs.unshift ch
	return
	
      when /\w/
	chrs.unshift ch
	chrs.unshift "$"
	identify_identifier(chrs)
	return
	
      else 
	chrs.unshift ch
	return
      end
    end
    
    def identify_identifier(chrs)
      token = ""
      token.concat chrs.shift if chrs[0] =~ /[$@]/
      while (ch = chrs.shift) =~ /\w|_/
	print ":", ch, ":" if $DEBUG
	token.concat ch
      end
      chrs.unshift ch
      
      if ch == "!" or ch == "?"
	chrs.shift
	token.concat ch
      end
      # fix token
      
      if token =~ /^[$@]/
	@lex_state = EXPR_END
	return
      end
      
      print token, "\n" if $DEBUG
      if state = CLAUSE_STATE_TRANS[token]
	if @lex_state != EXPR_BEG and token =~ /^(if|unless|while|until)/
	  # $B=$>~;R(B
	else
	  if ENINDENT_CLAUSE.include?(token)
	    @indent += 1
	  elsif DEINDENT_CLAUSE.include?(token)
	    @indent -= 1
	  end
	end
	@lex_state = state
	return
      end
      if @lex_state == EXPR_FNAME
	@lex_state = EXPR_END
	if chrs[0] == '='
	  chrs.shift
	end
      elsif @lex_state == EXPR_BEG
	@lex_state = EXPR_ARG
      else
	@lex_state = EXPR_END
      end
    end
    
    def identify_quotation(chrs)
      ch = chrs.shift
      if lt = PARCENT_LTYPE[ch]
	ch = chrs.shift
      else
	lt = "\"" #"
      end
      if ch !~ /\W/
	chrs.unshift ch
	next
      end
      @ltype = lt
      unless @quoted = PARCENT_PAREN[ch]
	@quoted = ch
      end
      identify_string(chrs)
    end

    def identify_number(chrs)
      @lex_state = EXPR_END
      
      ch = chrs.shift
      case ch
      when /0/
	if (ch = chrs[0]) == "x"
	  chrs.shift
	  match = /[0-9a-f_]/
	else
	  match = /[0-7_]/
	end
	while ch = chrs.shift
	  if ch !~ match
	    chrs.unshift ch
	    break
	  end
	end
	return
      end
      
      while ch = chrs.shift
	case ch
	when /[0-9]/
	when "e", "E"
	  #	type = FLOAT
	  unless (ch = chrs.shift) == "+" or ch == "-"
	    chrs.unshift ch
	  end
	when "."
	  #	type = FLOAT
	when "_"
	else
	  chrs.unshift ch
	  return
	end
      end
    end
    
    def identify_question(chrs)
      @lex_state = EXPR_END
      
      if chrs.shift == "\\" #"
	identify_escape(chrs)
      end
    end
    
    def identify_string(chrs)
      while ch = chrs.shift
	if @quoted == ch
	  if @ltype == "/"
	    if chrs[0] =~ /i|o|n|e|s/
	      chrs.shift
	    end
	  end
	  @ltype = nil
	  @quoted = nil
	  @lex_state = EXPR_END
	  break
	elsif ch == '\\' #'
	  identify_escape(chrs)
	end
      end
    end
    
    def identify_comment(chrs)
      while ch = chrs.shift
	if ch == "\\" #"
	  identify_escape(chrs)
	end
	if ch == "\n"
	  @ltype = nil
	  chrs.unshift ch
	  break
	end
      end
    end
    
    def identify_escape(chrs)
      ch = chrs.shift
      case ch
      when "\n", "\r", "\f"
	@continue = TRUE
      when "\\", "n", "t", "r", "f", "v", "a", "e", "b" #"
      when /[0-7]/
	chrs.unshift ch
	3.times do
	  ch = chrs.shift
	  case ch
	  when /[0-7]/
	  when nil
	    break
	  else
	    chrs.unshift ch
	    break
	  end
	end
      when "x"
	2.times do
	  ch = chrs.shift
	  case ch
	  when /[0-9a-fA-F]/
	  when nil
	    break
	  else
	    chrs.unshift ch
	    break
	  end
	end
      when "M"
	if (ch = chrs.shift) != '-'
	  chrs.unshift ch
	elsif (ch = chrs.shift) == "\\" #"
	  identify_escape(chrs)
	end
	return
      when "C", "c", "^"
	if ch == "C" and (ch = chrs.shift) != "-"
	  chrs.unshift ch
	elsif (ch = chrs.shift) == "\\" #"
	  identify_escape(chrs)
	end
	return
      end
    end
  end
  
  class Trie
    extend Exception2MessageMapper
    def_exception :ErrNodeNothing, "node nothing"
    def_exception :ErrNodeAlreadyExists, "node already exists"

    class Node
      # postproc$B$,$J$1$l$PCj>]%N!<%I(B, nil$B$8$c$J$1$l$P6q>]%N!<%I(B
      def initialize(preproc = nil, postproc = nil)
	@Tree = {}
	@preproc = preproc
	@postproc = postproc
      end
      
      def preproc(p)
	@preproc = p
      end
      
      def postproc(p)
	@postproc = p
      end
      
      def search(chrs, opt = nil)
	return self if chrs.empty?
	ch = chrs.shift
	if node = @Tree[ch]
	  node.search(chrs, opt)
	else
	  if opt
	    chrs.unshift ch
	    self.create_subnode(chrs)
	  else
	    Trie.fail ErrNodeNothing
	  end
	end
      end
      
      def create_subnode(chrs, preproc = nil, postproc = nil)
	ch = chrs.shift
	if node = @Tree[ch]
	  if chrs.empty?
	    Trie.fail ErrNodeAlreadyExists
	  else
	    node.create_subnode(chrs, preproc, postproc)
	  end
	else
	  if chrs.empty?
	    node = Node.new(preproc, postproc)
	  else
	    node = Node.new
	    node.create_subnode(chrs, preproc, postproc)
	  end
	  @Tree[ch] = node
	end
	node
      end
      
      def match(chrs, op = "")
	print "match: ", chrs, ":", op, "\n" if $DEBUG
	if chrs.empty?
	  if @preproc.nil? || @preproc.call(op, chrs)
	    printf "op1: %s\n", op if $DEBUG
	    @postproc.call(op, chrs)
	    ""
	  else
	    nil
	  end
	else
	  ch = chrs.shift
	  if node = @Tree[ch]
	    if ret = node.match(chrs, op+ch)
	      return ch+ret
	    elsif @postproc and @preproc.nil? || @preproc.call(op, chrs)
	      chrs.unshift ch
	      printf "op2: %s\n", op if $DEBUG
	      @postproc.call(op, chrs)
	      return ""
	    else
	      chrs.unshift ch
	      return nil
	    end
	  else
	    if @postproc and @preproc.nil? || @preproc.call(op, chrs)
	      printf "op3: %s\n", op if $DEBUG
	      chrs.unshift ch
	      @postproc.call(op, chrs)
	      return ""
	    else
	      chrs.unshift ch
	      return nil
	    end
	  end
	end
      end
    end
    
    def initialize
      @head = Node.new("")
    end
    
    def def_rule(token, preproc = nil, postproc = nil)
      node = search(token, :CREATE)
#      print node.inspect, "\n" if $DEBUG
      node.preproc(preproc)
      if iterator?
	node.postproc(proc)
      elsif postproc
	node.postproc(postproc)
      end
    end
    
    def def_rules(*tokens)
      if iterator?
	p = proc
      end
      for token in tokens
	def_rule(token, nil, p)
      end
    end
    
    def preporc(token)
      node = search(token)
      node.preproc proc
    end
    
    def postproc(token)
      node = search(token)
      node.postproc proc
    end
    
    def search(token, opt = nil)
      @head.search(token.split(//), opt)
    end
    
    def match(token)
      token = token.split(//) if token.kind_of?(String)
      ret = @head.match(token)
      printf "match end: %s:%s", ret, token.inspect if $DEBUG
      ret
    end
    
    def inspect
      format("<Trie: @head = %s>", @head.inspect)
    end
  end
  
  if /^-tt(.*)$/ =~ ARGV[0]
#    Tracer.on
    case $1
    when "1"
      tr = Trie.new
      print "0: ", tr.inspect, "\n"
      tr.def_rule("=") {print "=\n"}
      print "1: ", tr.inspect, "\n"
      tr.def_rule("==") {print "==\n"}
      print "2: ", tr.inspect, "\n"
      
      print "case 1:\n"
      print tr.match("="), "\n"
      print "case 2:\n"
      print tr.match("=="), "\n"
      print "case 3:\n"
      print tr.match("=>"), "\n"
      
    when "2"
      tr = Trie.new
      print "0: ", tr.inspect, "\n"
      tr.def_rule("=") {print "=\n"}
      print "1: ", tr.inspect, "\n"
      tr.def_rule("==", proc{FALSE}) {print "==\n"}
      print "2: ", tr.inspect, "\n"
      
      print "case 1:\n"
      print tr.match("="), "\n"
      print "case 2:\n"
      print tr.match("=="), "\n"
      print "case 3:\n"
      print tr.match("=>"), "\n"
    end
    exit
  end
  
  module CONTEXT
    def _=(value)
      @_ = value
    end
    
    def _
      @_
    end
    
    def quit
      exit
    end
    
    def trace_load(opt = nil)
      if opt
	@Trace_require = opt
      else
	@Trace_require = !@Trace_require
      end
      print "Switch to load/require #{unless @Trace_require; ' non';end} trace mode.\n"
      if @Trace_require
	eval %{
	  class << self
	    alias load rbc_load
	    alias require rbc_require
	  end
	}
      else
	eval %{
	  class << self
	    alias load rbc_load_org
	    alias require rbc_require_org
	  end
	}
      end
      @Trace_require
    end
    
    alias rbc_load_org load
    def rbc_load(file_name)
      return true if load_sub(file_name)
      raise LoadError, "No such file to load -- #{file_name}"
    end

    alias rbc_require_org require
    def rbc_require(file_name)
      rex = Regexp.new("#{Regexp.quote(file_name)}(\.o|\.rb)?")
      return false if $".find{|f| f =~ rex}

      case file_name
      when /\.rb$/
	if load_sub(file_name)
	  $:.push file_name
	  return true
	end
      when /\.(so|o|sl)$/
	require_org(file_name)
      end
      
      if load_sub(f = file_name + ".rb")
	  $:.push f
      end
      require(file_name)
    end

    def load_sub(fn)
      if fn =~ /^#{Regexp.quote(File::Separator)}/
	return false unless File.exist?(fn)
	BC.new.eval_input FileInputMethod.new(fn), self, CONFIG[:BIND]
	return true
      end
      
      for path in $:
	if File.exist?(f = File.join(path, fn))
	  BC.new.eval_input FileInputMethod.new(f), self, CONFIG[:BIND]
	  return true
	end
      end
      return false
    end

    def inspect(opt = nil)
      if opt
	CONFIG[:INSPECT] = opt
      else
	CONFIG[:INSPECT] = !$INSPECT
      end
      print "Switch to#{unless $INSPECT; ' non';end} inspect mode.\n"
      $INSPECT
    end
    
    def run
      CONFIG[:BIND] = proc

      if CONFIG[:TRACE_LOAD]
	trace_load true
      end
  
      for m in CONFIG[:LOAD_MODULES]
	begin
	  require m
	rescue
	  print $@[0], ":", $!.type, ": ", $!, "\n"
	end
      end
  
      if !$0.equal?(CONFIG[0])
	io = FileInputMethod.new($0)
      elsif defined? Readline
	io = ReadlineInputMethod.new
      else
	io = StdioInputMethod.new
      end

      BC.new.eval_input io, self, CONFIG[:BIND]
    end
  end
  
  class InputMethod
    attr :prompt, TRUE
    
    def gets
    end
    public :gets
  end
  
  class StdioInputMethod < InputMethod
    def gets
      print @prompt
      $stdin.gets
    end
  end
  
  class FileInputMethod < InputMethod
    def initialize(file)
      @io = open(file)
    end

    def gets
      l = @io.gets
      print @prompt, l
      l
    end
  end

  if CONFIG[:USE_READLINE]
    begin
      require "readline"
      print "use readline module\n"
      class ReadlineInputMethod < InputMethod
	include Readline 
	def gets
	  if l = readline(@prompt, TRUE)
	    l + "\n"
	  else
	    l
	  end
	end
      end
    rescue
      CONFIG[:USE_READLINE] = FALSE
    end
  end
end

extend BC_APPLICATION__::CONTEXT
run{}