Debian Codegraph @

lib/ninix/dll/kawari.rb

raw
1 # -*- coding: utf-8 -*-
2 #
3 # kawari.rb - a "華和梨" compatible Shiori module for ninix
4 # Copyright (C) 2001, 2002 by Tamito KAJIYAMA
5 # Copyright (C) 2002, 2003 by MATSUMURA Namihiko <[email protected]>
6 # Copyright (C) 2002-2019 by Shyouzou Sugitani <[email protected]>
7 # Copyright (C) 2003 by Shun-ichi TAHARA <[email protected]>
8 #
9 # This program is free software; you can redistribute it and/or modify it
10 # under the terms of the GNU General Public License (version 2) as
11 # published by the Free Software Foundation. It is distributed in the
12 # hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
13 # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 # PURPOSE. See the GNU General Public License for more details.
15 #
16
17
18 require 'base64'
19
20 require_relative "../home"
21 require_relative "../logging"
22
23
24 module Kawari
25
26 ### READER ###
27 $charset = 'CP932' # default
28
29 def self.read_dict(path)
30 open(path, 'rb') do |f|
31 lineno = 0
32 buf = []
33 for line in f
34 lineno = lineno + 1
35 position = [lineno, path]
36 if line.start_with?('!KAWA0000')
37 line = Kawari.decrypt(line[9..-1]).force_encoding($charset).encode("UTF-8", :invalid => :replace, :undef => :replace)
38 else
39 line = line.force_encoding($charset).encode("UTF-8", :invalid => :replace, :undef => :replace)
40 end
41 if line.strip.empty? or \
42 line.start_with?('#') or \
43 line.start_with?(':crypt') or \
44 line.start_with?(':endcrypt')
45 next
46 end
47 unless line.include?(':')
48 Logging::Logging.debug('kawari.rb: syntax error at line ' + position[0].to_s + ' in ' + position[1].to_s)
49 Logging::Logging.debug(line.strip())
50 next
51 end
52 entries, phrases = line.split(':', 2)
53 entries.strip!
54 phrases.strip!
55 if entries.empty?
56 Logging::Logging.debug('kawari.rb: syntax error at line ' + position[0].to_s + ' in ' + position[1].to_s)
57 Logging::Logging.debug(line.strip())
58 next
59 end
60 next if phrases.empty?
61 if entries == 'locale'
62 unless Encoding.name_list.include?(phrases)
63 Logging::Logging.error('kawari.rb: unsupported charset ' + phrases.to_s)
64 else
65 $charset = phrases
66 end
67 end
68 buf << [entries, phrases, position]
69 end
70 return buf
71 end
72 end
73
74 def self.decrypt(data)
75 buf = []
76 for c in Base64.decode64(data).each_char
77 buf << (c.ord ^ 0xcc).chr
78 end
79 return buf.join('')
80 end
81
82 def self.encrypt(data)
83 buf = []
84 for c in data
85 buf << (c.ord ^ 0xcc).chr
86 end
87 line = ['!KAWA0000', Base64.encode64(buf.join(''))].join('')
88 return line.gsub("\n", '')
89 end
90
91 def self.create_dict(buf)
92 rdict = {} # rules
93 kdict = {} # keywords
94 for entries, phrases, position in buf
95 parsed_entries = Kawari.parse_entries(entries)
96 parsed_phrases = Kawari.parse_phrases(phrases)
97 if parsed_phrases.nil?
98 Logging::Logging.debug('kawari.rb: syntax error at line ' + position[0].to_s + ' in ' + position[1].to_s + ':')
99 Logging::Logging.debug(phrases.strip())
100 next
101 end
102 if entries.start_with?('[')
103 Kawari.add_phrases(kdict, parsed_entries, parsed_phrases)
104 next
105 end
106 for entry in parsed_entries
107 Kawari.add_phrases(rdict, entry, parsed_phrases)
108 end
109 end
110 return rdict, kdict
111 end
112
113 def self.add_phrases(dic, entry, phrases)
114 unless dic.include?(entry)
115 dic[entry] = []
116 end
117 for phrase in phrases
118 unless phrase.empty?
119 phrase[0] = phrase[0].lstrip()
120 phrase[-1] = phrase[-1].rstrip()
121 end
122 dic[entry] << phrase
123 end
124 end
125
126 def self.parse_entries(data)
127 if data.start_with?('[') and data.end_with?(']')
128 entries = []
129 i = 0
130 j = data.length
131 while i < j
132 if data[i] == '"'
133 i, text = Kawari.parse_quotes(data, i)
134 entries << text
135 else
136 i += 1
137 end
138 end
139 else
140 entries = data.split(',', 0).map {|s| s.strip }
141 end
142 return entries
143 end
144
145 Re_comma = Regexp.new('\A,')
146
147 def self.parse_phrases(data)
148 buf = []
149 i = 0
150 j = data.length
151 while i < j
152 if data[i] == ','
153 i += 1
154 end
155 i, phrase = Kawari.parse(data, i, :stop_pattern => Re_comma)
156 unless phrase.empty?
157 buf << phrase
158 end
159 end
160 return buf
161 end
162
163 def self.parse(data, start, stop_pattern: nil)
164 buf = []
165 i = start
166 j = data.length
167 while i < j
168 break unless stop_pattern.nil? or stop_pattern.match(data[i..-1]).nil?
169 if data[i] == '"'
170 i, text = Kawari.parse_quotes(data, i)
171 buf << '"' + text + '"'
172 elsif data[i..i + 1] == '${'
173 i, text = Kawari.parse_reference(data, i)
174 buf << text
175 elsif data[i..i + 1] == '$('
176 i, text = Kawari.parse_inline_script(data, i)
177 buf << text
178 elsif data[i] == '$'
179 buf << data[i]
180 i += 1
181 elsif data[i] == ';'
182 buf << data[i]
183 i += 1
184 else
185 i, text = Kawari.parse_text(data, i, :stop_pattern => stop_pattern)
186 buf << text
187 end
188 end
189 unless buf.empty?
190 if Kawari.is_space(buf[0])
191 buf.delete_at(0)
192 else
193 buf[0] = buf[0].lstrip()
194 end
195 end
196 unless buf.empty?
197 if Kawari.is_space(buf[-1])
198 buf.delete_at(-1)
199 else
200 buf[-1] = buf[-1].rstrip()
201 end
202 end
203 return i, buf
204 end
205
206 def self.parse_quotes(data, start)
207 buf = []
208 i = (start + 1)
209 j = data.length
210 while i < j
211 if data[i] == '"'
212 i += 1
213 break
214 elsif data[i] == '\\'
215 i += 1
216 if i < j and data[i] == '"'
217 buf << ['\\', data[i]].join('')
218 i += 1
219 else
220 buf << '\\'
221 end
222 else
223 buf << data[i]
224 i += 1
225 end
226 end
227 return i, buf.join('')
228 end
229
230 def self.parse_reference(data, start)
231 i = start
232 j = data.length
233 while i < j
234 if data[i] == '}'
235 i += 1
236 break
237 else
238 i += 1
239 end
240 end
241 return i, data[start..i-1]
242 end
243
244 def self.parse_inline_script(data, start)
245 buf = ['$']
246 i = (start + 1)
247 j = data.length
248 npar = 0
249 while i < j
250 #begin specification bug work-around (1/3)
251 if data[i] == ')'
252 buf << data[i]
253 i += 1
254 break
255 end
256 #end
257 if data[i] == '"'
258 i, text = Kawari.parse_quotes(data, i)
259 buf << '"' + text.to_s + '"'
260 elsif data[i..i + 1] == '${'
261 i, text = Kawari.parse_reference(data, i)
262 buf << text
263 elsif data[i..i + 1] == '$('
264 i, text = Kawari.parse_inline_script(data, i)
265 buf << text
266 else
267 if data[i] == '('
268 npar = npar + 1
269 elsif data[i] == ')'
270 npar = (npar - 1)
271 end
272 buf << data[i]
273 i += 1
274 end
275 break if npar.zero?
276 end
277 return i, buf.join('')
278 end
279
280 def self.is_space(s)
281 s.strip.empty?
282 end
283
284 def self.parse_text(data, start, stop_pattern: nil)
285 condition = Kawari.is_space(data[start])
286 i = start
287 j = data.length
288 while i < j
289 break unless stop_pattern.nil? or stop_pattern.match(data[i..-1]).nil?
290 if ['$', '"'].include?(data[i])
291 break
292 elsif Kawari.is_space(data[i]) != condition
293 break
294 elsif data[i] == ';'
295 if i == start
296 i += 1
297 end
298 break
299 else
300 i += 1
301 end
302 end
303 return i, data[start..i-1]
304 end
305
306 def self.read_local_script(path)
307 rdict = {}
308 kdict = {}
309 open(path, :encoding => $charset) do |f|
310 while line = f.gets
311 if line.start_with?('#')
312 rdict[line.strip()] = [f.readline().strip()]
313 end
314 end
315 end
316 return rdict, kdict
317 end
318
319 ### KAWARI ###
320
321 class Kawari7
322 attr_reader :rdictlist, :kdictlist
323
324 MAXDEPTH = 30
325
326 def initialize(prefix, pathlist, rdictlist, kdictlist)
327 kawari_init(prefix, pathlist, rdictlist, kdictlist)
328 end
329
330 def kawari_init(prefix, pathlist, rdictlist, kdictlist)
331 @kis_commands = {
332 # flow controls
333 'if' => 'exec_new_if',
334 'foreach' => 'exec_foreach',
335 'loop' => 'exec_loop',
336 'while' => 'exec_while',
337 'until' => 'exec_until',
338 # dictionary operators
339 'adddict' => 'exec_adddict',
340 'array' => 'exec_array',
341 'clear' => 'exec_clear',
342 'enumerate' => 'exec_enumerate',
343 'set' => 'exec_set',
344 'load' => 'exec_load',
345 'save' => 'exec_save',
346 'savecrypt' => 'exec_savecrypt',
347 'textload' => 'exec_textload',
348 'size' => 'exec_size',
349 'get' => 'exec_get',
350 # list operators
351 'unshift' => 'exec_unshift',
352 'shift' => 'exec_shift',
353 'push' => 'exec_push',
354 'pop' => 'exec_pop',
355 # counter operators
356 'inc' => 'exec_inc',
357 'dec' => 'exec_dec',
358 # expression evaluators
359 'expr' => 'exec_expr',
360 'test' => 'exec_test',
361 '[' => 'exec_test',
362 'entry' => 'exec_entry',
363 'eval' => 'exec_eval',
364 # utility functions
365 'NULL' => 'exec_null',
366 '?' => 'exec_choice',
367 'date' => 'exec_date',
368 'rand' => 'exec_rand',
369 'echo' => 'exec_echo',
370 'escape' => 'exec_escape',
371 'tolower' => 'exec_tolower',
372 'toupper' => 'exec_toupper',
373 'pirocall' => 'exec_pirocall',
374 'split' => 'exec_split',
375 'urllist' => nil,
376 'chr' => 'exec_chr',
377 'help' => nil,
378 'ver' => nil,
379 'searchghost' => nil,
380 'saoriregist' => nil,
381 'saorierase' => nil,
382 'callsaori' => nil,
383 'callsaorix' => nil,
384 }
385 @prefix = prefix
386 @pathlist = pathlist
387 @rdictlist = rdictlist
388 @kdictlist = kdictlist
389 @system_entries = {}
390 @expr_parser = ExprParser.new()
391 #begin specification bug work-around (2/3)
392 @expr_parser.kawari = self
393 #end
394 @otherghost = {}
395 get_system_entry('OnLoad')
396 end
397
398 def finalize
399 get_system_entry('OnUnload')
400 end
401
402 # SHIORI/1.0 API
403 def getaistringrandom
404 get('sentence')
405 end
406
407 def getaistringfromtargetword(word)
408 get('sentence') # XXX
409 end
410
411 def getdms
412 getword('dms')
413 end
414
415 def getword(word_type)
416 for delimiter in ['.', '-']
417 name = ['compatible', delimiter, word_type].join('')
418 script = get(name, :default => nil)
419 return script.strip unless script.nil?
420 end
421 return ''
422 end
423
424 def getstring(name)
425 get("resource.#{name}")
426 end
427
428 # SHIORI/2.2 API
429 def get_event_response(event,
430 ref0: nil, ref1: nil, ref2: nil, ref3: nil,
431 ref4: nil, ref5: nil, ref6: nil, ref7: nil)
432 ref = [ref0, ref1, ref2,ref3, ref4, ref5, ref6, ref7].map {|r| r.to_s unless r.nil? }
433 for i in 0..7
434 unless ref[i].nil?
435 value = ref[i]
436 @system_entries['system.Reference' + i.to_s] = value
437 @system_entries['system-Reference' + i.to_s] = value
438 end
439 end
440 script = nil
441 if event == 'OnCommunicate'
442 @system_entries['system.Sender'] = ref[0]
443 @system_entries['system-Sender'] = ref[0]
444 @system_entries['system.Sender.Path'] = 'local' # (local/unknown/external)
445 @system_entries['system-Sender.Path'] = 'local' # (local/unknown/external)
446 unless @system_entries.include?('system.Age')
447 @system_entries['system.Age'] = '0'
448 @system_entries['system-Age'] = '0'
449 end
450 @system_entries['system.Sentence'] = ref[1]
451 @system_entries['system-Sentence'] = ref[1]
452 if @otherghost.include?(ref[0])
453 s0, s1 = @otherghost[ref[0]]
454 @system_entries['system.Surface'] = [s0.to_s,
455 s1.to_s].join(',')
456 @system_entries['system-Surface'] = [s0.to_s,
457 s1.to_s].join(',')
458 end
459 script = get_system_entry('OnResponse')
460 if script.nil?
461 for dic in @kdictlist
462 for entry in dic.keys
463 break_flag = false
464 for word in entry
465 unless ref[1].include?(word)
466 break_flag = true
467 break
468 end
469 end
470 unless break_flag
471 script = expand(dic[entry].sample)
472 break
473 end
474 end
475 end
476 end
477 if script.nil?
478 script = get_system_entry('OnResponseUnknown')
479 end
480 unless script.nil?
481 script = script.strip()
482 end
483 else
484 for delimiter in ['.', '-']
485 name = ['event', delimiter, event].join('')
486 script = get(name, :default => nil)
487 unless script.nil?
488 script = script.strip()
489 break
490 end
491 end
492 end
493 return script
494 end
495
496 # SHIORI/2.4 API
497 def teach(word)
498 @system_entries['system.Sentence'] = word
499 @system_entries['system-Sentence'] = word
500 return get_system_entry('OnTeach')
501 end
502
503 def get_system_entry(entry)
504 for delimiter in ['.', '-']
505 name = ['system', delimiter, entry].join('')
506 script = get(name, :default => nil)
507 unless script.nil?
508 return script.strip()
509 end
510 end
511 return nil
512 end
513
514 def otherghostname(ghost_list)
515 ghosts = []
516 for ghost in ghost_list
517 name, s0, s1 = ghost.split(1.chr, 3)
518 ghosts << [name, s0, s1]
519 @otherghost[name] = [s0, s1]
520 end
521 otherghost_name = []
522 for ghost in ghosts
523 otherghost_name << ghost[0]
524 end
525 @system_entries['system.OtherGhost'] = otherghost_name
526 @system_entries['system-OtherGhost'] = otherghost_name
527 otherghost_ex = []
528 for ghost in ghosts
529 otherghost_ex << ghost.join(1.chr)
530 end
531 @system_entries['system.OtherGhostEx'] = otherghost_ex
532 @system_entries['system-OtherGhostEx'] = otherghost_ex
533 unless ghosts.empty?
534 get_system_entry('OnNotifyOther')
535 end
536 return ''
537 end
538
539 def communicate_to
540 communicate = get_system_entry('communicate')
541 unless communicate.nil?
542 if communicate == 'stop'
543 @system_entries['system.Age'] = '0'
544 @system_entries['system-Age'] = '0'
545 communicate = nil
546 else
547 if @system_entries.include?('system.Age')
548 age = (@system_entries['system.Age'].to_i + 1)
549 @system_entries['system.Age'] = age.to_s
550 @system_entries['system-Age'] = age.to_s
551 else
552 @system_entries['system.Age'] = '0'
553 @system_entries['system-Age'] = '0'
554 end
555 end
556 end
557 clear('system.communicate')
558 return communicate
559 end
560
561 # internal
562 def clear(name)
563 Logging::Logging.debug('*** clear("' + name.to_s + '")')
564 for dic in @rdictlist
565 dic.delete(name) if dic.include?(name)
566 end
567 end
568
569 def get_internal_dict(name)
570 break_flag = false
571 for dic in @rdictlist
572 if dic.include?(name)
573 break_flag = true
574 break
575 end
576 end
577 unless break_flag
578 dic = @rdictlist[0]
579 dic[name] = []
580 end
581 return dic
582 end
583
584 def unshift(name, value)
585 Logging::Logging.debug('*** unshift("' + name.to_s + '", "' + value.to_s + '")')
586 dic = get_internal_dict(name)
587 i, segments = Kawari.parse(value, 0)
588 dic[name].insert(0, segments)
589 end
590
591 def shift(name)
592 dic = get_internal_dict(name)
593 value = expand(dic[name].shift)
594 Logging::Logging.debug('*** shift("' + name.to_s + '") => "' + value.to_s + '"')
595 return value
596 end
597
598 def push(name, value)
599 Logging::Logging.debug('*** push("' + name.to_s + '", "' + value.to_s + '")')
600 dic = get_internal_dict(name)
601 i, segments = Kawari.parse(value, 0)
602 dic[name] << segments
603 end
604
605 def pop(name)
606 dic = get_internal_dict(name)
607 value = expand(dic[name].pop())
608 Logging::Logging.debug('*** pop("' + name.to_s + '") => "' + value.to_s + '"')
609 return value
610 end
611
612 def set(name, value)
613 clear(name)
614 push(name, value)
615 end
616
617 def get(name, context: nil, depth: 0, default: '')
618 return '' if depth == MAXDEPTH
619 if not name.empty? and name.start_with?('@')
620 segments = context[name].sample
621 else
622 unless name.include?('&')
623 selection = select_simple_phrase(name)
624 else
625 selection = select_compound_phrase(name)
626 end
627 if selection.nil?
628 Logging::Logging.debug('${{' + name.to_s + '}} not found')
629 return default
630 end
631 segments, context = selection
632 end
633 Logging::Logging.debug([name, '=>', segments].join(''))
634 return expand(segments, :context => context, :depth => depth)
635 end
636
637 def parse_all(data, start: 0)
638 i, segments = Kawari.parse(data, start)
639 return expand(segments)
640 end
641
642 def parse_sub(data, start: 0, stop_pattern: nil)
643 i, segments = Kawari.parse(data, start, :stop_pattern => stop_pattern)
644 return i, expand(segments)
645 end
646
647 def expand(segments, context: nil, depth: 0)
648 buf = []
649 references = []
650 i = 0
651 j = segments.length
652 while i < j
653 segment = segments[i]
654 if segment.empty?
655 #pass
656 elsif segment.start_with?('${') and segment.end_with?('}')
657 newname = segment[2..-2]
658 if is_number(newname)
659 begin
660 segment = references[Integer(newname)]
661 rescue #except IndexError:
662 #pass
663 end
664 elsif is_system_entry(newname)
665 if ['system.OtherGhost', 'system-OtherGhost',
666 'system.OtherGhostEx',
667 'system-OtherGhostEx'].include?(newname)
668 segment_list = @system_entries[newname]
669 unless segment_list.empty?
670 segment = segment_list.sample
671 else
672 segment = ''
673 end
674 elsif newname == 'system.communicate'
675 segment = get_system_entry('communicate')
676 else
677 segment = (@system_entries.include?(newname) ? @system_entries[newname] : segment)
678 end
679 else
680 segment = get(newname, :context => context, :depth => depth + 1)
681 end
682 references << segment
683 elsif segment.start_with?('$(') and segment.end_with?(')')
684 i, segment = eval_inline_script(segments, i)
685 elsif segment.start_with?('"') and segment.end_with?('"')
686 segment = segment[1..-2].gsub('\\"', '"')
687 end
688 buf << segment
689 i += 1
690 end
691 return buf.join('')
692 end
693
694 def atoi(s)
695 begin
696 return Integer(s)
697 rescue #except ValueError:
698 return 0
699 end
700 end
701
702 def is_number(s)
703 begin
704 Integer(s)
705 rescue #except ValueError:
706 return false
707 end
708 return true
709 end
710
711 def is_system_entry(s)
712 return (s.start_with?('system-') or s.start_with?('system.'))
713 end
714
715 def select_simple_phrase(name)
716 n = 0
717 buf = []
718 for d in @rdictlist
719 if d.include?(name)
720 c = d[name]
721 else
722 c = []
723 end
724 n += c.length
725 buf << [c, d]
726 end
727 return nil if n.zero?
728 n = rand(0..n-1)
729 for c, d in buf
730 m = c.length
731 break if n < m
732 n -= m
733 end
734 return c[n], d
735 end
736
737 def select_compound_phrase(name)
738 buf = []
739 for name in name.split('&', 0).map {|s| s.strip }
740 cp_list = []
741 for d in @rdictlist
742 cp_list.concat(d.include?(name) ? d[name] : [])
743 end
744 buf << cp_list
745 end
746 buf = buf.map {|x| [x.length, x] }
747 buf.sort!
748 buf = buf.map {|x| x[1] }
749 candidates = []
750 for item in buf.shift
751 break_flag = false
752 for cp_list in buf
753 unless cp_list.include?(item)
754 break_flag = true
755 break
756 end
757 end
758 unless break_flag
759 candidates << item
760 end
761 end
762 if candidates.empty?
763 return nil
764 end
765 return candidates.sample, nil
766 end
767
768 def eval_inline_script(segments, i)
769 # check old 'if' syntax
770 if segments[i].start_with?('$(if ') and i + 1 < segments.length and \
771 segments[i + 1].start_with?('$(then ')
772 if_block = segments[i][5..-2].strip()
773 i += 1
774 then_block = segments[i][7..-2].strip()
775 if i + 1 < segments.length and segments[i + 1].start_with?('$(else ')
776 i += 1
777 else_block = segments[i][7..-2].strip()
778 else
779 else_block = ''
780 end
781 if i + 1 < segments.length and segments[i + 1] == '$(endif)'
782 i += 1
783 else
784 Logging::Logging.debug('kawari.rb: syntax error: $(endif) expected')
785 return i, '' # syntax error
786 end
787 return i, exec_old_if(if_block, then_block, else_block)
788 end
789 # execute command(s)
790 values = []
791 for command in split_commands(segments[i][2..-2])
792 argv = parse_argument(command)
793 argv[0] = expand(argv[0])
794 if argv[0] == 'silent'
795 if argv.length == 1
796 values = []
797 else
798 Logging::Logging.debug(
799 ['kawari.rb: syntax error:', segments[i]].join(''))
800 end
801 next
802 end
803 handler = @kis_commands[argv[0]]
804 begin
805 fail RuntimeError.new('invalid command') if handler.nil?
806 values << method(handler).call(argv)
807 rescue => message #except RuntimeError as message:
808 Logging::Logging.debug("kawari.rb: #{message}: #{segments[i]}")
809 end
810 end
811 result = values.join('')
812 Logging::Logging.debug(['>>>', segments[i]].join(''))
813 Logging::Logging.debug(['"', result, '"'].join(''))
814 return i, result
815 end
816
817 def split_commands(data)
818 i, segments = Kawari.parse(data, 0)
819 # find multiple commands separated by semicolons
820 buf = []
821 command = []
822 for segment in segments
823 if segment == ';'
824 unless command.empty?
825 buf << command
826 command = []
827 end
828 else
829 command << segment
830 end
831 end
832 unless command.empty?
833 buf << command
834 end
835 # strip white space before and after each command
836 for command in buf
837 if Kawari.is_space(command[0])
838 command.delete_at(0)
839 end
840 if Kawari.is_space(command[-1])
841 command.delete_at(-1)
842 end
843 end
844 return buf
845 end
846
847 def parse_argument(segments)
848 buf = [[]]
849 for segment in segments
850 if Kawari.is_space(segment)
851 buf << []
852 else
853 buf[-1] << segment
854 end
855 end
856 return buf
857 end
858
859 def exec_new_if(argv)
860 if argv.length == 3
861 return exec_if(argv[1], argv[2], nil)
862 elsif argv.length == 4
863 return exec_if(argv[1], argv[2], argv[3])
864 else
865 fail RuntimeError.new('syntax error')
866 end
867 end
868
869 def exec_old_if(if_block, then_block, else_block)
870 # convert [...] into $([...])
871 if not if_block.empty? and if_block.start_with?('[') and if_block.end_with?(']')
872 if_block = ['$(', if_block, ')'].join('')
873 end
874 # parse arguments
875 i, if_block = Kawari.parse(if_block, 0)
876 i, then_block = Kawari.parse(then_block, 0)
877 unless else_block.empty?
878 i, else_block = Kawari.parse(else_block, 0)
879 end
880 result = exec_if(if_block, then_block, else_block)
881 unless else_block.empty?
882 Logging::Logging.debug(
883 '>>> $(if ' + if_block.join('') + ')$(then ' + then_block.join('') + ')$(else ' + else_block.join('') + ')$(endif)')
884 else
885 Logging::Logging.debug(
886 '>>> $(if ' + if_block.join('') + ')$(then ' + then_block.join('') + ')$(endif)')
887 end
888 Logging::Logging.debug(['"', result, '"'].join(''))
889 return result
890 end
891
892 def exec_if(if_block, then_block, else_block)
893 if not ['', '0', 'false', 'False'].include?(expand(if_block))
894 return expand(then_block)
895 elsif not else_block.empty?
896 return expand(else_block)
897 end
898 return ''
899 end
900
901 def exec_foreach(argv)
902 if argv.length != 4
903 fail RuntimeError.new('syntax error')
904 end
905 temp = expand(argv[1])
906 name = expand(argv[2])
907 buf = []
908 for dic in @rdictlist
909 if dic.include?(name)
910 for segments in dic[name]
911 set(temp, expand(segments))
912 buf << expand(argv[3])
913 end
914 end
915 end
916 clear(temp)
917 return buf.join('')
918 end
919
920 def exec_loop(argv)
921 if argv.length != 3
922 fail RuntimeError.new('syntax error')
923 end
924 begin
925 n = Integer(expand(argv[1]))
926 rescue # except ValueError:
927 raise RuntimeError.new('invalid argument')
928 end
929 buf = []
930 for _ in 0..n-1
931 buf << expand(argv[2])
932 end
933 return buf.join('')
934 end
935
936 def exec_while(argv)
937 if argv.length != 3
938 fail RuntimeError.new('syntax error')
939 end
940 buf = []
941 while not ['', '0', 'false', 'False'].include?(expand(argv[1]))
942 buf << expand(argv[2])
943 end
944 return buf.join('')
945 end
946
947 def exec_until(argv)
948 if argv.length != 3
949 fail RuntimeError.new('syntax error')
950 end
951 buf = []
952 while ['', '0', 'false', 'False'].include?(expand(argv[1]))
953 buf << expand(argv[2])
954 end
955 return buf.join('')
956 end
957
958 def exec_set(argv)
959 if argv.length != 3
960 fail RuntimeError.new('syntax error')
961 end
962 set(expand(argv[1]), expand(argv[2]))
963 return ''
964 end
965
966 def exec_adddict(argv)
967 if argv.length != 3
968 fail RuntimeError.new('syntax error')
969 end
970 push(expand(argv[1]), expand(argv[2]))
971 return ''
972 end
973
974 def exec_array(argv) # XXX experimental
975 if argv.length != 3
976 fail RuntimeError.new('syntax error')
977 end
978 name = expand(argv[1])
979 n = atoi(expand(argv[2]))
980 for d in @rdictlist
981 c = (d.include?(name) ? d[name] : [])
982 if n < c.length
983 return c[n].map {|s| expand(s) }.join('')
984 end
985 n -= c.length
986 end
987 fail RuntimeError.new('invalid argument')
988 end
989
990 def exec_clear(argv)
991 if argv.length != 2
992 fail RuntimeError.new('syntax error')
993 end
994 clear(expand(argv[1]))
995 return ''
996 end
997
998 def exec_enumerate(argv)
999 if argv.length != 2
1000 fail RuntimeError.new('syntax error')
1001 end
1002 name = expand(argv[1])
1003 return enumerate(name).map {|s| expand(s) }.join(' ')
1004 end
1005
1006 def enumerate(name)
1007 buf = []
1008 for dic in @rdictlist
1009 if dic.include?(name)
1010 for segments in dic[name]
1011 buf << segments
1012 end
1013 end
1014 end
1015 return buf
1016 end
1017
1018 def exec_size(argv)
1019 if argv.length != 2
1020 fail RuntimeError.new('syntax error')
1021 end
1022 name = expand(argv[1])
1023 n = 0
1024 for d in @rdictlist
1025 c = (d.include?(name) ? d[name] : [])
1026 n += c.length
1027 end
1028 return n.to_s
1029 end
1030
1031 def exec_get(argv) # XXX experimental
1032 if argv.length != 3
1033 fail RuntimeError.new('syntax error')
1034 end
1035 name = expand(argv[1])
1036 n = atoi(expand(argv[2]))
1037 for d in @rdictlist
1038 c = (d.include?(name) ? d[name] : [])
1039 if n < c.length
1040 return c[n].join('')
1041 end
1042 n -= c.length
1043 end
1044 fail RuntimeError.new('invalid argument')
1045 end
1046
1047 def exec_unshift(argv)
1048 if argv.length != 3
1049 fail RuntimeError.new('syntax error')
1050 end
1051 unshift(expand(argv[1]), expand(argv[2]))
1052 return ''
1053 end
1054
1055 def exec_shift(argv)
1056 if argv.length != 2
1057 fail RuntimeError.new('syntax error')
1058 end
1059 return shift(expand(argv[1]))
1060 end
1061
1062 def exec_push(argv)
1063 if argv.length != 3
1064 fail RuntimeError.new('syntax error')
1065 end
1066 push(expand(argv[1]), expand(argv[2]))
1067 return ''
1068 end
1069
1070 def exec_pop(argv)
1071 if argv.length != 2
1072 fail RuntimeError.new('syntax error')
1073 end
1074 return pop(expand(argv[1]))
1075 end
1076
1077 def exec_pirocall(argv)
1078 fail RuntimeError.new('syntax error') if argv.length != 2
1079 selection = select_simple_phrase(expand(argv[1]))
1080 return '' if selection.nil?
1081 return selection[0]
1082 end
1083
1084 def exec_split(argv)
1085 fail RuntimeError.new('syntax error') if argv.length != 4
1086 name = expand(argv[1])
1087 word_list = expand(argv[2]).split(expand(argv[3]), 0)
1088 n = 0
1089 for word in word_list
1090 n += 1
1091 entry = (name.to_s + '.' + n.to_s)
1092 set(entry, word)
1093 end
1094 set([name, '.size'].join(''), n.to_s)
1095 return ''
1096 end
1097
1098 def get_dict_path(path)
1099 path = Home.get_normalized_path(path)
1100 fail RuntimeError.new('invalid argument') if path.nil?
1101 return path if path.start_with?('/')
1102 return File.join(@prefix, path)
1103 end
1104
1105 def exec_load(argv)
1106 if argv.length != 2
1107 fail RuntimeError.new('syntax error')
1108 end
1109 path = get_dict_path(expand(argv[1]))
1110 begin
1111 rdict, kdict = Kawari.create_dict(Kawari.read_dict(path))
1112 rescue #except IOError:
1113 raise RuntimeError.new('cannot read file')
1114 end
1115 if @pathlist.include?(path)
1116 i = @pathlist.index(path)
1117 @rdictlist[i].update(rdict)
1118 @kdictlist[i].update(kdict)
1119 else
1120 @pathlist.insert(0, path)
1121 @rdictlist.insert(0, rdict)
1122 @kdictlist.insert(0, kdict)
1123 end
1124 return ''
1125 end
1126
1127 def exec_save(argv, crypt: false)
1128 if argv.length < 2
1129 fail RuntimeError.new('syntax error')
1130 end
1131 path = get_dict_path(expand(argv[1]))
1132 begin
1133 open(path, 'wb') do |f|
1134 f.write("#\r\n# Kawari save file\r\n#\r\n")
1135 for i in 2..argv.length-1
1136 name = expand(argv[i])
1137 if name.strip.empty?
1138 next
1139 end
1140 buf = []
1141 for segments in enumerate(name)
1142 buf << segments.join('')
1143 end
1144 line = [name, ' : ', buf.join(' , ')].join('').encode($charset, :invalid => :replace, :undef => :replace)
1145 name = name.encode($charset, :invalid => :replace, :undef => :replace)
1146 if crypt
1147 line = Kawari.encrypt(line)
1148 end
1149 f.write(['# Entry ',
1150 name, "\r\n",
1151 line, "\r\n"].join(''))
1152 end
1153 end
1154 rescue #except IOError:
1155 raise RuntimeError.new('cannot write file')
1156 end
1157 return ''
1158 end
1159
1160 def exec_savecrypt(argv)
1161 return exec_save(argv, :crypt => true)
1162 end
1163
1164 def exec_textload(argv)
1165 if argv.length != 3
1166 fail RuntimeError.new('syntax error')
1167 end
1168 path = get_dict_path(expand(argv[1]))
1169 begin
1170 open(path, :encoding => $charset) do |f|
1171 linelist = f.readlines()
1172 end
1173 rescue #except IOError:
1174 raise RuntimeError.new('cannot read file')
1175 end
1176 name = expand(argv[2])
1177 n = 0
1178 for line in linelist
1179 n += 1
1180 entry = (name.to_s + '.' + n.to_s)
1181 if line.end_with?("\r\n")
1182 line = line[0..-3]
1183 elsif line.end_with?("\r") or line.end_with?("\n")
1184 line = line[0..-2]
1185 end
1186 if line.empty?
1187 clear(entry)
1188 else
1189 set(entry, line)
1190 end
1191 end
1192 set([name, '.size'].join(''), n.to_s)
1193 return ''
1194 end
1195
1196 def exec_escape(argv)
1197 data = argv[1..-1].map {|s| expand(s) }.join(' ')
1198 data = data.gsub('\\', '\\\\')
1199 data = data.gsub('%', '\%')
1200 return data
1201 end
1202
1203 def exec_echo(argv)
1204 return argv[1..-1].map {|s| expand(s) }.join(' ')
1205 end
1206
1207 def exec_tolower(argv)
1208 return exec_echo(argv).downcase
1209 end
1210
1211 def exec_toupper(argv)
1212 return exec_echo(argv).upcase
1213 end
1214
1215 def exec_eval(argv)
1216 return parse_all(exec_echo(argv))
1217 end
1218
1219 def exec_entry(argv)
1220 if argv.length == 2
1221 return get(expand(argv[1]))
1222 elsif argv.length == 3
1223 result = get(expand(argv[1]))
1224 unless result.empty?
1225 return result
1226 else
1227 return expand(argv[2])
1228 end
1229 else
1230 fail RuntimeError.new('syntax error')
1231 end
1232 end
1233
1234 def exec_null(argv)
1235 if argv.length != 1
1236 fail RuntimeError.new('syntax error')
1237 end
1238 return ''
1239 end
1240
1241 def exec_chr(argv)
1242 if argv.length != 2
1243 fail RuntimeError.new('syntax error')
1244 end
1245 num = atoi(expand(argv[1]))
1246 return num.chr if num < 256
1247 return [((num >> 8) & 0xff).chr, (num & 0xff).chr].join('')
1248 end
1249
1250 def exec_choice(argv)
1251 return '' if argv.length == 1
1252 i = rand(1..argv.length-1)
1253 return expand(argv[i])
1254 end
1255
1256 def exec_rand(argv)
1257 if argv.length != 2
1258 fail RuntimeError.new('syntax error')
1259 end
1260 bound = atoi(expand(argv[1]))
1261 if bound.zero?
1262 return 0.to_s
1263 elsif bound > 0
1264 return rand(0..bound-1).to_s
1265 else
1266 return rand(bound + 1..-1).to_s
1267 end
1268 end
1269
1270 def exec_date(argv)
1271 if argv.length == 1
1272 format_ = '%y/%m/%d %H:%M:%S'
1273 else
1274 format_ = argv[1..-1].map {|s| expand(s) }.join(' ')
1275 end
1276 buf = []
1277 i = 0
1278 j = format_.length
1279 now = Time.now
1280 while i < j
1281 if format_[i] == '%'
1282 i += 1
1283 if i < j
1284 c = format_[i]
1285 i += 1
1286 else
1287 break
1288 end
1289 case c
1290 when 'y', 'Y' # year (4 columns)
1291 buf << sprintf("%04d", now.year)
1292 when 'm' # month (01 - 12)
1293 buf << sprintf("%02d", now.month)
1294 when 'n' # month (1 - 12)
1295 buf << now.month.to_s
1296 when 'd' # day (01 - 31)
1297 buf << sprintf("%02d", now.day)
1298 when 'e' # day (1 - 31)
1299 buf << now.day.to_s
1300 when'H' # hour (00 - 23)
1301 buf << sprintf("%02d", now.hour)
1302 when 'k' # hour (0 - 23)
1303 buf << now.hour.to_s
1304 when 'M' # minute (00 - 59)
1305 buf << sprintf("%02d", now.min)
1306 when 'N' # minute (0 - 59)
1307 buf << now.min.to_s
1308 when 'S' # second (00 - 59)
1309 buf << sprintf("%02d", now.sec)
1310 when 'r' # second (0 - 59)
1311 buf << now.sec.to_s
1312 when 'w' # weekday (0 = Sunday)
1313 buf << now.wday.to_s
1314 when 'j' # Julian day (001 - 366)
1315 buf << sprintf("%03d", now.yday)
1316 when 'J' # Julian day (1 - 366)
1317 buf << now.yday.to_s
1318 when '%'
1319 buf << '%'
1320 else
1321 buf << '%'
1322 i -= 1
1323 end
1324 else
1325 buf << format_[i]
1326 i += 1
1327 end
1328 end
1329 return buf.join('')
1330 end
1331
1332 def exec_inc(argv)
1333 _inc = lambda {|value, step, bound|
1334 value += step
1335 return bound if not bound.nil? and value > bound
1336 return value
1337 }
1338 apply_counter_op(_inc, argv)
1339 return ''
1340 end
1341
1342 def exec_dec(argv)
1343 _dec = lambda {|value, step, bound|
1344 value -= step
1345 return bound if not bound.nil? and value < bound
1346 return value
1347 }
1348 apply_counter_op(_dec, argv)
1349 return ''
1350 end
1351
1352 def apply_counter_op(func, argv)
1353 if argv.length < 2 or argv.length > 4
1354 fail RuntimeError.new('syntax error')
1355 end
1356 name = expand(argv[1])
1357 value = atoi(get(name))
1358 if argv.length >= 3
1359 step = atoi(expand(argv[2]))
1360 else
1361 step = 1
1362 end
1363 if argv.length == 4
1364 bound = atoi(expand(argv[3]))
1365 else
1366 bound = nil
1367 end
1368 set(name, func.call(value, step, bound).to_s)
1369 end
1370
1371 def exec_test(argv)
1372 if argv[0] == 'test' and argv.length == 4 or \
1373 argv[0] == '[' and argv.length == 5 and expand(argv[4]) == ']'
1374 op1 = expand(argv[1])
1375 op = expand(argv[2])
1376 op2 = expand(argv[3])
1377 else
1378 fail RuntimeError.new('syntax error')
1379 end
1380 case op
1381 when '=', '=='
1382 result = (op1 == op2).to_s
1383 when '!='
1384 result = (op1 != op2).to_s
1385 when '<='
1386 result = (op1 <= op2).to_s
1387 when '>='
1388 result = (op1 >= op2).to_s
1389 when '<'
1390 result = (op1 < op2).to_s
1391 when '>'
1392 result = (op1 > op2).to_s
1393 when '-eq'
1394 result = (atoi(op1) == atoi(op2)).to_s
1395 when '-ne'
1396 result = (atoi(op1) != atoi(op2)).to_s
1397 when '-le'
1398 result = (atoi(op1) <= atoi(op2)).to_s
1399 when '-ge'
1400 result = (atoi(op1) >= atoi(op2)).to_s
1401 when '-lt'
1402 result = (atoi(op1) < atoi(op2)).to_s
1403 when '-gt'
1404 result = (atoi(op1) > atoi(op2)).to_s
1405 else
1406 fail RuntimeError.new('unknown operator')
1407 end
1408 return result
1409 end
1410
1411 def exec_expr(argv)
1412 tree = @expr_parser.parse(
1413 argv[1..-1].map {|e| e.join('') }.join(' '))
1414 fail RuntimeError.new('syntax error') if tree.nil?
1415 begin
1416 value = interp_expr(tree)
1417 rescue #except ExprError:
1418 raise RuntimeError.new('runtime error')
1419 end
1420 return value
1421 end
1422
1423 def interp_expr(tree)
1424 case tree[0]
1425 when ExprParser::OR_EXPR
1426 for subtree in tree[1..-1]
1427 value = interp_expr(subtree)
1428 break unless value.empty? or ['', '0', 'false', 'False'].include?(value)
1429 end
1430 return value
1431 when ExprParser::AND_EXPR
1432 buf = []
1433 for subtree in tree[1..-1]
1434 value = interp_expr(subtree)
1435 return '0' if value.empty? or ['', '0', 'false', 'False'].include?(value)
1436 buf << value
1437 end
1438 return buf[0]
1439 when ExprParser::CMP_EXPR
1440 op1 = interp_expr(tree[1])
1441 op2 = interp_expr(tree[3])
1442 if is_number(op1) and is_number(op2)
1443 op1 = Integer(op1)
1444 op2 = Integer(op2)
1445 end
1446 case tree[2]
1447 when '=', '=='
1448 return (op1 == op2).to_s
1449 when '!='
1450 return (op1 != op2).to_s
1451 when '<='
1452 return (op1 <= op2).to_s
1453 when '>='
1454 return (op1 >= op2).to_s
1455 when '<'
1456 return (op1 < op2).to_s
1457 when '>'
1458 return (op1 > op2).to_s
1459 else
1460 fail RuntimeError.new('unknown operator')
1461 end
1462 when ExprParser::ADD_EXPR
1463 for i in 1.step(tree.length-1, 2)
1464 tree[i] = interp_expr(tree[i])
1465 unless is_number(tree[i])
1466 fail ExprError
1467 end
1468 end
1469 value = Integer(tree[1])
1470 for i in 2.step(tree.length-1, 2)
1471 if tree[i] == '+'
1472 value += Integer(tree[i + 1])
1473 elsif tree[i] == '-'
1474 value -= Integer(tree[i + 1])
1475 end
1476 end
1477 return value.to_s
1478 when ExprParser::MUL_EXPR
1479 for i in 1.step(tree.length-1, 2)
1480 tree[i] = interp_expr(tree[i])
1481 unless is_number(tree[i])
1482 fail ExprError
1483 end
1484 end
1485 value = Integer(tree[1])
1486 for i in 2.step(tree.length-1, 2)
1487 if tree[i] == '*'
1488 value *= Integer(tree[i + 1])
1489 elsif tree[i] == '/'
1490 begin
1491 value /= Integer(tree[i + 1])
1492 value = value.to_i
1493 rescue # except ZeroDivisionError:
1494 raise ExprError
1495 end
1496 elsif tree[i] == '%'
1497 begin
1498 value = value % Integer(tree[i + 1])
1499 rescue # except ZeroDivisionError:
1500 raise ExprError
1501 end
1502 end
1503 end
1504 return value.to_s
1505 when ExprParser::STR_EXPR
1506 case tree[1]
1507 when 'length'
1508 length = get_characters(interp_expr(tree[2])).length
1509 return length.to_s
1510 when 'index'
1511 s = get_characters(interp_expr(tree[2]))
1512 c = get_characters(interp_expr(tree[3]))
1513 break_flag = false
1514 for pos in 0..s.length-1
1515 if c.include?(s[pos])
1516 break_flag = true
1517 break
1518 end
1519 end
1520 unless break_flag
1521 pos = 0
1522 end
1523 return pos.to_s
1524 when 'match'
1525 begin
1526 match = Regexp.new(interp_expr(tree[3])).match(interp_expr(tree[2]))
1527 rescue #except re.error:
1528 match = nil
1529 end
1530 unless match.nil?
1531 length = match.end(0) - match.begin(0)
1532 else
1533 length = 0
1534 end
1535 return length.to_s
1536 when 'find'
1537 s = interp_expr(tree[3])
1538 pos = nterp_expr(tree[2]).index(s)
1539 return '' if pos.nil? or pos < 0
1540 return s
1541 when 'findpos'
1542 s = interp_expr(tree[3])
1543 pos = interp_expr(tree[2]).find(s);
1544 return '' if pos.nil? or pos < 0
1545 return (pos + 1).to_s
1546 when 'substr'
1547 s = interp_expr(tree[2])
1548 p = interp_expr(tree[3])
1549 n = interp_expr(tree[4])
1550 if is_number(p) and is_number(n)
1551 p = Integer(p) - 1
1552 n = p + Integer(n)
1553 if 0 <= p and p <= n
1554 characters = get_characters(s)
1555 return characters[p..n-1].join('')
1556 end
1557 end
1558 return ''
1559 end
1560 when ExprParser::LITERAL
1561 return expand(tree[1..-1])
1562 end
1563 end
1564
1565 def get_characters(s)
1566 buf = []
1567 i = 0
1568 j = s.length
1569 while i < j
1570 buf << s[i]
1571 i += 1
1572 end
1573 return buf
1574 end
1575 end
1576
1577 ### EXPR PARSER ###
1578
1579 class ExprError < StandardError # ValueError
1580 #pass
1581 end
1582
1583
1584 class ExprParser
1585 attr_accessor :kawari
1586
1587 def initialize
1588 #pass
1589 @kawari = nil
1590 end
1591
1592 def show_progress(func, buf)
1593 if buf.nil?
1594 Logging::Logging.debug(func.to_s + '() -> syntax error')
1595 else
1596 Logging::Logging.debug(func.to_s + '() -> ' + buf.to_s)
1597 end
1598 end
1599
1600 Re_token = Regexp.new('\A([():|&*/%+-]|[<>]=?|[!=]?=|match|index|findpos|find|substr|length|quote|(\\s+))')
1601
1602 def tokenize(data)
1603 buf = []
1604 i = 0
1605 j = data.length
1606 while i < j
1607 match = Re_token.match(data[i..-1])
1608 unless match.nil?
1609 buf << match[0]
1610 i += match.end(0)
1611 else
1612 i, segments = Kawari.parse(data, i, :stop_pattern => Re_token)
1613 buf.concat(segments)
1614 end
1615 end
1616 return buf
1617 end
1618
1619 def parse(data)
1620 @tokens = tokenize(data)
1621 begin
1622 return get_expr()
1623 rescue #except ExprError:
1624 return nil # syntax error
1625 end
1626 end
1627
1628 # internal
1629 def done
1630 @tokens.empty?
1631 end
1632
1633 def pop
1634 begin
1635 return @tokens.shift
1636 rescue #except IndexError:
1637 raise ExprError
1638 end
1639 end
1640
1641 def look_ahead(index: 0)
1642 begin
1643 return @tokens[index]
1644 rescue #except IndexError:
1645 raise ExprError
1646 end
1647 end
1648
1649 def match(s)
1650 if pop() != s
1651 fail ExprError
1652 end
1653 end
1654
1655 def match_space
1656 unless Kawari.is_space(pop())
1657 fail ExprError
1658 end
1659 end
1660
1661 def check(s, index: 0)
1662 return (look_ahead(:index => index) == s)
1663 end
1664
1665 def check_space(index: 0)
1666 return Kawari.is_space(look_ahead(:index => index))
1667 end
1668
1669 # tree node types
1670 OR_EXPR = 1
1671 AND_EXPR = 2
1672 CMP_EXPR = 3
1673 ADD_EXPR = 4
1674 MUL_EXPR = 5
1675 STR_EXPR = 6
1676 LITERAL = 7
1677
1678 def get_expr
1679 buf = get_or_expr()
1680 unless done()
1681 fail ExprError
1682 end
1683 show_progress('get_expr', buf)
1684 return buf
1685 end
1686
1687 def get_or_expr
1688 buf = [OR_EXPR]
1689 while true
1690 buf << get_and_expr()
1691 if not done() and \
1692 check_space() and check('|', :index => 1)
1693 pop() # space
1694 pop() # operator
1695 match_space()
1696 else
1697 break
1698 end
1699 end
1700 if buf.length == 2
1701 buf = buf[1]
1702 end
1703 show_progress('get_or_expr', buf)
1704 return buf
1705 end
1706
1707 def get_and_expr
1708 buf = [AND_EXPR]
1709 while true
1710 buf << get_cmp_expr()
1711 if not done() and \
1712 check_space() and check('&', :index => 1)
1713 pop() # space
1714 pop() # operator
1715 match_space()
1716 else
1717 break
1718 end
1719 end
1720 if buf.length == 2
1721 buf = buf[1]
1722 end
1723 show_progress('get_and_expr', buf)
1724 return buf
1725 end
1726
1727 def get_cmp_expr
1728 buf = [CMP_EXPR]
1729 buf << get_add_expr()
1730 if not done() and \
1731 check_space() and \
1732 ['<=', '>=', '<', '>', '=', '==', '!='].include?(look_ahead(:index => 1))
1733 pop() # space
1734 buf << pop() # operator
1735 match_space()
1736 buf << get_add_expr()
1737 end
1738 if buf.length == 2
1739 buf = buf[1]
1740 end
1741 show_progress('get_cmp_expr', buf)
1742 return buf
1743 end
1744
1745 def get_add_expr
1746 buf = [ADD_EXPR]
1747 while true
1748 buf << get_mul_expr()
1749 if not done() and \
1750 check_space() and ['+', '-'].include?(look_ahead(:index => 1))
1751 pop() # space
1752 buf << pop() # operator
1753 match_space()
1754 else
1755 break
1756 end
1757 end
1758 if buf.length == 2
1759 buf = buf[1]
1760 end
1761 show_progress('get_add_expr', buf)
1762 return buf
1763 end
1764
1765 def get_mul_expr
1766 buf = [MUL_EXPR]
1767 while true
1768 buf << get_mat_expr()
1769 if not done() and \
1770 check_space() and ['*', '/', '%'].include?(look_ahead(:index => 1))
1771 pop() # space
1772 buf << pop() # operator
1773 match_space()
1774 else
1775 break
1776 end
1777 end
1778 if buf.length == 2
1779 buf = buf[1]
1780 end
1781 show_progress('get_mul_expr', buf)
1782 return buf
1783 end
1784
1785 def get_mat_expr
1786 buf = [STR_EXPR]
1787 buf << get_str_expr()
1788 if not done() and \
1789 check_space() and check(':', :index => 1)
1790 buf.insert(1, 'match')
1791 pop() # space
1792 pop() # ':'
1793 match_space()
1794 buf << get_str_expr()
1795 end
1796 if buf.length == 2
1797 buf = buf[1]
1798 end
1799 show_progress('get_mat_expr', buf)
1800 return buf
1801 end
1802
1803 def get_str_expr
1804 argc = 0
1805 if check('length')
1806 argc = 1
1807 elsif ['match', 'index', 'find', 'findpos'].include?(look_ahead())
1808 argc = 2
1809 elsif check('substr')
1810 argc = 3
1811 end
1812 if argc > 0
1813 buf = [STR_EXPR, pop()] # fuction
1814 for _ in 0..argc-1
1815 match_space()
1816 buf << get_str_expr()
1817 end
1818 elsif check('quote')
1819 buf = [LITERAL]
1820 pop()
1821 match_space()
1822 if Re_token.match(look_ahead())
1823 buf << pop()
1824 else
1825 buf.concat(get_str_seq())
1826 end
1827 else
1828 buf = get_sub_expr()
1829 end
1830 show_progress('get_str_expr', buf)
1831 return buf
1832 end
1833
1834 def get_sub_expr
1835 if check('(')
1836 pop()
1837 if check_space()
1838 pop()
1839 end
1840 buf = get_or_expr()
1841 if check_space()
1842 pop()
1843 end
1844 #begin specification bug work-around (3/3)
1845 @tokens[0] = @kawari.parse_all(@tokens[0])
1846 #end
1847 match(')')
1848 else
1849 buf = [LITERAL]
1850 buf.concat(get_str_seq())
1851 end
1852 show_progress('get_sub_expr', buf)
1853 return buf
1854 end
1855
1856 def get_str_seq
1857 buf = []
1858 while not done() and \
1859 Re_token.match(look_ahead()).nil?
1860 buf << pop()
1861 end
1862 if buf.empty?
1863 fail ExprError
1864 end
1865 return buf
1866 end
1867 end
1868
1869 # <<< EXPR SYNTAX >>>
1870 # expr := or-expr
1871 # or-expr := and-expr (sp or-op sp and-expr)*
1872 # or-op := '|'
1873 # and-expr := cmp-expr (sp and-op sp cmp-expr)*
1874 # and-op := '&'
1875 # cmp-expr := add-expr (sp cmp-op sp add-expr)?
1876 # cmp-op := <= | >= | < | > | == | = | !=
1877 # add-expr := mul-expr (sp add-op sp mul-expr)*
1878 # add-op := '+' | '-'
1879 # mul-expr := mat-expr (sp mul-op sp mat-expr)*
1880 # mul-op := '*' | '/' | '%'
1881 # mat-expr := str-expr (sp ':' sp str-expr)?
1882 # str-expr := 'quote' sp (OPERATOR | str-seq) |
1883 # 'match' sp str-expr sp str-expr |
1884 # 'index' sp str-expr sp str-expr |
1885 # 'find' sp str-expr sp str-expr |
1886 # 'findpos' sp str-expr sp str-expr |
1887 # 'substr' sp str-expr sp str-expr sp str-expr |
1888 # 'length' sp str-expr |
1889 # sub-expr
1890 # sub-expr := '(' sp? or-expr sp? ')' | str-seq
1891 # sp := SPACE+ (white space)
1892 # str-seq := STRING+ (literal, "...", ${...}, and/or $(...))
1893
1894
1895 ### API ###
1896
1897 DICT_FILE, INI_FILE = Array(0..1)
1898
1899 def self.list_dict(kawari_dir, saori_ini: {})
1900 return Kawari.scan_ini(kawari_dir, 'kawari.ini', saori_ini)
1901 end
1902
1903 def self.scan_ini(kawari_dir, filename, saori_ini)
1904 buf = []
1905 ini_path = File.join(kawari_dir, filename)
1906 begin
1907 line_list = Kawari.read_dict(ini_path)
1908 rescue #except IOError:
1909 line_list = []
1910 end
1911 read_as_dict = false
1912 for entry, value, position in line_list
1913 if entry == 'dict'
1914 filename = Home.get_normalized_path(value)
1915 path = File.join(kawari_dir, filename)
1916 begin
1917 open(path, 'rb') do |f|
1918 f.read(64)
1919 end
1920 rescue #except IOError as e:
1921 ##errno, message = e.args
1922 Logging::Logging.debug('kawari.rb: read error: ' + path.to_s)
1923 next
1924 end
1925 buf << [DICT_FILE, path]
1926 elsif entry == 'include'
1927 filename = Home.get_normalized_path(value)
1928 buf.concat(Kawari.scan_ini(kawari_dir, filename, saori_ini))
1929 elsif entry == 'set'
1930 read_as_dict = true
1931 elsif ['randomseed', 'debug', 'security', 'set'].include?(entry)
1932 #pass
1933 elsif entry == 'saori'
1934 saori_list = value.split(',', 0)
1935 path = saori_list[0].strip()
1936 alias_ = saori_list[1].strip()
1937 if saori_list.length == 3
1938 option = saori_list[2].strip()
1939 else
1940 option = 'loadoncall'
1941 end
1942 saori_ini[alias_] = [path, option]
1943 else
1944 Logging::Logging.debug('kawari.rb: unknown entry: ' + entry.to_s)
1945 end
1946 end
1947 if read_as_dict
1948 buf << [INI_FILE, ini_path]
1949 end
1950 return buf
1951 end
1952
1953 def self.read_ini(path)
1954 buf = []
1955 begin
1956 line_list = Kawari.read_dict(path)
1957 rescue #except IOError:
1958 line_list = []
1959 end
1960 for entry, value, position in line_list
1961 if entry == 'set'
1962 begin
1963 entry, value = value.split(nil, 2)
1964 rescue #except ValueError:
1965 next
1966 end
1967 buf << [entry.strip(), value.strip(), position]
1968 end
1969 end
1970 return buf
1971 end
1972
1973
1974 class Shiori < Kawari7
1975
1976 def initialize(dll_name)
1977 @dll_name = dll_name
1978 @saori_list = {}
1979 @saori_ini = {}
1980 end
1981
1982 def use_saori(saori)
1983 @saori = saori
1984 end
1985
1986 def load(dir: nil)
1987 @kawari_dir = dir
1988 pathlist = [nil]
1989 rdictlist = [{}]
1990 kdictlist = [{}]
1991 @saori_ini = {}
1992 for file_type, path in Kawari.list_dict(@kawari_dir, :saori_ini => @saori_ini)
1993 pathlist << path
1994 if file_type == INI_FILE
1995 rdict, kdict = Kawari.create_dict(Kawari.read_ini(path))
1996 elsif Kawari.is_local_script(path)
1997 rdict, kdict = Kawari.read_local_script(path)
1998 else
1999 rdict, kdict = Kawari.create_dict(Kawari.read_dict(path))
2000 end
2001 rdictlist << rdict
2002 kdictlist << kdict
2003 end
2004 kawari_init(@kawari_dir, pathlist, rdictlist, kdictlist)
2005 for value in @saori_ini.values()
2006 if value[1] == 'preload'
2007 head, tail = File.split(value[0].gsub('\\', '/'))
2008 saori_load(value[0], File.join(@kawari_dir, head))
2009 end
2010 end
2011 @kis_commands['saoriregist'] = 'exec_saoriregist'
2012 @kis_commands['saorierase'] = 'exec_saorierase'
2013 @kis_commands['callsaori'] = 'exec_callsaori'
2014 @kis_commands['callsaorix'] = 'exec_callsaorix'
2015 return 1
2016 end
2017
2018 def unload
2019 finalize
2020 for name in @saori_list.keys()
2021 @saori_list[name].unload()
2022 @saori_list.delete(name)
2023 end
2024 $charset = 'CP932' # reset
2025 end
2026
2027 def find(dir, dll_name)
2028 result = 0
2029 unless Kawari.list_dict(dir).empty?
2030 result = 200
2031 end
2032 $charset = 'CP932' # reset
2033 return result
2034 end
2035
2036 def show_description
2037 Logging::Logging.info(
2038 "Shiori: KAWARI compatible module for ninix\n" \
2039 " Copyright (C) 2001, 2002 by Tamito KAJIYAMA\n" \
2040 " Copyright (C) 2002, 2003 by MATSUMURA Namihiko\n" \
2041 " Copyright (C) 2002-2019 by Shyouzou Sugitani\n" \
2042 " Copyright (C) 2003 by Shun-ichi TAHARA")
2043 end
2044
2045 def request(req_string)
2046 header = req_string.force_encoding($charset).encode("UTF-8", :invalid => :replace, :undef => :replace).split(/\r?\n/, 0)
2047 req_header = {}
2048 unless header.empty?
2049 line = header.shift
2050 line = line.strip()
2051 req_list = line.split(nil, -1)
2052 if req_list.length >= 2
2053 command = req_list[0].strip()
2054 protocol = req_list[1].strip()
2055 end
2056 for line in header
2057 line = line.strip()
2058 next if line.empty?
2059 next unless line.include?(':')
2060 key, value = line.split(':', 2)
2061 key.strip!
2062 value.strip!
2063 begin
2064 value = Integer(value)
2065 rescue
2066 value = value.to_s
2067 end
2068 req_header[key] = value
2069 end
2070 end
2071 result = ''
2072 to = nil
2073 if req_header.include?('ID')
2074 if req_header['ID'] == 'dms'
2075 result = getdms()
2076 elsif req_header['ID'] == 'OnAITalk'
2077 result = getaistringrandom()
2078 elsif ['\\ms', '\\mz', '\\ml', '\\mc', '\\mh', \
2079 '\\mt', '\\me', '\\mp'].include?(req_header['ID'])
2080 result = getword(req_header['ID'][1..-1])
2081 elsif req_header['ID'] == '\\m?'
2082 result = getword('m')
2083 elsif req_header['ID'] == 'otherghostname'
2084 otherghost = []
2085 for n in 0..127
2086 key = ['Reference', n.to_s].join('')
2087 if req_header.include?(key)
2088 otherghost << req_header[key]
2089 end
2090 end
2091 result = otherghostname(otherghost)
2092 elsif req_header['ID'] == 'OnTeach'
2093 if req_header.include?('Reference0')
2094 teach(req_header['Reference0'])
2095 end
2096 else
2097 result = getstring(req_header['ID'])
2098 if result.empty?
2099 ref = []
2100 for n in 0..7
2101 key = ['Reference', n.to_s].join('')
2102 if req_header.include?(key)
2103 ref << req_header[key]
2104 else
2105 ref << nil
2106 end
2107 end
2108 ref0, ref1, ref2, ref3, ref4, ref5, ref6, ref7 = ref
2109 result = get_event_response(
2110 req_header['ID'],
2111 :ref0 => ref0, :ref1 => ref1, :ref2 => ref2, :ref3 => ref3,
2112 :ref4 => ref4, :ref5 => ref5, :ref6 => ref6, :ref7 => ref7)
2113 end
2114 end
2115 if result.nil?
2116 result = ''
2117 end
2118 to = communicate_to()
2119 end
2120 result = ("SHIORI/3.0 200 OK\r\n" \
2121 "Sender: Kawari\r\n" \
2122 "Charset: " + $charset.to_s + "\r\n" \
2123 "Value: " + result.to_s + "\r\n")
2124 unless to.nil?
2125 result = [result, "Reference0: " + to.to_s + "\r\n"].join('')
2126 end
2127 result = [result, "\r\n"].join('')
2128 return result.encode($charset, :invalid => :replace, :undef => :replace)
2129 end
2130
2131 def exec_saoriregist(kawari, argv)
2132 filename = expand(argv[1])
2133 alias_ = expand(argv[2])
2134 if argv.length == 4
2135 option = expand(argv[3])
2136 else
2137 option = 'loadoncall'
2138 end
2139 @saori_ini[alias_] = [filename, option]
2140 if @saori_ini[alias_][1] == 'preload'
2141 head, tail = File.split(
2142 @saori_ini[alias_][0].gsub('\\', '/'))
2143 saori_load(@saori_ini[alias_][0],
2144 File.join(@kawari_dir, head))
2145 end
2146 return ''
2147 end
2148
2149 def exec_saorierase(kawari, argv)
2150 alias_ = expand(argv[1])
2151 if @saori_ini.include?(alias_)
2152 saori_unload(@saori_ini[alias_][0])
2153 end
2154 return ''
2155 end
2156
2157 def exec_callsaori(kawari, argv)
2158 alias_ = expand(argv[1])
2159 return '' unless @saori_ini.include?(alias_)
2160 unless @saori_list.include?(@saori_ini[alias_][0])
2161 if @saori_ini[alias_][1] == 'preload'
2162 return ''
2163 else
2164 head, tail = File.split(
2165 @saori_ini[alias_][0].gsub('\\', '/'))
2166 saori_load(@saori_ini[alias_][0],
2167 File.join(@kawari_dir, head))
2168 end
2169 end
2170 saori_statuscode = ''
2171 saori_header = []
2172 saori_value = {}
2173 saori_protocol = ''
2174 req = ("EXECUTE SAORI/1.0\r\n" \
2175 "Sender: KAWARI\r\n" \
2176 "SecurityLevel: local\r\n" \
2177 "Charset: " + $charset.to_s + "\r\n")
2178 for i in 2..argv.length-1
2179 req = [req,
2180 "Argument" + (i - 2).to_s + ": " + expand(argv[i]).to_s + "\r\n"].join('')
2181 end
2182 req = [req, "\r\n"].join('')
2183 response = saori_request(@saori_ini[alias_][0],
2184 req.encode($charset, :invalid => :replace, :undef => :replace))
2185 header = response.splitlines()
2186 unless header.empty?
2187 line = header.shift
2188 line = line.strip()
2189 if line.include?(' ')
2190 saori_protocol, saori_statuscode = line.split(' ', 2)
2191 saori_protocol.strip!
2192 saori_statuscode.strip!
2193 end
2194 for line in header
2195 line = line.strip()
2196 next if line.empty?
2197 next unless line.include?(':')
2198 key, value = line.split(':', 2)
2199 key.strip!
2200 value.strip!
2201 unless key.empty?
2202 saori_header << key
2203 saori_value[key] = value
2204 end
2205 end
2206 end
2207 if saori_value.include?('Result')
2208 result = saori_value['Result']
2209 else
2210 result = ''
2211 end
2212 if @saori_ini[alias_][1] == 'noresident'
2213 saori_unload(@saori_ini[alias_][0])
2214 end
2215 return result
2216 end
2217
2218 def exec_callsaorix(kawari, argv)
2219 alias_ = expand(argv[1])
2220 entry = expand(argv[2])
2221 return '' unless @saori_ini.include?(alias_)
2222 unless @saori_list.include?(@saori_ini[alias_][0])
2223 if @saori_ini[alias_][1] == 'preload'
2224 return ''
2225 else
2226 head, tail = File.split(
2227 @saori_ini[alias_][0].gsub('\\', '/'))
2228 saori_load(@saori_ini[alias_][0],
2229 File.join(@kawari_dir, head))
2230 end
2231 end
2232 saori_statuscode = ''
2233 saori_header = []
2234 saori_value = {}
2235 saori_protocol = ''
2236 req = ("EXECUTE SAORI/1.0\r\n" \
2237 "Sender: KAWARI\r\n" \
2238 "SecurityLevel: local\r\n")
2239 for i in 3..argv.length-1
2240 req = [req,
2241 "Argument" + (i -3).to_s + ": " + expand(argv[i]) + "\r\n"].join('')
2242 end
2243 req = [req, "\r\n"].join('')
2244 response = saori_request(@saori_ini[alias_][0],
2245 req.encode($charset, :invalid => :replace, :undef => :replace))
2246 header = response.splitlines()
2247 unless header.empty?
2248 line = header.shift
2249 line = line.strip()
2250 if line.include?(' ')
2251 saori_protocol, saori_statuscode = line.split(' ', 2)
2252 saori_protocol.strip!
2253 saori_statuscode.strip1
2254 end
2255 for line in header
2256 line = line.strip()
2257 next if line.empty?
2258 next unless line.include?(':')
2259 key, value = line.split(':', 2)
2260 key.strip!
2261 value.strip!
2262 unless key.empty?
2263 saori_header << key
2264 saori_value[key] = value
2265 end
2266 end
2267 end
2268 result = {}
2269 for key, value in saori_value
2270 if key.start_with?('Value')
2271 result[key] = value
2272 end
2273 end
2274 for key, value in result
2275 set([entry, '.', key].join(''), value)
2276 end
2277 if @saori_ini[alias_][1] == 'noresident'
2278 saori_unload(@saori_ini[alias_][0])
2279 end
2280 return result.length
2281 end
2282
2283 def saori_load(saori, path)
2284 result = 0
2285 if @saori_list.keys().include?(saori)
2286 result = @saori_list[saori].load(:dir => path)
2287 else
2288 module_ = @saori.request(saori)
2289 unless module_.nil?
2290 @saori_list[saori] = module_
2291 result = @saori_list[saori].load(:dir => path)
2292 end
2293 end
2294 return result
2295 end
2296
2297 def saori_unload(saori)
2298 result = 0
2299 if @saori_list.keys().include?(saori)
2300 result = @saori_list[saori].unload()
2301 end
2302 return result
2303 end
2304
2305 def saori_request(saori, req)
2306 result = 'SAORI/1.0 500 Internal Server Error'
2307 if @saori_list.include?(saori)
2308 result = @saori_list[saori].request(req)
2309 end
2310 return result
2311 end
2312 end
2313
2314 def self.is_local_script(path)
2315 line = ''
2316 open(path, 'rb') do |f|
2317 line = f.readline()
2318 end
2319 return line.start_with?('[SAKURA]')
2320 end
2321 end