diff options
Diffstat (limited to 'sample')
-rw-r--r-- | sample/README | 60 | ||||
-rw-r--r-- | sample/cal.rb | 118 | ||||
-rw-r--r-- | sample/fib.py | 10 | ||||
-rw-r--r-- | sample/fib.scm | 4 | ||||
-rw-r--r-- | sample/freq.rb | 8 | ||||
-rw-r--r-- | sample/from.rb | 36 | ||||
-rw-r--r-- | sample/goodfriday.rb | 48 | ||||
-rw-r--r-- | sample/mkproto.rb | 8 | ||||
-rw-r--r-- | sample/observ.rb | 15 | ||||
-rw-r--r-- | sample/occur.rb | 8 | ||||
-rw-r--r-- | sample/rbc.rb | 257 | ||||
-rw-r--r-- | sample/sieve.rb | 3 | ||||
-rw-r--r-- | sample/test.rb | 218 | ||||
-rw-r--r-- | sample/trojan.rb | 4 | ||||
-rw-r--r-- | sample/tsvr.rb | 2 |
15 files changed, 631 insertions, 168 deletions
diff --git a/sample/README b/sample/README new file mode 100644 index 0000000000..90ac0c7220 --- /dev/null +++ b/sample/README @@ -0,0 +1,60 @@ +README this file +biorhythm.rb biorhythm calculator +cal.rb cal(1) clone +cbreak.rb no echo done by ioctl +clnt.rb socket client +dbmtest.rb test for dbm +dir.rb directory access +dstore.rb object database on dbm +eval.rb simple evaluator +export.rb method access example +exyacc.rb extrace BNF from yacc file +fact.rb factorial calculator +fib.awk Fibonacci number (AWK) +fib.pl Fibonacci number (Perl) +fib.py Fibonacci number (Python) +fib.rb Fibonacci number (Ruby) +fib.scm Fibonacci number (Scheme) +freq.rb count word occurrence +from.rb scan mail spool +fullpath.rb convert ls -lR to fullpath format +getopts.test test fot getopt.rb +goodfriday.rb print various christian calendar event. +inf-ruby.el program to run ruby under emacs +io.rb io test +less.rb front end for less +list.rb stupid object sample +list2.rb stupid object sample +list3.rb stupid object sample +mine.rb simple mine sweeper +mkproto.rb extract protptype from C +mpart.rb split file int multi part +mrshtest.rb test marshal +observ.rb observer design pattern sample +occur.pl count word occurrence (Perl) +occur.rb count word occurrence (Ruby) +occur2.rb count word occurrence - another style +philos.rb famous dining philosophers +pi.rb calculate PI +rbc.rb interactive ruby, to be removed by irb +rcs.awk random character stereogram (AWK) +rcs.rb random character stereogram (Ruby) +rcs.dat data for random character stereogram +regx.rb regular expression tester +ruby-mode.el ruby mode for emacs +rubydb2x.el ruby debugger support for emacs 19.2x or before +rubydb3x.el ruby debugger support for emacs 19.3x or later +sieve.rb sieve of Eratosthenes +svr.rb socket server +test.rb test suite used by `make test' +time.rb /usr/bin/time clone +tkbiff.rb mail notifier using Tk +tkbrowse.rb directory browser using Tk +tkdialog.rb dialog example +tkfrom.rb scan mail spool using Tk +tkhello.rb simple Tk example +tkline.rb simple Tk example +tktimer.rb stopwatch +trojan.rb simple tool to find file that may be trojan horse. +tsvr.rb socket server using thread +uumerge.rb merge files and uudecode them diff --git a/sample/cal.rb b/sample/cal.rb new file mode 100644 index 0000000000..a5f4b4db18 --- /dev/null +++ b/sample/cal.rb @@ -0,0 +1,118 @@ +#! /usr/local/bin/ruby + +# cal.rb (bsd compatible version): Written by Tadayoshi Funaba 1998 +# $Id: bsdcal.rb,v 1.2 1998/12/01 13:47:40 tadf Exp $ + +require 'date2' + +$tab = +{ + 'cn' => true, # China + 'de' => 2342032, # Germany (protestant states) + 'dk' => 2342032, # Denmark + 'es' => 2299161, # Spain + 'fi' => 2361390, # Finland + 'fr' => 2299227, # France + 'gb' => 2361222, # United Kingdom + 'gr' => 2423868, # Greece + 'hu' => 2301004, # Hungary + 'it' => 2299161, # Italy + 'jp' => true, # Japan + 'no' => 2342032, # Norway + 'pl' => 2299161, # Poland + 'pt' => 2299161, # Portugal + 'ru' => 2421639, # Russia + 'se' => 2361390, # Sweden + 'us' => 2361222, # United States + 'os' => false, # (old style) + 'ns' => true # (new style) +} + +$cc = 'gb' + +def usage + $stderr.puts 'usage: cal [-c iso3166] [-jy] [[month] year]' + exit 1 +end + +def cal(m, y, gs) + for d in 1..31 + break if jd = Date.exist?(y, m, d, gs) + end + fst = cur = Date.new(jd, gs) + ti = Date::MONTHNAMES[m] + ti << ' ' << y.to_s unless $yr + mo = ti.center((($w + 1) * 7) - 1) << "\n" + mo << ['S', 'M', 'Tu', 'W', 'Th', 'F', 'S']. + collect{|x| x.rjust($w)}.join(' ') << "\n" + mo << ' ' * (($w + 1) * fst.wday) + while cur.mon == fst.mon + mo << (if $jd then cur.yday else cur.mday end).to_s.rjust($w) + mo << (if (cur += 1).wday != 0 then "\s" else "\n" end) + end + mo << "\n" * (6 - ((fst.wday + (cur - fst)) / 7)) + mo +end + +def zip(xs) + yr = '' + until xs.empty? + ln = (if $jd then l, r, *xs = xs; [l, r] + else l, c, r, *xs = xs; [l, c, r] end). + collect{|x| x.split(/\n/no, -1)} + 8.times do + yr << ln.collect{|x| + x.shift.ljust((($w + 1) * 7) - 1)}.join(' ') << "\n" + end + end + yr +end + +while /^-(.*)$/no =~ $*[0] + a = $1 + if /^c(.+)?$/no =~ a then + if $1 then + $cc = $1.downcase + elsif $*.length >= 2 then + $cc = $*[1].downcase + $*.shift + else + usage + end + else + a.scan(/./no) do |c| + case c + when 'j'; $jd = true + when 'y'; $yr = true + else usage + end + end + end + $*.shift +end +usage if (gs = $tab[$cc]).nil? +case $*.length +when 0 + td = Date.today + m = td.mon + y = td.year +when 1 + y = $*[0].to_i + $yr = true +when 2 + m = $*[0].to_i + y = $*[1].to_i +else + usage +end +usage unless m.nil? or (1..12) === m +usage unless y >= -4712 +$w = if $jd then 3 else 2 end +unless $yr then + print cal(m, y, gs) +else + print y.to_s.center(((($w + 1) * 7) - 1) * + (if $jd then 2 else 3 end) + + (if $jd then 2 else 4 end)), "\n\n", + zip((1..12).collect{|m| cal(m, y, gs)}), "\n" +end diff --git a/sample/fib.py b/sample/fib.py new file mode 100644 index 0000000000..8318021d24 --- /dev/null +++ b/sample/fib.py @@ -0,0 +1,10 @@ +# calculate Fibonacci(20) +# for benchmark +def fib(n): + if n<2: + return n + else: + return fib(n-2)+fib(n-1) + +print fib(20) + diff --git a/sample/fib.scm b/sample/fib.scm index 8eba75bb9e..5c2b86e656 100644 --- a/sample/fib.scm +++ b/sample/fib.scm @@ -3,4 +3,6 @@ n (+ (fib (- n 2)) (fib (- n 1))))) -(fib 20) +(display (fib 20)) +(newline) + diff --git a/sample/freq.rb b/sample/freq.rb index d951591735..4e0206c114 100644 --- a/sample/freq.rb +++ b/sample/freq.rb @@ -1,13 +1,13 @@ # word occurrence listing # usege: ruby freq.rb file.. -freq = {} +freq = Hash.new(0) while gets while sub!(/\w+/, '') word = $& - freq[word] +=1 + freq[word] += 1 end end -for word in freq.keys.sort - printf("%s -- %d\n", word, freq[word]) +for word in freq.keys.sort! + print word, " -- ", freq[word], "\n" end diff --git a/sample/from.rb b/sample/from.rb index d39bb70084..93b6c4bade 100644 --- a/sample/from.rb +++ b/sample/from.rb @@ -9,8 +9,6 @@ include Kconv class String - public :kconv - def kconv(code = Kconv::EUC) Kconv.kconv(self, code, Kconv::AUTO) end @@ -32,13 +30,20 @@ if ARGV[0] == '-w' end if ARGV.length == 0 - user = ENV['USER'] + file = ENV['MAIL'] + user = ENV['USER'] || ENV['USERNAME'] || ENV['LOGNAME'] else - user = ARGV[0] + file = user = ARGV[0] + ARGV.clear end -[ENV['SPOOLDIR'], '/usr/spool', '/var/spool', '/usr', '/var'].each do |m| - break if File.exist? ARGV[0] = "#{m}/mail/#{user}" +if file == nil or !File.exist? file + [ENV['SPOOLDIR'], '/usr/spool', '/var/spool', '/usr', '/var'].each do |m| + if File.exist? f = "#{m}/mail/#{user}" + file = f + break + end + end end $outcount = 0; @@ -63,18 +68,23 @@ def fromout(date, from, subj) end from = from.kconv(lang).kjust(28) subj = subj.kconv(lang).kjust(40) - printf "%02d/%02d/%02d [%s] %s\n",y,m,d,from,subj + printf "%02d/%02d/%02d [%s] %s\n",y%100,m,d,from,subj $outcount += 1 end -for file in ARGV - next if !File.exist?(file) +if File.exist?(file) + atime = File.atime(file) + mtime = File.mtime(file) f = open(file, "r") - while !f.eof? - mail = Mail.new(f) - fromout mail.header['Date'], mail.header['From'], mail.header['Subject'] + begin + until f.eof? + mail = Mail.new(f) + fromout mail.header['Date'],mail.header['From'],mail.header['Subject'] + end + ensure + f.close + File.utime(atime, mtime, file) end - f.close end if $outcount == 0 diff --git a/sample/goodfriday.rb b/sample/goodfriday.rb new file mode 100644 index 0000000000..f0027ec5dd --- /dev/null +++ b/sample/goodfriday.rb @@ -0,0 +1,48 @@ +#! /usr/local/bin/ruby + +# goodfriday.rb: Written by Tadayoshi Funaba 1998 +# $Id: goodfriday.rb,v 1.1 1998/03/08 09:44:44 tadf Exp $ + +require 'date2' + +def easter(y) + g = (y % 19) + 1 + c = (y / 100) + 1 + x = (3 * c / 4) - 12 + z = ((8 * c + 5) / 25) - 5 + d = (5 * y / 4) - x - 10 + e = (11 * g + 20 + z - x) % 30 + e += 1 if e == 25 and g > 11 or e == 24 + n = 44 - e + n += 30 if n < 21 + n = n + 7 - ((d + n) % 7) + if n <= 31 then [y, 3, n] else [y, 4, n - 31] end +end + +es = Date.new3(*easter(Time.now.year)) +[[-9*7, 'Septuagesima Sunday'], + [-8*7, 'Sexagesima Sunday'], + [-7*7, 'Quinquagesima Sunday (Shrove Sunday)'], + [-48, 'Shrove Monday'], + [-47, 'Shrove Tuesday'], + [-46, 'Ash Wednesday'], + [-6*7, 'Quadragesima Sunday'], + [-3*7, 'Mothering Sunday'], + [-2*7, 'Passion Sunday'], + [-7, 'Palm Sunday'], + [-3, 'Maunday Thursday'], + [-2, 'Good Friday'], + [-1, 'Easter Eve'], + [0, 'Easter Day'], + [1, 'Easter Monday'], + [7, 'Low Sunday'], + [5*7, 'Rogation Sunday'], + [39, 'Ascension Day (Holy Thursday)'], + [42, 'Sunday after Ascension Day'], + [7*7, 'Pentecost (Whitsunday)'], + [50, 'Whitmonday'], + [8*7, 'Trinity Sunday'], + [60, 'Corpus Christi (Thursday after Trinity)']]. +each do |xs| + puts ((es + xs.shift).to_s + ' ' + xs.shift) +end diff --git a/sample/mkproto.rb b/sample/mkproto.rb index 97006f9f54..8661240085 100644 --- a/sample/mkproto.rb +++ b/sample/mkproto.rb @@ -8,17 +8,17 @@ while gets() arg.gsub! ' +', ' ' if arg =~ /,/ if arg =~ /(([^*]+) *\** *[\w\d_]+),/ - type = $2.strip! - args.push $1.strip! + type = $2.strip + args.push $1.strip arg = $' else type = "" end while arg.sub!(/(\** *[\w\d_]+)(,|$)/, "") - args.push type + " " + $1.strip! + args.push type + " " + $1.strip end else - args.push arg.strip! + args.push arg.strip end end printf "%s);\n", args.join(', ') diff --git a/sample/observ.rb b/sample/observ.rb index f7b1e73137..72e5178b38 100644 --- a/sample/observ.rb +++ b/sample/observ.rb @@ -7,25 +7,26 @@ class Tick include Observable def initialize Thread.start do - while TRUE + loop do sleep 0.999 + now = Time.now changed - notify_observers(Time.now.strftime("%H:%M:%S")) + notify_observers(now.hour, now.min, now.sec) end end end end class Clock - def initialize - @tick = Tick.new + def initialize(tick) + @tick = tick @tick.add_observer(self) end - def update(time) - print "\e[8D", time + def update(h, m, s) + printf "\e[8D%02d:%02d:%02d", h, m, s STDOUT.flush end end -clock = Clock.new +clock = Clock.new(Tick.new) sleep diff --git a/sample/occur.rb b/sample/occur.rb index 2141fade38..f489beee17 100644 --- a/sample/occur.rb +++ b/sample/occur.rb @@ -1,12 +1,12 @@ # word occurrence listing # usege: ruby occur.rb file.. -freq = {} +freq = Hash.new(0) while gets() for word in $_.split(/\W+/) - freq[word] +=1 + freq[word] += 1 end end -for word in freq.keys.sort - printf("%s -- %d\n", word, freq[word]) +for word in freq.keys.sort! + print word, " -- ", freq[word], "\n" end diff --git a/sample/rbc.rb b/sample/rbc.rb index 88a5b2d069..83796255cc 100644 --- a/sample/rbc.rb +++ b/sample/rbc.rb @@ -1,9 +1,9 @@ #!/usr/local/bin/ruby # # rbc.rb - -# $Release Version: 0.6 $ -# $Revision: 1.2 $ -# $Date: 1997/11/27 13:46:06 $ +# $Release Version: 0.8 $ +# $Revision: 1.8 $ +# $Date: 1998/03/11 05:43:00 $ # by Keiju ISHITSUKA(Nippon Rational Inc.) # # -- @@ -11,46 +11,46 @@ # # rbc.rb [options] file_name opts # options: -# -d デバッグモード(利用しない方が良いでしょう) -# -m bcモード(分数, 行列の計算ができます) -# -r load-module ruby -r と同じ -# --inspect 結果出力にinspectを用いる(bcモード以外はデ -# フォルト). -# --noinspect 結果出力にinspectを用いない. -# --noreadline readlineライブラリを利用しない(デフォルト -# ではreadlineライブラリを利用しようとする). +# -d debug mode (not recommended) +# -f does not read ~/.irbrc +# -m bc mode (rational/matrix calc) +# -r load-module same as `ruby -r' +# --inspect use inspect for result output +# (default for non-bc mode) +# --noinspect does not use inspect for result output +# --noreadline does not use readline library +# (default: try to use readline) # -# 追加 private method: -# exit, quit 終了する. -# inspect(sw = nil) インスペクトモードのトグル -# trace_load(sw = nil) load/require時にrbcのfile読み込み機能を用 -# いるモードのスイッチ(デフォルトはトレース -# モード) +# additional private method (as function): +# exit, quit terminate the interpreter +# inspect_mode(sw = nil) toggle inspect mode +# trace_load(sw = nil) change trace mode for file loading using +# load/require. (default: trace-mode on) # require "e2mmap.rb" $stdout.sync = TRUE module BC_APPLICATION__ - RCS_ID='-$Header: /home/keiju/var/src/var.lib/ruby/ruby/RCS/rbc.rb,v 1.2 1997/11/27 13:46:06 keiju Exp keiju $-' + RCS_ID='-$Id: rbc.rb,v 1.8 1998/03/11 05:43:00 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 + CONFIG[:TRACE_LOAD] = FALSE + CONFIG[:RC] = TRUE + + CONFIG[:DEBUG] = FALSE while opt = ARGV.shift case opt when "-d" - $DEBUG = TRUE + CONFIG[:DEBUG] = TRUE when "-m" CONFIG[:INSPECT] = FALSE if CONFIG[:INSPECT].nil? require "mathn.rb" @@ -58,6 +58,9 @@ module BC_APPLICATION__ when "-r" opt = ARGV.shift CONFIG[:LOAD_MODULES].push opt if opt + when "-f" + opt = ARGV.shift + CONFIG[:RC] = FALSE when "--inspect" CONFIG[:INSPECT] = TRUE when "--noinspect" @@ -66,7 +69,7 @@ module BC_APPLICATION__ CONFIG[:USE_READLINE] = FALSE when /^-/ # print UnrecognizedSwitch.inspect, "\n" - BC.fail UnrecognizedSwitch, opt + BC_APPLICATION__.fail UnrecognizedSwitch, opt else CONFIG[:USE_READLINE] = FALSE $0 = opt @@ -104,7 +107,7 @@ module BC_APPLICATION__ line = line + l lex(l) if l != "\n" - print @quoted.inspect, "\n" if $DEBUG + print @quoted.inspect, "\n" if CONFIG[:DEBUG] if @ltype @io.prompt = format(PROMPTs, @indent, @ltype) next @@ -120,9 +123,9 @@ module BC_APPLICATION__ if line != "\n" begin if CONFIG[:INSPECT] - print (cont._=eval(line, bind)).inspect, "\n" + print((cont._=eval(line, bind)).inspect, "\n") else - print (cont._=eval(line, bind)), "\n" + print((cont._=eval(line, bind)), "\n") end rescue # $! = 'exception raised' unless $! @@ -182,7 +185,8 @@ module BC_APPLICATION__ "case", "class", "def", "do", "for", "if", "module", "unless", "until", "while", "begin" #, "when" ] - DEINDENT_CLAUSE = ["end"] + DEINDENT_CLAUSE = ["end" #, "when" + ] PARCENT_LTYPE = { "q" => "\'", @@ -197,7 +201,7 @@ module BC_APPLICATION__ "<" => ">", "(" => ")" } - + def lex_init() @OP = Trie.new @OP.def_rules("\0", "\004", "\032"){} @@ -211,7 +215,7 @@ module BC_APPLICATION__ identify_comment(rests) end @OP.def_rule("\n") do - print "\\n\n" if $DEBUG + print "\\n\n" if CONFIG[:DEBUG] if @lex_state == EXPR_BEG || @lex_state == EXPR_FNAME @continue = TRUE else @@ -220,9 +224,9 @@ module BC_APPLICATION__ 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("=", "==", "===", "=~", "<=>") {@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 @@ -268,10 +272,14 @@ module BC_APPLICATION__ if rests[0] =~ /[0-9]/ rests.unshift op identify_number(rests) + else + # obj.if などの対応 + identify_identifier(rests, TRUE) + @lex_state = EXPR_ARG end end @OP.def_rules("..", "...") {@lex_state = EXPR_BEG} - + lex_int2 end @@ -280,8 +288,12 @@ module BC_APPLICATION__ @lex_state = EXPR_END @indent -= 1 end - @OP.def_rule(":") {} - @OP.def_rule("::") {@lex_state = EXPR_BEG} + @OP.def_rule(":") {|op,rests| + identify_identifier(rests, TRUE) + } + @OP.def_rule("::") {|op,rests| + identify_identifier(rests, TRUE); + } @OP.def_rule("/") do |op, rests| if @lex_state == EXPR_BEG || @lex_state == EXPR_MID @@ -343,16 +355,26 @@ module BC_APPLICATION__ identify_identifier(rests) end end + @OP.def_rule("def", proc{|op, chrs| /\s/ =~ chrs[0]}) do + |op, rests| + @indent += 1 + @lex_state = EXPR_END + until rests[0] == "\n" or rests[0] == ";" + rests.shift + end + end @OP.def_rule("") do |op, rests| - printf "match: start %s: %s", op, rests.inspect if $DEBUG + printf "MATCH: start %s: %s\n", op, rests.inspect if CONFIG[: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 + printf "MATCH: end %s: %s\n", op, rests.inspect if CONFIG[:DEBUG] end + + p @OP if CONFIG[:DEBUG] end def lex(l) @@ -380,9 +402,9 @@ module BC_APPLICATION__ until chrs.empty? @space_seen = FALSE - printf "perse: %s\n", chrs.join("") if $DEBUG + printf "perse: %s\n", chrs.join("") if CONFIG[:DEBUG] @OP.match(chrs) - printf "lex_state: %s continue: %s\n", @lex_state.id2name, @continue if $DEBUG + printf "lex_state: %s continue: %s\n", @lex_state.id2name, @continue if CONFIG[:DEBUG] end end @@ -421,11 +443,11 @@ module BC_APPLICATION__ end end - def identify_identifier(chrs) + def identify_identifier(chrs, escaped = FALSE) token = "" - token.concat chrs.shift if chrs[0] =~ /[$@]/ + token.concat chrs.shift if chrs[0] =~ /[$@]/ or escaped while (ch = chrs.shift) =~ /\w|_/ - print ":", ch, ":" if $DEBUG + print ":", ch, ":" if CONFIG[:DEBUG] token.concat ch end chrs.unshift ch @@ -436,12 +458,12 @@ module BC_APPLICATION__ end # fix token - if token =~ /^[$@]/ + if token =~ /^[$@]/ or escaped @lex_state = EXPR_END return end - print token, "\n" if $DEBUG + print token, "\n" if CONFIG[:DEBUG] if state = CLAUSE_STATE_TRANS[token] if @lex_state != EXPR_BEG and token =~ /^(if|unless|while|until)/ # 修飾子 @@ -624,14 +646,9 @@ module BC_APPLICATION__ @preproc = preproc @postproc = postproc end - - def preproc(p) - @preproc = p - end - - def postproc(p) - @postproc = p - end + + attr :preproc, TRUE + attr :postproc, TRUE def search(chrs, opt = nil) return self if chrs.empty? @@ -649,10 +666,29 @@ module BC_APPLICATION__ end def create_subnode(chrs, preproc = nil, postproc = nil) + if chrs.empty? + if @postproc + p node + Trie.fail ErrNodeAlreadyExists + else + print "Warn: change abstruct node to real node\n" if CONFIG[:DEBUG] + @preproc = preproc + @postproc = postproc + end + return self + end + ch = chrs.shift if node = @Tree[ch] if chrs.empty? - Trie.fail ErrNodeAlreadyExists + if node.postproc + p node + Trie.fail ErrNodeAlreadyExists + else + print "Warn: change abstruct node to real node\n" if CONFIG[:DEBUG] + node.preproc = preproc + node.postproc = postproc + end else node.create_subnode(chrs, preproc, postproc) end @@ -669,10 +705,10 @@ module BC_APPLICATION__ end def match(chrs, op = "") - print "match: ", chrs, ":", op, "\n" if $DEBUG + print "match>: ", chrs, "op:", op, "\n" if CONFIG[:DEBUG] if chrs.empty? if @preproc.nil? || @preproc.call(op, chrs) - printf "op1: %s\n", op if $DEBUG + printf "op1: %s\n", op if CONFIG[:DEBUG] @postproc.call(op, chrs) "" else @@ -683,23 +719,23 @@ module BC_APPLICATION__ 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 + if @postproc and @preproc.nil? || @preproc.call(op, chrs) + printf "op2: %s\n", op.inspect if CONFIG[:DEBUG] + @postproc.call(op, chrs) + return "" + else + return nil + end end else + chrs.unshift ch if @postproc and @preproc.nil? || @preproc.call(op, chrs) - printf "op3: %s\n", op if $DEBUG - chrs.unshift ch + printf "op3: %s\n", op if CONFIG[:DEBUG] @postproc.call(op, chrs) return "" else - chrs.unshift ch return nil end end @@ -712,14 +748,9 @@ module BC_APPLICATION__ 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 +# print node.inspect, "\n" if CONFIG[:DEBUG] + postproc = proc if iterator? + node = create(token, preproc, postproc) end def def_rules(*tokens) @@ -731,24 +762,28 @@ module BC_APPLICATION__ end end - def preporc(token) + def preporc(token, proc) node = search(token) - node.preproc proc + node.preproc=proc end def postproc(token) - node = search(token) - node.postproc proc + node = search(token, proc) + node.postproc=proc end - def search(token, opt = nil) - @head.search(token.split(//), opt) + def search(token) + @head.search(token.split(//)) + end + + def create(token, preproc = nil, postproc = nil) + @head.create_subnode(token.split(//), preproc, postproc) 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 + printf "match end: %s:%s", ret, token.inspect if CONFIG[:DEBUG] ret end @@ -795,25 +830,26 @@ module BC_APPLICATION__ module CONTEXT def _=(value) - @_ = value + CONFIG[:_] = value + eval "_=BC_APPLICATION__::CONFIG[:_]", CONFIG[:BIND] end - def _ - @_ - end +# def _ +# eval "_", CONFIG[:BIND] +# end def quit exit end def trace_load(opt = nil) - if opt - @Trace_require = opt + if !opt.nil? + CONFIG[:TRACE_LOAD] = opt else - @Trace_require = !@Trace_require + CONFIG[:TRACE_LOAD] = !CONFIG[:TRACE_LOAD] end - print "Switch to load/require #{unless @Trace_require; ' non';end} trace mode.\n" - if @Trace_require + print "Switch to load/require #{unless CONFIG[:TRACE_LOAD]; ' non';end} trace mode.\n" + if CONFIG[:TRACE_LOAD] eval %{ class << self alias load rbc_load @@ -828,7 +864,7 @@ module BC_APPLICATION__ end } end - @Trace_require + CONFIG[:TRACE_LOAD] end alias rbc_load_org load @@ -845,17 +881,18 @@ module BC_APPLICATION__ case file_name when /\.rb$/ if load_sub(file_name) - $:.push file_name + $".push file_name return true end when /\.(so|o|sl)$/ - require_org(file_name) + rbc_require_org(file_name) end if load_sub(f = file_name + ".rb") - $:.push f + $".push f + return true end - require(file_name) + rbc_require_org(file_name) end def load_sub(fn) @@ -874,19 +911,34 @@ module BC_APPLICATION__ return false end - def inspect(opt = nil) + def inspect_mode(opt = nil) if opt CONFIG[:INSPECT] = opt else - CONFIG[:INSPECT] = !$INSPECT + CONFIG[:INSPECT] = !CONFIG[:INSPECT] end - print "Switch to#{unless $INSPECT; ' non';end} inspect mode.\n" - $INSPECT + print "Switch to#{unless CONFIG[:INSPECT]; ' non';end} inspect mode.\n" + CONFIG[:INSPECT] end - def run - CONFIG[:BIND] = proc + def run(bind) + CONFIG[:BIND] = bind + if CONFIG[:RC] + rc = File.expand_path("~/.irbrc") + if File.exists?(rc) + begin + load rc + rescue + print "load error: #{rc}\n" + print $!.type, ": ", $!, "\n" + for err in $@[0, $@.size - 2] + print "\t", err, "\n" + end + end + end + end + if CONFIG[:TRACE_LOAD] trace_load true end @@ -898,7 +950,7 @@ module BC_APPLICATION__ print $@[0], ":", $!.type, ": ", $!, "\n" end end - + if !$0.equal?(CONFIG[0]) io = FileInputMethod.new($0) elsif defined? Readline @@ -959,4 +1011,5 @@ module BC_APPLICATION__ end extend BC_APPLICATION__::CONTEXT -run{} +run(binding) + diff --git a/sample/sieve.rb b/sample/sieve.rb index 03ff8a67f4..5e9f792d81 100644 --- a/sample/sieve.rb +++ b/sample/sieve.rb @@ -1,7 +1,6 @@ # sieve of Eratosthenes sieve = [] -if ! max = ARGV.shift; max = 100; end -max = max.to_i +max = Integer(ARGV.shift || 100) print "1" for i in 2 .. max diff --git a/sample/test.rb b/sample/test.rb index 0a9d41c2ed..f28327659e 100644 --- a/sample/test.rb +++ b/sample/test.rb @@ -24,6 +24,24 @@ end # make sure conditional operators work +check "assignment" + +a=[]; a[0] ||= "bar"; +ok(a[0] == "bar") +h={}; h["foo"] ||= "bar"; +ok(h["foo"] == "bar") + +aa = 5 +aa ||= 25 +ok(aa == 5) +bb ||= 25 +ok(bb == 25) +cc &&=33 +ok(cc == nil) +cc = 5 +cc &&=44 +ok(cc == 44) + check "condition" $x = '0'; @@ -109,8 +127,8 @@ tmp.close $bad = false tmp = open("while_tmp", "r") while tmp.gets() - next if /vt100/; - $bad = 1 if /vt100/; + next if /vt100/; + $bad = 1 if /vt100/; end ok(!(!tmp.eof? || /vt100/ || $bad)) tmp.close @@ -240,6 +258,18 @@ while true end ok(!$bad) +ok(catch(:foo) { + loop do + loop do + throw :foo, true + break + end + break + ok(false) # should no reach here + end + false + }) + check "array" ok([1, 2] + [3, 4] == [1, 2, 3, 4]) ok([1, 2] * 2 == [1, 2, 1, 2]) @@ -265,11 +295,20 @@ ok($x[0] == -1 && $x[1] == 10) $x[-1, 1] = 20 ok($x[-1] == 20 && $x.pop == 20) +# array and/or +ok(([1,2,3]&[2,4,6]) == [2]) +ok(([1,2,3]|[2,4,6]) == [1,2,3,4,6]) + # compact $x = [nil, 1, nil, nil, 5, nil, nil] $x.compact! ok($x == [1, 5]) +# uniq +$x = [1, 1, 4, 2, 5, 4, 5, 1, 2] +$x.uniq! +ok($x == [1, 4, 2, 5]) + # empty? ok(!$x.empty?) $x = [] @@ -287,7 +326,8 @@ ok($x == [7,5,3,2,1]) # split test $x = "The Book of Mormon" -ok($x.split(//).reverse!.join == "nomroM fo kooB ehT") +ok($x.split(//).reverse!.join == $x.reverse) +ok($x.reverse == $x.reverse!) ok("1 byte string".split(//).reverse.join(":") == "g:n:i:r:t:s: :e:t:y:b: :1") $x = "a b c d" ok($x.split == ['a', 'b', 'c', 'd']) @@ -296,7 +336,7 @@ ok(defined? "a".chomp) ok("abc".scan(/./) == ["a", "b", "c"]) ok("1a2b3c".scan(/(\d.)/) == [["1a"], ["2b"], ["3c"]]) # non-greedy match -ok("a=12;b=22".scan(/(.*?)=(\d*?);?/) == [["a", "12"], ["b", "22"]]) +ok("a=12;b=22".scan(/(.*?)=(\d*);?/) == [["a", "12"], ["b", "22"]]) $x = [1] ok(($x * 5).join(":") == '1:1:1:1:1') @@ -374,17 +414,6 @@ tt{|i| break if i == 5} ok(i == 5) # iterator break/redo/next/retry -unless defined? loop - def loop - while true - yield - end - end - ok(false) -else - ok(true) -end - done = true loop{ break @@ -431,6 +460,76 @@ end ok($x.size == 10) ok($x == [1, 2, 3, 1, 2, 3, 4, 5, 6, 7]) +# append method to built-in class +class Array + def iter_test1 + collect{|e| [e, yield(e)]}.sort{|a,b|a[1]<=>b[1]} + end + def iter_test2 + a = collect{|e| [e, yield(e)]} + a.sort{|a,b|a[1]<=>b[1]} + end +end +$x = [[1,2],[3,4],[5,6]] +ok($x.iter_test1{|x|x} == $x.iter_test2{|x|x}) + +class IterTest + def initialize(e); @body = e; end + + def each0(&block); @body.each(&block); end + def each1(&block); @body.each { |*x| block.call(*x) } end + def each2(&block); @body.each { |*x| block.call(x) } end + def each3(&block); @body.each { |x| block.call(*x) } end + def each4(&block); @body.each { |x| block.call(x) } end + def each5; @body.each { |*x| yield(*x) } end + def each6; @body.each { |*x| yield(x) } end + def each7; @body.each { |x| yield(*x) } end + def each8; @body.each { |x| yield(x) } end +end + +IterTest.new([0]).each0 { |x| $x = x } +ok($x == 0) +IterTest.new([1]).each1 { |x| $x = x } +ok($x == 1) +IterTest.new([2]).each2 { |x| $x = x } +ok($x == [2]) +IterTest.new([3]).each3 { |x| $x = x } +ok($x == 3) +IterTest.new([4]).each4 { |x| $x = x } +ok($x == 4) +IterTest.new([5]).each5 { |x| $x = x } +ok($x == 5) +IterTest.new([6]).each6 { |x| $x = x } +ok($x == [6]) +IterTest.new([7]).each7 { |x| $x = x } +ok($x == 7) +IterTest.new([8]).each8 { |x| $x = x } +ok($x == 8) + +IterTest.new([[0]]).each0 { |x| $x = x } +ok($x == [0]) +IterTest.new([[1]]).each1 { |x| $x = x } +ok($x == 1) +IterTest.new([[2]]).each2 { |x| $x = x } +ok($x == [2]) +IterTest.new([[3]]).each3 { |x| $x = x } +ok($x == 3) +IterTest.new([[4]]).each4 { |x| $x = x } +ok($x == [4]) +IterTest.new([[5]]).each5 { |x| $x = x } +ok($x == 5) +IterTest.new([[6]]).each6 { |x| $x = x } +ok($x == [6]) +IterTest.new([[7]]).each7 { |x| $x = x } +ok($x == 7) +IterTest.new([[8]]).each8 { |x| $x = x } +ok($x == [8]) + +IterTest.new([[0,0]]).each0 { |x| $x = x } +ok($x == [0,0]) +IterTest.new([[8,8]]).each8 { |x| $x = x } +ok($x == [8,8]) + check "bignum" def fact(n) return 1 if n == 0 @@ -482,7 +581,9 @@ ok($good) $good = true; for i in 4000..4096 n1 = 1 << i; - $good = false if ((n1**2-1) / (n1+1) != (n1-1)) + if (n1**2-1) / (n1+1) != (n1-1) + $good = false + end end ok($good) @@ -491,9 +592,9 @@ check "string & char" ok("abcd" == "abcd") ok("abcd" =~ "abcd") ok("abcd" === "abcd") -ok(("abc" =~ /^$/) == false) -ok(("abc\n" =~ /^$/) == false) -ok(("abc" =~ /^d*$/) == false) +ok("abc" !~ /^$/) +ok("abc\n" !~ /^$/) +ok("abc" !~ /^d*$/) ok(("abc" =~ /d*$/) == 3) ok("" =~ /^$/) ok("\n" =~ /^$/) @@ -539,6 +640,8 @@ ok(?\M-\C-a == 129) ok("a".upcase![0] == ?A) ok("A".downcase![0] == ?a) ok("abc".tr!("a-z", "A-Z") == "ABC") +ok("aabbcccc".tr_s!("a-z", "A-Z") == "ABC") +ok("abc".tr!("0-9", "A-Z") == nil) ok("abcc".squeeze!("a-z") == "abc") ok("abcd".delete!("bc") == "ad") @@ -571,10 +674,13 @@ ok(a == 1) a, *b = 1, 2, 3 ok(a == 1 && b == [2, 3]) +a, (b, c), d = 1, [2, 3], 4 +ok(a == 1 && b == 2 && c == 3 && d == 4) + *a = 1, 2, 3 ok(a == [1, 2, 3]) -*a = 1..3 +*a = 1..3 # array conversion ok(a == [1, 2, 3]) check "call" @@ -614,14 +720,14 @@ ok($proc.call(2) == 4) ok($proc.call(3) == 6) proc{ - iii=5 # dynamic local variable + iii=5 # nested local variable $proc = proc{|i| iii = i } $proc2 = proc { - $x = iii # dynamic variables shared by procs + $x = iii # nested variables shared by procs } - # scope of dynamic variables + # scope of nested variables ok(defined?(iii)) }.call ok(!defined?(iii)) # out of scope @@ -649,9 +755,7 @@ if defined? Process.kill rescue x = $! end - ok(x && x =~ /Interrupt/) -else - ok(false) + ok(x && /Interrupt/ =~ x) end check "eval" @@ -691,8 +795,8 @@ def test_ev end $x = test_ev -ok(eval("local1", $x) == "local1") # static local var -ok(eval("local2", $x) == "local2") # dynamic local var +ok(eval("local1", $x) == "local1") # normal local var +ok(eval("local2", $x) == "local2") # nested local var $bad = true begin p eval("local1") @@ -716,6 +820,51 @@ rescue NameError # must raise error end ok(!$bad) +x = proc{} +eval "i4 = 1", x +ok(eval("i4", x) == 1) +x = proc{proc{}}.call +eval "i4 = 22", x +ok(eval("i4", x) == 22) +$x = [] +x = proc{proc{}}.call +eval "(0..9).each{|i5| $x[i5] = proc{i5*2}}", x +ok($x[4].call == 8) + +x = binding +eval "i = 1", x +ok(eval("i", x) == 1) +x = proc{binding}.call +eval "i = 22", x +ok(eval("i", x) == 22) +$x = [] +x = proc{binding}.call +eval "(0..9).each{|i5| $x[i5] = proc{i5*2}}", x +ok($x[4].call == 8) + +proc { + p = binding + eval "foo11 = 1", p + proc{foo11=22}.call + ok(eval("foo11", p) == eval("foo11")) + ok(eval("foo11") == 1) +}.call + +p1 = proc{i6 = 0; proc{i6}}.call +ok(p1.call == 0) +eval "i6=5", p1 +ok(p1.call == 5) +ok(!defined?(i6)) + +p1 = proc{i6 = 0; proc{i6}}.call +i6 = nil +ok(p1.call == 0) +eval "i6=1", p1 +ok(p1.call == 1) +eval "i6=5", p1 +ok(p1.call == 5) +ok(i6 == nil) + check "system" ok(`echo foobar` == "foobar\n") ok(`./ruby -e 'print "foobar"'` == 'foobar') @@ -766,6 +915,14 @@ ok(done) File.unlink "script_tmp" or `/bin/rm -f "script_tmp"` File.unlink "script_tmp.bak" or `/bin/rm -f "script_tmp.bak"` +$bad = false +for script in Dir["{lib,sample}/*.rb"] + unless `./ruby -c #{script}`.chomp == "Syntax OK" + $bad = true + end +end +ok(!$bad) + check "const" TEST1 = 1 TEST2 = 2 @@ -809,6 +966,11 @@ rescue ok true end +check "marshal" +$x = [1,2,3,[4,5,"foo"],{1=>"bar"},2.5,fact(30)] +$y = Marshal.dump($x) +ok($x == Marshal.load($y)) + check "pack" $format = "c2x5CCxsdila6"; diff --git a/sample/trojan.rb b/sample/trojan.rb index 2024da0908..edf8ee63ce 100644 --- a/sample/trojan.rb +++ b/sample/trojan.rb @@ -2,10 +2,10 @@ path = ENV['PATH'].split(/:/) for dir in path - if File.d(dir) + if File.directory?(dir) for f in d = Dir.open(dir) fpath = dir+"/"+f - if File.f(fpath) && (File.stat(fpath).mode & 022) != 0 + if File.file?(fpath) && (File.stat(fpath).mode & 022) != 0 printf("file %s is writable from other users\n", fpath) end end diff --git a/sample/tsvr.rb b/sample/tsvr.rb index fbc6545bb5..d6a5620d11 100644 --- a/sample/tsvr.rb +++ b/sample/tsvr.rb @@ -13,7 +13,7 @@ while TRUE ns = gs.accept print(ns, " is accepted\n") Thread.start do - s = ns # save to dynamic variable + s = ns # save to thread-local variable while s.gets s.write($_) end |