From 210367ec889f5910e270d6ea2c7ddb8a8d939e61 Mon Sep 17 00:00:00 2001 From: matz Date: Wed, 20 Jan 1999 04:59:39 +0000 Subject: This commit was generated by cvs2svn to compensate for changes in r372, which included commits to RCS files with non-trunk default branches. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@373 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- sample/fib.scm | 4 +- sample/freq.rb | 8 +- sample/from.rb | 36 +++++--- sample/mkproto.rb | 8 +- sample/observ.rb | 15 ++-- sample/occur.rb | 8 +- sample/rbc.rb | 257 ++++++++++++++++++++++++++++++++---------------------- sample/sieve.rb | 3 +- sample/test.rb | 218 +++++++++++++++++++++++++++++++++++++++------ sample/trojan.rb | 4 +- sample/tsvr.rb | 2 +- 11 files changed, 395 insertions(+), 168 deletions(-) (limited to 'sample') 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/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 -- cgit v1.2.3